Posts

Showing posts from June, 2013

java - Given an unordered stream of integers maintain the ordering but remove the elements that occur exactly once in the array -

my solution: public class removeuniqueelements { public static integer[] removeunique(int[] arr){ map<integer,integer> output = new hashmap<integer,integer>(); list<integer> result = new arraylist<integer>(); for(int i=0;i<arr.length;i++){ if(output.containskey(arr[i])){ int count = output.get(arr[i]); count = count+1; output.put(arr[i],count); } else { output.put(arr[i],1); } } for(int i=0;i<arr.length;i++){ if(output.get(arr[i])!=1){ result.add(arr[i]); } } return result.toarray(new integer[result.size()]); } public static void main(string[] args){ int[] array = {1,2,3,4,2,3,4}; integer[] result = removeunique(array); system.out.println(arrays.tostring(result)); } } time complexity : o(n) s

sql server - MS SQL Identity Column Not Counting Correctly on Identity Column -

Image
this question has answer here: identity increment jumping in sql server database 6 answers i using ms sql server. please tell me why identity column in database did crazy jump in numbers when supposed auto increment 1 automatically? first off have been entering data in row row. after maybe 100 entries place them not in order sticking 101 right after 31 not in order. of sudden has jumped 290's 1400's when should still in order.... management tools still show right number of entries makes no sense how supposed counting one. please explain me? <cfif structkeyexists(form, "user_pass")> <!--- form has been submitted ---> <cffile action = "upload" filefield = "filefieldname" destination = "#expandpath("/webapps/dash/images/")#" nameconflict = "makeun

html - How to generate 'required' Attribute in GWT using UIBinder? -

expected html <input class="sth" type="input" required/> how generate using uibinder in gwt? using following , not generating required attribute <g:textbox ui:field="username"/> you cannot in uibinder standard textbox widget. if one-off situation, set in code. if use often, create own widget extending textbox , adding: public void setrequired(boolean isrequired) { if (isrequired) { getelement().setattribute("required", "required"); } } then can use in uibinder: <w:mytextbox ui:field="username" required="true"/> where w links widgets folder.

ruby on rails - Where is the Model.new method defined? -

i trying find source of models' new method. tried use source_location activerecord::base.new, , widget.new (where widget model), , do find . -name *rb -exec grep -il "def new$" {} \; inside activerecord gem directory had no luck. when ruby object instantiated via .new , runs object's initialize method. defined on class default: 1.9.3p327 :002 > activerecord::base.method(:new) => #<method: class#new> if want create custom initializer rails model, define initialize method. note there caveats this, because initialize isn't called activerecord. may better off adding after_initialize callback instead. see how find method defined @ runtime? , in ruby, what's relationship between 'new' , 'initialize'? how return nil while initializing? more helpful information finding methods defined , how new , initialize related.

ruby on rails - My database is not migrating properly to my live Heroku App (Coursework) -

i doing coursework through online bootcamp , learning ruby on rails implementing project through heroku. i have working absolutely fine in development environment. ran migrations database , pushed (to knowledge) heroku. when try run heroku run rake db:migrate command output is: running rake db:migrate on kpez-app... up, run.4076 activerecord::schemamigration load (3.5ms) select "schema_migrations".* "schema_migrations" when pull live app database missing.

javascript - In h5 page I want to open app(had schema already) when the iPhone install the app if not jump to appstore -

as said in title,i used following js code: <a href="https://itunes.apple.com/cn/app/id1111" id="openapp" style="display: none">openapp</a> <script type="text/javascript"> document.getelementbyid('openapp').onclick = function(e){ window.location.href = "haocai://"; window.settimeout(function(){ window.location.href = "itms-apps://itunes.apple.com/us/app/id11113?mt=8"; },3000) }; this code has problem, if iphone has no app, safari popup problem, can problem solved?

parse.com - Parse Cloud Function won't return response.success -

my cloud function calls web crawler i'm hosting , retrieves string back, can't response.success string app if string long (it works short strings reason). here code: parse.cloud.define("search", function(request, response){ parse.cloud.usemasterkey(); parse.cloud.httprequest({ url: 'https://xxx.herokuapp.com/', params: { keyword: request.params.searchterm }, success: function(httpresponse){ // httpresponse.text received reason // not returned response.success response.success(httpresponse.text); }, error: function(httpresponse){ response.error(httpresponse); } }); }); i've been stuck on problem several days , appreciated. i made stupid mistake, seems needed following when returning string app: response.success(json.parse(httpresponse.text)); i'm not sure why needs done longer strings , doesn't seem matter shor

Unsure of XML and XSD errors when validating -

i having trouble getting files validate. here errors getting. -errors in xml document: 9: 23 cvc-complex-type.2.4.d: invalid content found starting element 'boardrelationships'. no child element expected @ point. 25: 23 cvc-complex-type.2.4.d: invalid content found starting element 'boardrelationships'. no child element expected @ point. 40: 23 cvc-complex-type.2.4.d: invalid content found starting element 'boardrelationships'. no child element expected @ point. 54: 23 cvc-complex-type.2.4.d: invalid content found starting element 'boardrelationships'. no child element expected @ point. 67: 23 cvc-complex-type.2.4.d: invalid content found starting element 'boardrelationships'. no child element expected @ point. -errors in file xml-schema: 11: 62 s4s-elt-must-match.1: content of 'name' must match (annotation?, (simpletype | complextype)?, (unique | key | keyref)*)). problem found starting at: element

How to Intercept all Nancy requests -

i have seen post: nancy: how capture requests irrespective of verb or path , followed along on github article. but not work. have added class in project: public class mybootstrapper : nancy.defaultnancybootstrapper but class never instantiated, , github documentation not discuss in detail. what need cause bootstrapper used? i found it. there 2 ways add items pipeline. 1 deriving bootstrap class, failed me. other implementing class honored iapplicationstartup interface. worked, , here code: public class beforeallrequests : iapplicationstartup { public void initialize(ipipelines pipelines) { pipelines.beforerequest.additemtostartofpipeline(ctx => { if (ctx != null) { log.debug("request: " + ctx.request.url); } return null; }); } }

javascript - jQuery not changing value for input text with plus/minus button -

i have simple plus , minus button next input. works fine. however, it's not changing value once number set in form. causing problems since have calculator changes based on value of input. there way make jquery change actual value when plus/minus buttons used? can manually type number , works fine. i have tried using .change() , .attr('value' currentval) no luck. http://jsfiddle.net/zer00ne/v1pje44v/ you use this change var currentval = parseint($('input[name=' + fieldname + ']').val(); $('input[name=' + fieldname + ']').val(currentval + 1); $('input[name=' + fieldname + ']').val(10); $('input[name=' + fieldname + ']').val(currentval - 1); $('input[name=' + fieldname + ']').val(0); to var currentval = parseint($('.qty').val()); $('.qty').val(currentval + 1); $('.qty').val(10); $('.qty').val(currentval - 1); $('.qty').val(0); thi

java - Android: App engine NoClassDefFoundError -

i working on app uses app engine backend. following code crashes with java.lang.noclassdeffounderror: com.petfinder.backend.model.userapi.userapi$builder i stumped. have tried updating jars. still no luck. i can running on nexus 6 without error when run on other devices moto e error crashes app. testing on 4.4.4 device. userapi.builder builder = new userapi.builder(androidhttp.newcompatibletransport(), new androidjsonfactory(), null) // options running against local devappserver // - 10.0.2.2 localhost's ip address in android emulator // - turn off compression when running against local devappserver // .setrooturl("http://192.168.16.254:8080/_ah/api") .setrooturl(url) .setgoogleclientrequestinitializer(new googleclientrequestinitializer() { @override public void initialize(abstractgoogleclientrequest<?> abstractgo

oop - When creating a set (unique elements of same type) in JavaScript, what is customary to use as values for a key? -

since javascript has no straight concept of "set", way create object acts set create associative array keys elements of set , values true , e.g. function toset ( arr ) { // return set of var s = {}; arr.foreach(function (elem) { s[elem] = true; }); return s; } since true s dummy data, there better value use? maybe 1 takes 1 byte? since javascript has no straight concept of "set"... javascript have set object of es6. can read here on mdn . and, there multiple polyfills use similar in pre-es6 environments. if trying simulate set using plain javascript object, key must string have find unique representation of object can used string key. number, that's string representation of number, boolean, that's "true" or "false" . object, have create unique string represents object , if object presented again can recreate same string. there multiple possibilities how in pre-es6. es6 set can hold object direc

mysql - php mysqli insert multiple rows to 1 table and 1 row to another table -

i've been working on site. can insert players table multiple rows (based on $add-rows value). need to, also, insert events table 1 row. when submit form, inserts players fine not events this form values needed 2 queries <form id="form-add" name="form-add" method="post" enctype="multipart/form-data" action="page.php"> <input name="add-name" id="add-name" type="text" value="event"> <input name="add-start" id="add-start" type="text" value=""> <input name="add-end" id="add-end" type="text" value=""> <input name="add-loc" id="add-loc" type="text" value=""> <input name="add-rows" id="add-rows" type="text" value=""> <input name="add-submit" id="add-submit" type="submit

selenium - TestNG XML with groups and packages not working -

i working on set of selenium tests want run using testng xml. <suite name="mats"> <parameter name="browser" value="firefox" /> <parameter name="platform" value="windows" /> <test name="mats_test"> <groups> <run> <include name = "mats" /> </run> </groups> <packages> <package name="com.sel.tests.app.set1.*" /> <package name="com.sel.tests.app.set2.*" /> <package name="com.sel.tests.app.set3.*" /> </packages> </test> </suite> directly under each of packages there multiple classes @test(groups = { "mats" }) annotation on top. however, output: mats total tests run: 0, failures: 0, skips: 0 update: ok, cleaning project didn't work imported again in new

node.js - When __filename in a main script could be different from the file used in command line? -

i'm reading node.js docs __filename variable: the filename of code being executed. resolved absolute path of code file. for main program not same filename used in command line . value inside module path module file. i wonder when main program __filename might differ filename used in command line. can point out such case?

c - getopt_long() fail when starting with non option character -

this first program uses getopt_long() please excuse me if questions trivial. i having problem when first argument passed program invalid here code main int main(int argc, char * argv[]) { printf("----------------------------------------------\n\n"); int fd[128]; int fdcount=0; int c; int digit_optind =0; int verboseflag=0; //to exit specific value collected functions int overallexitstatus=0; while(1) { int this_option_optind = optind ? optind : 1; int option_index =0; static struct option long_options[] = { {"rdonly", optional_argument, 0, 'a'}, {"wronly", optional_argument, 0, 'b'}, {"command", optional_argument, 0, 'c'}, {"verbose", no_argument, 0, 'd'}, {0,0,0,0} }; c=getopt_long(argc,argv, "+", long_options, &option_index); if(c == -1) b

view - Custom Editor template based on ViewModel Dataannotation attribute MVC4 -

what want automatically add image span after input textboxes if [ required ] attribute decorates viewmodel property integer, double, string, date etc for example, viewmodel might like public class myviewmodel { [required] public string name { get; set; } } and view like @html.editorfor(model => model.name) @html.validationmessagefor(model => model.name) and output like <input id="name" class="text-box single-line" type="text" value="" name="name" data-val-required="the name field required." data-val-length-max="20" data-val-length="the field name must string maximum length of 20." data-val="true"> <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="name"></span> -- note automatically added span <span class="indicator required" style="width: 11px;"></span>

swift - How to use the delegates with NSKeyedUnarchiver? -

i using nskeyedunarchiver unarchive object , use delegates (nskeyedunarchiverdelegate), delegates not called. archiving , unarchiving working fine, delegates (unarchiver & unarchiverdidfinish) not called. can help? i have following implementation: class blobhandler: nsobject , nskeyedunarchiverdelegate{ func load() -> myobjectclass{ let data:nsdata? = getblob(); var mykeyedunarchiver:nskeyedunarchiver=nskeyedunarchiver(forreadingwithdata: data!); mykeyedunarchiver.delegate = self; let temp=mykeyedunarchiver.decodeobjectforkey("rootobject") // no delegates called if temp==nil { blobsexists=false; }else{ objectreturn = temp! as! myobjectclass; return objectreturn; } } func save1(myob

spring - Exception while executing service task in activiti,activiti engine Not able to locate class -

i developing web project using spring mvc , activiti worked fine simple user tasks, when workflow reaches service task in java method called exception thrown. project running on eclipse using tomcat7 server. org.activiti.engine.activitiillegalargumentexception: delegate expression com.nuc.service.doservice did neither resolve implementation of interface org.activiti.engine.impl.pvm.delegate.activitybehavior nor interface org.activiti.engine.delegate.javadelegate @ org.activiti.engine.impl.bpmn.behavior.servicetaskdelegateexpressionactivitybehavior.execute(servicetaskdelegateexpressionactivitybehavior.java:81) @ org.activiti.engine.impl.pvm.runtime.atomicoperationactivityexecute.execute(atomicoperationactivityexecute.java:45) @ org.activiti.engine.impl.interceptor.commandcontext.performoperation(commandcontext.java:88) @ org.activiti.engine.impl.persistence.entity.executionentity.performoperationsync(executionentity.java:532) @ org.activiti.engine.impl.persistence.entity.execution

c++ - operator = overload in template class -

im working on matrix template class, , should write "=" operator overload. im trying delete matrix appears in left side of '=', , return new 1 equals matrix appears in right side of '='. because can't delete "this" distructor, delete "manually" in function. should make new matrix, therefor make new 1 ("temp") , return it. prblem "temp" return, doesn't set in matrix appears in left side of '='. the code: matrix<int> m (3, 4); matrix<int> m2(2, 5); m2 = m; this main part. the function: template<class t> matrix<t> & matrix<t>::operator=(matrix<t>& mat) { if (this==&mat) { return *this; } (int = 0; < this->rows; i++) { delete[] this->mat[i]; } delete[] this->mat; matrix<t> * temp = new matrix<t>(mat.rows, mat.cols); (int = 0; < temp->rows; i++) (

recyclerview - Data List duplicate after go to other fragment (Sliding Tab) -

there 3 tabs : one || two || tri example : mylist = 1,2,3 issue : after go page two mylist = 1,2,3,1,2,3 (double duplicate) if go page tri mylist = 1,2,3,1,2,3,1,2,3 (triple duplicate) after looking solution on internet, found code (on adapter class) : public void swap(list<foodmodel> datas){ datas = new arraylist<>();//updated if(mlistfood !=null || mlistfood.size() !=0){ mlistfood.clear(); mlistfood.addall(datas); }else{ mlistfood = datas; } notifydatasetchanged(); } i used in onefragment.java : mlistfoodadapter = new listfoodadapter(getcontext(), mfoodmodel); mlistfoodadapter.swap(mfoodmodel); mrecyclerviewlistfood.setlayoutmanager(linearlayoutmanager); mrecyclerviewlistfood.setadapter(mlistfoodadapter); mrecyclerviewlistfood.setitemanimator(new defaultitemanimator()); but gave me nullpointer there no data show in recyclerview

java - Android telnet client through apache commons -

Image
i new android, want write telnet client app android. have written code using apache commons library telnet. able connect telnet server (for have used asyctask concept) , able read login banner after long time don't know causing that. have modified example given in apache commons work android code.i have 2 java codes in "src" folder (mainactivity.java , telnetclientexample.java). first, want login prompt , want user interact please help, in advance :) posting screen capture of getting. mainactivity.java package com.example.telnetapp; import java.io.bufferedinputstream; import java.io.inputstream; import java.io.printwriter; import android.app.activity; import android.os.asynctask; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.textview; import android.widget.toast; public class m

string - How can I use javascript to get a substring of whatever is between two parenthesis? -

i trying return "aa" using javascript. this doesn't work. var mystr = "item code alpha tengo (aa)"; var newstr = mystr.substring("(",mystr.lastindexof(")")); you can do: var mystr = 'item code alpha tengo (aa)'; mystr.replace(/^[^(]*\(|\)[^)]*$/g, ''); // aa or simpler: mystr.replace(/.*\(|\).*/g,'')

c# - asp.net MVC how to show chlid count of model -

Image
i have model named productgroup , want show count of child product group in view . that's pretty simple linq query: var productchildcounts = context.productgroups .include(pg => pg.products) .include(pg => pg.attributes) .select(pg => new { pg.title, productcount = pg.products.count(), attributecount = pg.attributes.count() }); http://www.dotnetcurry.com/showarticle.aspx?id=513

java - Android App - Unable to start activity ComponentInfo -

i created app, should receive data thingspeak channel. first used webview widget, want go further , use thingspeak java api handle data myself. in mainactivity put in code : channel channel = new channel(1234,"writekey"); try { entry entry = channel.getlastchannelentry(); } catch (unirestexception e) { e.printstacktrace(); } catch (thingspeakexception e) { e.printstacktrace(); } out.println("entry"); but following error: java.lang.runtimeexception: unable start activity componentinfo{de.babytemp.babytempapp2/de.babytemp.babytempapp2.mainactivity}: java.lang.illegalargumentexception: unknown pattern character 'x' @ android.app.activitythread.performlaunchactivity(activitythread.java:2325) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2387) @ android.app.activitythread.access$800(activitythread.java:151) @ android.app.activitythread$h.handlemessage(activitythread.java:1303) @ android.os.handler.dispatchmessag

Google cloud DNS: point naked domain to www? -

i maintain owon.ro domain uses simple app engine app. use google cloud dns. these dns records: a record ip addresses: owon.ro. -> 216.239.32.21 216.239.34.21 216.239.36.21 216.239.38.21 cname www.owon.ro. -> ghs.googlehosted.com. and mx records. the problem app reachable www subdomain , section states ip addresses should in record naked domain redirect www , doesn't work. i tried use @ wildcard record doesn't work also. if go owon.ro see 404 page www subdomain works. am missing something? thank you the dns operations suggested in step 5c ( documentation here ) not enough, need add naked domain gae config (in addition www one) - step 5d. 5. continue next step add new custom domain form, selecting custom domain want point app engine app: a. refresh console domain page list domains properly. b. if want use subdomain, such www, use second option (http://www.example.com); c. if want use naked domain, use first option spec

sql - Query Postgres table by Block Range Index (BRIN) identifier directly -

i have n client machines. want load each of machine distinct partition of brin index. that requires to: create brin predefined number of partitions - equal number of client machines send queries clients uses where on brin partitions identifier instead of filter on indexed column the main goal performance improvement when loading single table postgres distributed client machines, keeping equal number of rows between clients - or close equal if rows count not divides machines count . i can achieve maintaining new column chunks table number of buckets equal number of client machines (or use row_number() on (order datetime) % n on fly). way not efficient in timing , memory, , brin index looks nice feature speed such use cases. minimal reproducible example 3 client machines: create table bigtable (datetime timestamptz, value text); insert bigtable values ('2015-12-01 00:00:00+00'::timestamptz, 'txt1'); insert bigtable values ('2015-12-01 05:0

java - How to create custom Subscriber? -

i want display progressdialog while observable downloading file , , when it's done want send file subscriber. i tried make custom subscriber extends subscriber example: public abstract class mysubscriber<t> extends subscriber { abstract void onmessage(string message); abstract void ondownloaded(file file); } and tried subscribe it: ` mysubscriber mysubscriber = new mysubscriber() { @override public void onmessage(string message) { progessdialog.setmessage(message); } @override public void oncompleted() { } @override public void onerror(throwable e) { } @override public void onnext(object o) { } }; observable.subscribe(mysubscriber); observable : observable = observable.create(new observable.onsubscribe<void>() { @override public void call(subscr

html - Perl internal server error when using Email::valid -

i noticed i'm getting internal server error 500 when try use email::valid in cgi script. i'm newbie in this, i'm not able understand problem may be. i'm trying write simple form validator using email::valid validate email addresses, when try put line use email::valid; it gives me error. here's complete code: #!c:\xampp\perl\bin\perl.exe use email::valid; use cgi; $query = new cgi; print $query->header ( ); $nome = $query->param("nome"); $email_address = $query->param("email"); $website = $query->param("website"); $comments = $query->param("messaggio"); $nome = filter ( $nome ); unless( email::valid->address($email_address) ) { $email_address = "invalid email address"; } $website = filter ( $website ); $comments = filter ( $comments ); print "nome: $nome<br>"; print "email: $email_address<br>"; print "sito: $website<br>"; print &qu

php - Batch processing notifications of job tracking -

at moment we're using 3 nested foreach loops information run batch. i'm sure information single mysql statement joins , sub-queries. we have 30 categories 2000 users. our aim 100 categories 100000 users though foreach loops not ideal (even take minute run). circumstance: users want notified if there work available trade can in area goal: batch process (daily, weekly, etc) notifications put in outbox technology: php, mysql what have far: database: "table.notification_options" : [id][user_id][category] "table.user" : [id][user_id][method_of_contact][contact_frequency][center_of_work_area_long][center_of_work_area_lat][distance_from_center] "table.work" : [id][post_date][longitude][latitude][category] code: foreach user{ foreach category tracked{ foreach job in category posted <> $current_date-$batch_frequency{ if job inside workspace{ notify_user(job); }

haskell - testing functions that return a Maybe Monad -

say have function: safehead :: [a] -> maybe safehead [] = nothing safehead xs = $ head xs and test: describe "example.safehead" $ "returns head" $ safehead [1,2,3] `shouldbe` 1 "returns nothing empty list" $ safehead [] `shouldbe` nothing this produces: no instance (eq a0) arising use of ‘shouldbe’ type variable ‘a0’ ambiguous note: there several potential instances: instance (eq a, eq b) => eq (either b) -- defined in ‘data.either’ instance forall (k :: box) (s :: k). eq (data.proxy.proxy s) -- defined in ‘data.proxy’ instance (ghc.arr.ix i, eq e) => eq (ghc.arr.array e) -- defined in ‘ghc.arr’ ...plus 88 others in second argument of ‘($)’, namely ‘safehead [] `shouldbe` nothing’ in stmt of 'do' block: "returns nothing empty list" $ safehead [] `shouldbe` nothing in second argument of ‘($)’, namely ‘do { "returns head" $ { safehead [...] `shouldbe` 1 };