Posts

Showing posts from September, 2010

mysql - Adding form fields using javascript in a jsp program? -

basically have javascript function allows user add forms he/she wishes. have couple of input fields , have no problem adding them. here code. <script> var counter = 1; function addinput(divname){ var newdiv = document.createelement('div'); newdiv.innerhtml = "<center><br><hr width='300'>\n\ control number: <br><input type='text' name='control_number'>\n\ date of pull out: <br><br><input type='date' name='pulloutdate'>\n\ \n\item description: <br><br> <select name='des'>\n\ \n\ <% while(rselectrecord.next()){ %> <option value="<%=rselectrecord.getstring("item_code")%>"><%=rselectrecord.getstring("item_code")%></option> <% } %> </center

plot - R summarize dataframe with unique features -

Image
i have large table in following format: data <- data.frame("chrom" = c("chr1", "chr1", "chr1", "chr4", "chr4", "chr6"), "site" = c(100, 200, 400, 140, 300, 400), "heart" = c(20, 100, 0, 35, 92, 100), "brain" = c(30, 40, 55, 100, 0, 100), "liver" = c(100, 55, 20, 90, 0, 0), "lungs" = c(100, 0, 80, 40, 30, 0)) giving: > data chrom site heart brain liver lungs 1 chr1 100 20 30 100 100 2 chr1 200 100 40 55 0 3 chr1 400 0 55 20 80 4 chr4 140 35 100 90 40 5 chr4 300 92 0 0 30 6 chr6 400 100 100 0 0 i want make figure similar published figure. ( http://www.nature.com/ncomms/2015/150218/ncomms7363/fig_tab/ncomms7363_f1.html ): basically each row (based on common chrom , site), want see how many intermediate values there are. define intermediate here values between 15 ,

Read/Write Microsoft Access (.accdb) synced to Sharepoint with Ruby -

i have had success reading , writing microsoft access .accdb database using ruby, , local access database. unfortunately need able database has been uploaded , synced via sharepoint. is possible this? how username/password handled? any advice or sample code appreciated. i may misunderstanding situation, apologize in advance if case. when sync access db sharepoint, access creates sharepoint list each table. links list local access database. edit data through forms, editing data in sharepoint list. access serves proxy, , each list in sharepoint surfaced linked table in access, along connection string caches credentials. continue work access table (which sharepoint list), or bypass access altogether , work list in sharepoint directly. sharepoint has api , other techniques allow work list programmatically. if scenario, no longer need use access. ruby can work sharepoint. let me know if off track, , perhaps can still help.

c++ - How to implement unnamed parameters -

i have issue. void setname(const string&); how can implement code above? need write this.name = ... there no named variable. there & symbol. you don't need include explicit parameter names in function prototype. in fact, programmers deliberately omit them. only when define function need supply parameter name, , if refer parameter. so in header, void setname(const string&); fine. telling function takes reference string (the & denotes reference), , not return anything. but when define function, you'll need supply parameter if refer it.

Ruby hash merge by comparing a value -

i have following array of hashes [{:day=>"may 2015", :rent=>0, :bond=>0, :rentinadvance=>0}, {:day=>"may 2015", :rent=>0, :bond=>0, :rentinadvance=>450}, {:day=>"may 2015", :rent=>0, :bond=>750, :rentinadvance=>0}, {:day=>"jun 2015", :rent=>600, :bond=>0, :rentinadvance=>0}, {:day=>"jul 2015", :rent=>600, :bond=>0, :rentinadvance=>0}, {:day=>"dec 2015", :rent=>600, :bond=>0, :rentinadvance=>0}] i need merge record using day key value, expected result is [{:day=>"may 2015", :rent=>0, :bond=>750, :rentinadvance=>450}, {:day=>"jun 2015", :rent=>600, :bond=>0, :rentinadvance=>0}, {:day=>"jul 2015", :rent=>600, :bond=>0, :rentinadvance=>0}, {:day=>"dec 2015", :rent=>600, :bond=>0, :rentinadvance=>0}] thanks in advance.. tldr: data.group_by |d|

c++ - My while statement is getting infinite loop? -

#include "stdafx.h" #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; //this program let user input assignment score , see letter grade int main() { int score; cout << "input score: "; //to make while loop int x = 1; while (x == 1) { cin >> score; if (score >= 90){ cout << "\na"; break; } else if (score >= 80) { cout << "\nb"; break; } else if (score >= 70) { cout << "\nc"; break; } else if (score >= 60) { cout << "\nd"; break; } else if (score >= 0) { cout << "\nf"; break; } else cout << "\ni

python - SQLAlchemy: filtering multiple column values in a subquery -

in sql, can use in operator subquery so: select * t1 (t1.some_int, t1.some_string) in ( select id, name t2 ) but unable translate sqlalchemy query. far know, in_ method works on 1 column. there way replicate functionality in sqlalchemy? you use join instead of subquery. this: select * t1 inner join t2 on t1.some_int = t2.id , t1.some_string = t2.name and in sqlalchemy: t1: class t1(declarativebase): __tablename__ = 't1' __table_args__ = {'mysql_engine': 'innodb'} id = column(u'id', integer, primary_key=true) some_int = column('some_int', integer) some_str = column('some_str', string(45)) def __init__ (self, some_int, some_str): self.some_int = some_int self.some_str = some_str t2: class t2(declarativebase): __tablename__ = 't2' __table_args__ = {'mysql_engine': 'innodb'} id = column(u'id', integer, primary_key=true)

http - Is there a spec for nested urlencoded params[]? -

at 1 point in history, server side languages started tweaking urlencoded parameters add support submitting data arrays , key/value objects: // key/value pairs contact[name]=john contact[phone]=800-555-1234 // arrays foo[]=bar foo[]=baz i’m playing around edge cases in 1 library's nested parameter parsing, eg preservation of parameter order. there spec formalizes how server should process encoding? if not, reference implementation introduced syntax? square brackets in uris according rfc-3986 "uniform resource identifier (uri): generic syntax" using unencoded square brackets in uris isn't allowed. therefore it's not http standard. a host identified internet protocol literal address, version 6 [rfc3513] or later, distinguished enclosing ip literal within square brackets ("[" , "]"). place square bracket characters allowed in uri syntax. many programming languages using square brackets arrays, therefore guess natural

Running SQL Server 2012 Express Scalar Function in View -

my sql guru in costa rica week , have problem don't know how solve. have 4 simple tables , 1 function. simplicity sake i'll remove fields not required understand need. table1: primary_item_id, inventory_item_id table2: table2id, inventory_item_id, table3id table3: table3id, department, departmentjobtype table4: primary_item_id discrete_job the function returns jobtype of job table4's discrete_job column. what need: see inventory_item_id 's table1 . show department when jobtype table3 equal result function. the links like.. table1.inventory_item_id -> table2.inventory_item_id , table1.primary_item_id = table4.primary_item_id table2.table3id -> table3.table3id when table3.departmentjobtype = (select getjobtype_f(table4.discrete_job) i'm hoping can have , not need redesign tables. (i realize if had jobtype in table1 wouldn't need avoid changing tables as possible. awesome! other gurus! i resolved issue us

javascript - Error prerendering server of a pie chart with D3.js in svg format -

Image
i'm using library d3.js draw pie chart . this code i'm testing to create chart use prerendering server side (nodejs) using gulp, , module npm jsdom , save html file. , works. // html saving // window jsdom obj var innerhtml = window.document.documentelement.innerhtml; var parser = require('parse5').parser, parser = new parser(), dom = parser.parse(htmlstring); save(xmlserializer.serializetostring(dom)); // save file but need save in svg format , use these functions convert html xml svg. // svg saving // window jsdom obj var body = window.document.queryselector("html"); var svg = body.getelementsbytagname("svg")[0]; var svg_xml = xmlserializer.serializetostring(body); save(vkbeautify.xml(svg_xml));// save file (npm modules: vkbeautify , xmlserializer ) i have done several graphics without problems, except pie chart: html perfect, svg rendered badly. outputs: what cause? how can

postgresql - Rails with Sunspot add Child Model Attributes -

so, have been messing hours , think have tried thats been posted on issue already. first question. so, trying search models (locations) :branch_name, :branch_address1, etc child model (employees) :first_name used within model own attribute. desired effect locations (as results) return if locations employee name in search query. i'm trying achieve code this: class location < activerecord::base belongs_to :partner has_many :employees, dependent: :destroy validates_presence_of :branch_name, :branch_address1, :branch_country, :branch_zip_code accepts_nested_attributes_for :employees, allow_destroy: true, :reject_if > proc { |attributes| attributes['first_name'].blank? } searchable text :branch_name, :branch_address1, :branch_city, :branch_zip_code text :employee_attributes :first_name if :employee_attributes end end end end use parent model (partners) name but, couldn't work either. could make new column in loc

haskell - Practical use of `foldl` -

today when working on 1 little script used foldl instead of foldl' . got stack overflow , imported data.list (foldl') , happy this. , default workflow foldl . use foldl' when lazy version falls evaluate. real world haskell says should use foldl' instead of foldl in cases. foldr foldl foldl' says usually choice between foldr , foldl' . ... however, if combining function lazy in first argument, foldl may happily return result foldl' hits exception. and given example: (?) :: int -> int -> int _ ? 0 = 0 x ? y = x*y list :: [int] list = [2, 3, undefined, 5, 0] okey = foldl (?) 1 list boom = foldl' (?) 1 list well, sorry, it's rather academic, interesting academic example. asking, there example of practical use of foldl ? mean, when can't replace foldl foldl' . p. s. know, it's hard define term practical , hope understand mean. p. p. s. understand, why lazy foldl default in haskell. don'

Microsoft Interop OutLook C#- Cannot save attachments of type OLE -

i have c# program saving attachments unread emails outlook mail box folder , below line of code breaks(first line) attachment types of ole type error "outlook cannot perform action on type of attachment"(where 'it' of type mailitem ). string attachedfilename = it.attachments[i].filename; it.attachments[i].saveasfile("c:\\temp\\"+attachedfilename); i have read articles on using http://www.dimastr.com/redemption/rdomail.htm (library) overcome problem ole type attachments, apart option can make use of other .net library overcome problem? if yes, kindly share code snippet in c#. you need call iattach::openproperty(pr_attach_data_obj, iid_istorage, ...) open particular stream istorage contains data after. note stream , format specific application created ole attachment. redemption supports word pad, paint brush, excel, power point, word, open office, acrobat, bitmap, metafile, etc. formats. iattach::openproperty available in extended mapi

php - How to get image file format if it doesn't have an extension? -

i have folder of image files. of them don't have extension. need find format , attach proper extension them through php or shell programming in linux/ubuntu. can please me how it? i dont have enough reputation post comment, so... see if anything $finfo = finfo_open(fileinfo_mime_type); $mime = finfo_file($finfo, $_files['afile']['tmp_name']); this should store detected file format $mime.

ibm rad - Accessing WebSphere Application Server 8 installation folder in RAD (Rational Application Developer) -

i'm using ant build build ejb client , need installation folder path included in build.properties file creating ejb stubs. an entry in property file looks this: server.dir = c:/program files (x86)/ibm/websphere/appserver this entry includes static value server.dir property i'm looking more flexible solution (e.g. getting path system variable or that). also right value of variable on computer if installation directory different. possible achieve? thanks ideas. i'm not sure i'm following question. can see installation path in window > preferences > servers > runtime environments. variables 1 way standardize that, there 1 using templates (if plan include path in code in content assist way). instance, in java preferences (window > preferences > java) go editor > templates , add new one. approach allows export template , share peers ti imported in environments what mean "i use information in application"? mean program

python - Replace multiline text in file using regex on Linux -

i need replace multiline text in config file. can use sed (busybox v1.21.1), perl (revision 5 version 14 subversion 2) or python (2.7). the file can have 2 formats: a) "is_managed": false, "local_profile_id": 15191724, "name": "first user" }, **"session": { "restore_on_startup": 4, "restore_on_startup_migrated": true, "urls_to_restore_on_startup": [ "http://alamakota/" ] }** } or b) "is_managed": false, "local_profile_id": 15191724, "name": "first user" }, **"session": { "restore_on_startup_migrated": true, }** } i want change this: "is_managed": false, "local_profile_id": 15191724, "name": "first user" }, "session": { "restore_on_startup": 4, "

javascript - A potentially dangerous Request.Form value was detected from the client (ctl00$cphMain$txCourseDescription="...ace="'MS Sans Serif&#...") -

my screen has telrik rad popup populate on button click(btncoursedescription) . have taken label show html formated data , textbox work code behind file. when click on btncoursedescription ; telrik's popup opens , and after submit shows data on label , assign value textbox using javascript ... here javascript code... <script type="text/javascript"> function clientshow(sender, eventargs) { //$find(); var txtinput = document.getelementbyid("<%=lbcoursedescription.clientid%>"); sender.argument = txtinput.innerhtml; } function clientclose(sender, args) { if (args.get_argument() != null) { var lbinput = document.getelementbyid("<%=lbcoursedescription.clientid%>"); var txtinput = document.getelementbyid("<%=txcoursedescription.clientid%>"); lbinput.innerhtml = args.get_arg

android - Gradle with Flavors configuration -

i read lot of posts here e couldn't find way it, want define "res" debug per flavor, like: + src + main + java + res + flavor1 + release + res + debug + res + flavor2 + release + res + debug + res the reason have ic_launcher each buildtypes , , each flavor has own ic_launcher, need have de release , debug ic_launcher per flavor. is possible? it's possible following namings: flavor1release flavor1debug flavor2release flavor2debug put in every directory result folder , specific launcher icon. can switch build type , system select correct one

javascript - Hover effect only on letter (not container) -

i have huge text , trigger color change when letters hovered . means white background shouldn't trigger hover effect, black fiill of letter should trigger it. the default hover effect triggered when text container hovered : * {margin: 0;padding: 0;} p { font-size: 75vw; line-height: 100vh; text-align: center; } p:hover { color: darkorange; } <p>so</p> using text element in svg acts same way : text:hover{ fill:darkorange; } <svg viewbox="0 0 100 100"> <text x="0" y="50" font-size="70">so</text> </svg> is there way trigger hover effect when fill of letters (black parts in examples) hovered , not on containing box? you can use inkscape convert text path via path>object path or path>stroke path. once text path hover default operate on rendered parts of path. i.e. you'd need edit document itself, it's not svg directly su

android - AlertDialog customize background -

there problem styles. prepare alertdialog totaly colered in yellow without shadow. here code below: alertdialog.builder alert = new alertdialog.builder(about.this, r.style.mystyle); <style name="apptheme" parent="theme.appcompat"> <item name="android:dialogtheme">@style/mystyle.dialog</item> <style name="mystyle.dialog" parent="theme.appcompat.light.dialog"> <item name="coloraccent">@color/color_accent</item> <item name="android:windowbackground">@android:color/transparent</item> <item name="android:windowisfloating">true</item> <item name="android:windownotitle">true</item> <item name="android:windowcloseontouchoutside">false</item> any help? messsage in white color. if use alertdialog , apply custom style still display black shadow though

C doubly linked circular list insert -

doesn't insert , doesn't keep adresses of next , prev node: i'm trying read input file; can read data corectly , based on every line, creates aeronava object. seems insert doesn't work.any suggestions? void insertfav_av(favnode*list, aeronava *av){ favnode* nn = (favnode*)malloc(sizeof(favnode)); //first = list; nn->infoutil = (aeronava*)malloc(sizeof(aeronava)); nn->infoutil->idaeronava = (char*)malloc(strlen(av->idaeronava) + 1); //strcpy(nn->infoutil->idaeronava, av->idaeronava); nn->infoutil = av; if (first == null){ nn->prev = nn->next = nn; first = nn; } else{ list = first; while (list->next != first){ list = list->next; } nn->prev = list; list->next = nn; nn->next = first; } } struct aeronava{ char* idaeronava; ti

ruby - How to represent serialized fields in ActiveRecord::Base in ActiveRecord:Migration (Rails 2.3.16) -

i'm new in rails. read rencently how serialize array of string example store in database. class fle < activerecord::base serialze :etat_fle end but don't know how represent serialized field in corresponding activerecord::migration have idea ? store text . if table created - add_column :table, :column, :text

Query to calculate sum of distance (longitude, latitude) in consecutive rows in Mysql -

i new sql , stuck. trying calculate (yearly) sum of distance each user has traveled. have table (lets call dist_table) following structure: rowid user_name date lat long 1 maria 2005-01-01 51.555 5.014 2 maria 2005-01-01 51.437 5.474 3 peter 2005-02-03 51.437 5.474 4 john 2005-02-03 51.858 5.864 5 maria 2005-02-04 51.858 5.864 6 john 2005-02-03 51.437 5.474 7 john 2006-02-04 0 0 8 john 2006-02-04 51.858 5.864 9 john 2006-02-04 51.858 5.864 10 john 2006-02-04 51.437 5.474 this intermediate step in calculation (just clarify mean): rowid user_name date lat long distance 1 maria 2005-01-01 51.555 5.014 0 2 maria 2005-01-01 51.437

java - how to store string data into integer array from sqlite for android -

i want convert sqlite data integer array. public integer[] getch() { sqlitedatabase database = this.getreadabledatabase(); cursor cursor = database.rawquery("select sum(sales) sales group outlet_code order ordered_date", null); // string[] array = new string[crs.getcount()]; int columnindex = 3; integer[] in = new integer[cursor.getcount()]; if (cursor.movetofirst()) { (int = 0; < cursor.getcount(); i++) { in[i] = cursor.getint(columnindex); cursor.movetonext(); } } cursor.close(); return in; } i need result in following format: int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800, 0,0,0,0}; integer[] income = controller.getch(); i'm getting error : couldn't read row 0, col 3 cursorwindow. make sure cursor initialized correctly before accessing data it why using columnindex = 3

javascript - How to print out all attributes of an object -

this question has answer here: get objects (dom or otherwise) using javascript 1 answer i'm using d3 , when hover on node want text box appear nodes attributes written it. have made text box , im able write attributes know text box : function onhover(){ d3.selectall("#nodeattributes") .text(function() { return (d.type); }) //random attribute know ; } this called on 'mouseover' on node. if dont know attributes node has ? how can loop through attributes , write of them text box. data looks similar : nodes: [ { "type": "o", "name": "fred", "age": "16", "class": "maths", . . . . }, what want outputted text : type: o name: fred age: 16 class: maths i'm unsure h

javascript - jquery click does not work although I've enclosed in document.ready -

jquery click not working. although, issue has been discussed lot, can not find answer solves problem me. have enclosed jquery code in $(document).ready vainly. here html <!doctype html> <html> <head> <title>tic tac toe</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="triliza01.css" type="text/css" /> <script type="text/javascript" src="jquery.1.11.2.js"></script> <script type="text/javascript" src="script.js"></script> <script type="text/javascript"> $(document).ready(function() { p1=new lplayer("x.png"); p2=new lplayer("o.jpg"); p1.setoponent(p2); p2.setoponent(p1); thewinner=play(p1); }); //

javascript - Generate a fingerprint (unique id) for each element in html -

i trying generate fingerprint each element in html body. my first attempt looping elements in body , assigning id it. for taking input tag assign var = 0; $.each($('#container').find("input"), function(key, value) { $(this).attr("data-index", this.tagname.tolowercase() + "-" + i); }); but if add input tag dynamically in between 2 input tags, have re-assign data-index, not want do. also not want keep track of last added id. for second attempt thinking of generating fingerprint depending on input tag attributes, fingerprint unique page. note that, time if page opened, same finger print value should generated. is way correct? if yes then, how generate fingerprint? if no then, please can 1 redirect me other way of doing it? any appreciated. thank in advance. i going suggest guid (globally unique identifier), said wanted same value every time page generated. since that's case, suggest sort of "unique ran

c# - How to avoid complete refresh on button click in custom tab of Outllook Plugin -

This summary is not available. Please click here to view the post.

python - TypeError in SOAP Request (using pysimplesoap) -

i'm trying relevant information soap service dutch government land register ( wsdl here ) pysimplesoap . far managed connect , request information specific property following code: from pysimplesoap.client import soapclient client = soapclient(wsdl='http://www1.kadaster.nl/1/schemas/kik-inzage/20141101/verzoektotinformatie-2.1.wsdl', username='xxx', password='xxx', trace=true) response = client.verzoektotinformatie( aanvraag={ 'berichtversie': '4.7', # refers schema version 'klantreferentie': klantreferentie, # reference can set ourselves. 'productaanduiding': '1185', # four-digit code referring whether response should in "xml" (1185), "pdf" (1191) or "xml , pdf" (1057). 'ingang': { 'object': { 'imkad_kadastraleaanduiding': { 'gemeente': 'arnhem ac', # muni

java - how to move multi-module projects to maven -

we attempting move several multi-module applications maven, , having problems. each module stored independently in cvs. have manifest files each application, list modules required application (and optionally version). not modules in maven form. so application 'customer_care' has following manifest: <manifest> <module id="my_api"/> <module id="custcare_webapp"/> </manifest> similarly, application 'core batch' has manifest this: <manifest> <module id="my_api"/> <module id="core"/> <module id="batch"/><!--nb non-maven module --> </manifest> i have started 'mavenising' our code, my_api project has pom.xml dependencies defined, including 1 on internal code module 'central_config'. have specified version release. the problem this works fine, until need create frozen manifest. can specify version each module: <mani

node.js - npm windows cannot install bower, no errors -

i running command on windows cmd: >npm install -g bower but hangs on rotating slash , rotates infinite without result. proxy configured correctly , i can install other npm modules no problem . tried online suggestion no success. no errors displayed on console, there method run nmp install in debug mode? idea? edit: thanks @davin tryon hanging on this: npm verb addtmptarball have metadata; skipping unpack handlebars@1.3.0 npm verb afteradd c:\users\user\appdata\roaming\npm-cache\handlebars\1.3.0\package\package.json not in flight; writing npm verb afteradd c:\users\user\appdata\roaming\npm-cache\handlebars\1.3.0\package\package.json written -

How to provide a ymal file to django-rest-swagger? -

using django-rest-swagger django-rest-framework documenting api calls. have written documentation of view inside view docstring in yaml syntax. want place these docstrings views separate yaml file. possible use separate yaml file documentation ?

swift - iOS: Go back to previous view -

i have 2 views in story board: [view1] -> [navigation controller] -> [view2] to go view1(has tableview) view 2, on click of row on view1: self.performseguewithidentifier("showmyview2", sender:self) this works. now have button on view 2, when clicked should take me previous view i.e view 1. i tried this: navigationcontroller!.popviewcontrolleranimated(true) but not work. how go first view? first add navigation controller first view1 through storyboard.(editor->embed navigation controller), if navigation not present. or self.dismissviewcontrolleranimated(true, completion: nil); call function , try instead of navigation popviewcontroller

java - tomcat UnsupportedClassVersionError -

i have bitnami tomcat 7 installation (apache + tomcat + mysql) on mac, uses java 1.7 76. mac uses java 1.8 runtime. when deploy project (made in intellij on same mac) tomcat , try run unsupportedclassversionerror. not matter version of jdk use compile project (i've tried apple 1.6, oracle 1.7 , oracle 1.8 versions) , not seem te matter language level set. way app running using language level 1.3 (using jdk 1.7 of 1.8) to fix problem have set tomcat run on 1.8 jdk installed on mac, configured intellij use same jdk. works fine. my question: need compile using exact same version of jdk java version runs tomcat? or doing wrong. the complete error: (sometimes shows unsupportedclassversionerror: minor version) http status 500 - javax.servlet.servletexception: java.lang.unsupportedclassversionerror: test/testclass type exception report message javax.servlet.servletexception: java.lang.unsupportedclassversionerror: test/testclass description server encountered internal error

integer - Python typecasting string to int fails -

i error when try simple typecasting string integer in python (2.7): year = device.time[year_pos:].strip() # '1993' t = int(year) # throws exception: "unboundlocalerror: local variable 'int' referenced before assignment" why? :) the unboundlocalerror sounds if you've assigned name int in other scope in code (i.e., code throwing exception inside function, , you've used int name store variable in global code, or somewhere else). there's a blog post unboundlocalerror can read more kind of problem, issue, i'd recommend not using builtin names store variables.

constructor - How to call static variable from another form c#? -

i have mdi parent , few child forms. want declare static variable in mdi parent form, , 'call' child forms. in particulary want start 0 (zero) , eventualy give value 1 or 2. this way declared static variable, , want know code ok, , if not wrong. static class permission { static int role; public static int getpermission() { role = 0; return (role); } } the second , more important question how call static variable inside child form(s). code should write , ? thank all. you call via permission.getpermission(); anywhere within same project (as it's defaulted internal class).

r - maximum number of unique elements occurring for a given value in matrix -

suppose got data frame this: > id = c(1,1,1,1,1,2,2,2,3,3) > type = c("a","a","b","c","a","a","b","c","a","c") > data = data.frame(id,type) > data id type 1 1 2 1 3 1 b 4 1 c 5 1 6 2 7 2 b 8 2 c 9 3 10 3 c i find out maximum number of unique types per id, not maximum among values. there 1 liner in base package this? thank you. you can try library(data.table)#v1.9.5+ setdt(data)[, list(type=uniquen(type)) ,id] or library(dplyr) data %>% group_by(id) %>% summarise(type= n_distinct(type)) or using base r aggregate(type~id, data, fun=function(x) length(unique(x)))

python - TkInter: drawing on wrong positions -

i load picture on canvas. large picture need scroll vertically , horizontally able see it. let user drawn random curves/lines using mouse pointer on image. everything ok except when scroll horizontally or vertically try draw see curves not drawn mouse points in other place. how can resolve problem ? here code: import pil.image import pil.imagetk tkinter import * import numpy np import cv2 class exampleapp(frame): def __init__(self,master): frame.__init__(self,master=none) self.x = self.y = 0 self.imcv=none self.canvas=canvas(self,width=600,height=600) self.b1="up" self.liste=[] self.xold=none self.yold=none def dessiner(self): # load imge , allow user scroll if large. self.canvas.bind("<motion>",self.motion) self.canvas.bind("<buttonpress-1>",self.b1down) self.canvas.bind("<buttonrelease-1>",self.b1up) self

javascript - How can I simulate a timeout event in a XHR using jasmine? -

i'm testing function makes ajax requests, allowing retries when network not working or there timeouts because connection unstable (i'm thinking mobile devices). i'm sure works because i've used integrated other code, want have proper test. however haven't been able create unit test ensure formally. i'm using jasmine 2.3 along karma , here code far: var retries=2; var timeout=1000; function dorequest(method, url, successfn, errorfn, body, retries) { var request = new xmlhttprequest(); retries = retries === undefined ? retries : retries; request.open(method, url); request.setrequestheader('accept', 'application/json'); request.setrequestheader('content-type', 'application/json'); request.onload = function () { if (request.status < 300 && request.status >= 200) { successfn(json.parse(request.responsetext)); } else { if (errorfn) {

knockout.js - Knockout js $root $parent keyword -

i learning knockout js. reading many article , code various source. got small code knockout js. have confusion understand few area in code. highlight , 1 please me understand. here full code html <ul data-bind="foreach: {data: links, afteradd: $root.fadein, afterremove: $root.fadeout}"> <li> <select> <option>homepege</option> <option>facebook</option> </select> <input type="text" /> <button class="close" data-bind="click: $root.removelink">&times;</button> </li> </ul> <a href="#" data-bind="click: addlink">add link</a> knockoutjs function link(id, url) { var self = this; self.id = id; self.url = url; } function venuecreateviewmodel() { var self = this; self.links = ko.observablearray([new link("", "")]); //self.li

How to use geocoding with codeigniter? At the moment I'm using Biostall's Google Maps v3 API -

i want save postal address database co-ordinates guys have idea of how codeigniter , geocoding? public function save() { $postal = ""; $orgname= ($this->input->post('inputname')); $category= ($this->input->post('category')); $streetno= ($this->input->post('streetno')); $streetname= ($this->input->post('streetname')); $suburb= ($this->input->post('suburb')); $state= ($this->input->post('state')); $postcode= ($this->input->post('postcode')); } $postal = $streetno.' '.$streetname.' '.$suburb.' '.$state.' '.$postcode.' australia'; $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address=$postal&sensor=false'); $output= json_decode($geocode); $lat = $output->results[0]->geometry->location->lat; $long = $output->results[0]->geometry->location->lng;

Avro Namespace Error -

i have question. made following avro schema: { "namespace": "foo", "fields": [ { "type": [ "string", "null" ], "name": "narf" }, { "namespace": "foo.run", "fields": [ { "type": [ "string", "null" ], "name": "baz" } ], "type": "record", "name": "foo" } ], "type": "record", "name": "run" } when try compile following error: /usr/bin/python3.4 /home/marius/pycharmprojects/av

sql server - T sql order by 2 rows according to different dates -

i have table called " customers " customers table has below columns companyname varchar(100) productname varchar(100) createddate datetime salesprice money i have below data in customer table companyname (column) - productname (column) - createddate (column) - salesprice (column) b 2015-01-02 00:00:00.000 419,10 c d 2014-04-20 00:00:00.000 30,10 b 2014-01-02 00:00:00.000 60,00 c d 2015-04-20 00:00:00.000 540,00 i want select data below. need order createddate less more like createddate 2014 createddate 2015 createddate 2014 createddate 2015 result must below (2014-2015 ordering) a b 2014-01-02 00:00:00.000 60,00 (this 2014) b 2015-01-02 00:00:00.000 419,10

Python for loop single liner for concatenating 2 strings -

i have implement below pseudo code in python. dict = {} list1 = [1,2,3,4,5,6] list2 = [2,4,5,7,8] dict['msg'] = "list 2 items not in list 1 : " x in list 2: if x in list1: dict['msg'] += x <write in log : dict['msg']> if use value of msg list dict['msg'] = ["list 2 items not in list 1 : "] i can append values in single liner as [dict['msg'].append(x) x in l2 if x not in l1] but result on output page msg : [ "list 2 items not in list 1 :", 7, 8 ] i want result in single line as msg : list 2 items not in list 1 : 7,8 how can achieve that? not sure why trying use dict here in first place. did same string , list. while printing convert list string. list1 = [1,2,3,4,5,6] list2 = [2,4,5,7,8] msg = "list 2 items not in list 1 : " exclusion = [ str(i) in list2 if not in list1 ] print msg, ', '.join(x) output: list 2 items no