Posts

Showing posts from February, 2014

xcode - How can I make SKSpriteNode positions the same for any simulator/device? -

in game, position of sknodes change when run app on virtual simulator vs on real device(my ipad). here pictures of talking about. this virtual simulator this ipad it hard see, 2 red boxes higher on ipad in simulator here how declare size , position of red boxes , green net: following code located in gamescene.swift file func loadappearance_rim1() { rim1 = skspritenode(color: uicolor.redcolor(), size: cgsizemake((frame.size.width) / 40, (frame.size.width) / 40)) rim1.position = cgpointmake(((frame.size.width) / 2.23), ((frame.size.height) / 1.33)) rim1.zposition = 1 addchild(rim1) } func loadappearance_rim2(){ rim2 = skspritenode(color: uicolor.redcolor(), size: cgsizemake((frame.size.width) / 40, (frame.size.width) / 40)) rim2.position = cgpoint(x

python - List index out of range in a random generating program -

i working on program take random words list , combine them 1 sentence keep getting error: file "test2.py", line 13, in generater print list[z+2] , indexerror: list index out of range this code: def generater(): list = ["naji", "gaming", "gameplay", "start", "stuped", "awesome", "fast", "new", "racing", "shoting", "cool", "super"] random import randint x = randint(0,11) print list[x] , y = randint(0,11) if y == x , y != 0 : print list[y-1] , else : print list[y] , z = randint(0,11) if z == x or z == y , z < 8 : print list[z+2] , elif z == x or z == y , z > 9 : print list[z-5] else : print list[z] generater() your list contains 12 items, valid index range 0 11. your rand generator returns value between 0 , 10. 10 + 2 more 11 - you're t

json - How to use `jq` to obtain the keys -

my json looks : { "20160522201409-jobsv1-1": { "vmstatedisplayname": "ready", "servers": { "20160522201409 jobs_v1 1": { "serverstatedisplayname": "ready", "creationdate": "2016-05-22t20:14:22.000+0000", "state": "ready", "provisionstatus": "pending", "serverrole": "role", "servertype": "server", "servername": "20160522201409 jobs_v1 1", "serverid": 2902 } }, "isadminnode": true, "creationdate": "2016-05-22t20:14:23.000+0000", "totalstorage": 15360, "shapeid": "ot1", "state": "ready", "vmid": 4353, "hostname": "20160522201409-jobsv1-1", "label":

c++ - QTableView doesn't show anything -

i trying prototype window qtableview . there isn't yet database behind it, there @ point. can't tableview show anything. rectangle white space. i've looked @ examples online , seem doing right, far can tell. i set qtableview object gui builder , added following code after call ui.setupui(this); // set prototype table model hold dummy data qsqltablemodel * model = new qsqltablemodel(this); model->settable("errors"); model->seteditstrategy(qsqltablemodel::onmanualsubmit); model->select(); // set header names model->setheaderdata(0, qt::horizontal, qobject::tr("error number")); model->setheaderdata(1, qt::horizontal, qobject::tr("message")); model->setheaderdata(2, qt::horizontal, qobject::tr("details")); // insert dummy record { qsqlrecord record; qsqlfield field1("errno", qvariant::int); field1.setvalue(1); record.insert(0, field1); qsqlfield field2("msg", qvariant::string);

python - Create a video of layered videos -

i'm python , opencv beginner! create video made of 3 others videos. each video moving car on black background i created video empty moment: video_summary=cv2.videowriter(video_output_path ,fourcc,video_fps ,(480,270), true) now, add videos called 0, 2 , 4 "video_a_ajouter" in video_summary. video_a_ajouter=[0,2,4] video_working=[] so, did this: for in video_a_ajouter: video_working.append(cv2.videocapture(output_directory_path+'output_tp_'+str(video_a_ajouter[0])+'.avi')) video_a_ajouter.remove(video_a_ajouter[0]) i know how put 3 videos in video_summary, considering 0 overlaps 2 , 2 overlaps 4 thank in advance !! :) i'm not sure mean "made of 3 other videos", here 2 ideas: 1) 3 videos seen 1 after in succession: if case, can check if current video finished. if isn't, add frame, else append frame next video: ret1,img1=cap1.read()//read 1st video ret2,img2=cap2.read()//2nd ret3,img3=cap3.read()

android - Check Internet during SplashScreen -

well, after splashscreen screen. app check internet connection. if there internet available, call webview . otherwise, call 1 activity of error. but how pair check internet during splashscreen? activity splash screen: public class splash extends activity{ private static int tempo_splash = 1000; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.splash); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); // para o layout preencher toda tela cel (remover barra de tit.) new timer().schedule(new timertask() { public void run() { finish(); intent intent = new intent(); intent.setclass(splash.this, mainactivity.class); //chamando classe splash e principal (main) startactivity(intent); } }, 2000); } } my class check

android - How to create "levels" in Marmalade? -

i create game marmalade, don't know how make "levels" in it. mean levels, on android screens, or activitys. for example don't know how make menu, click on button (i can make button, control touch...) , create new screen game level. on android there activitys reason, how can in marmalade? you can use marmalade's iwui api this. used creating ui of game. can either use .ui files (similar xml files in android/xib in ios) or can programmatically too. what need is, create separate ciwuielement* objects can represent complete views in game. these can called main page elements or super parent elements. can assign childs super parents, such buttons, images etc. according button clicks can add or remove these super parents iwuicontroller , change views according that. can add elements without removing previous ones, result in overlay. you might want create separate class separate super parent element. i've created base class ui , subclasses h

JavaScript - Use innerHTML as actual html instead of plain text -

when i'm trying change document.documentelement.innerhtml using innerhtml of textarea this: document.documentelement.innerhtml = document.queryselector('#mytextarea').innerhtml the innerhtml of #mytextarea not used actual html change dom, plain text. for example: if innerhtml of #mytextarea <p>a paragraph</p> . then document after loading looks like: <p>a paragraph</p> instead of a paragraph how should value inside #mytextarea used change dom? (ex. appending new elements) use .value contents of textarea without being encoded. document.getelementbyid("documentelement").innerhtml = document.queryselector('#mytextarea').value; <textarea id="mytextarea"> <p>a paragraph</p> </textarea> <div id="documentelement"> </div>

php - how to format the display of results after a sql query -

i have been trying format results being sorted first letter of surname having problems i need echo in following format <section> <div id="slider"> <div class="slider-content"> <ul> <li id="letter"><a name="letter" class="title">letter</a><ul> <li><a href="#">surname</a></li> </ul> </li> </ul> </li> </ul> </div> </div> </section> i have tried split (see code bellow) not rendering correctly <html> <head> <title>mysq

dictionary - Memory usage of Dictionaries in C# -

i have code added nested dictionary to, of following format dictionary<string, dictionary<string, dictionary<string, float>>> after doing noticed memory usage of application shot significantly. these dictionaries keyed on strings repeated, , there many of these dictionaries, on order of 10's of thousands. in order address problem hypothesized repeated strings eating significant amount of memory. solution hash strings , use integer instead (i keep 1 copy of rainbow table reverse hash when necessary) dictionary<int, dictionary<int, dictionary<int, float>>> so went memory profiler see kind of size reduction get. shock found string storage smaller in size (both normal , inclusive). this doesn't make intuitive sense me. if compiler smart enough store 1 copy of string , use reference, think reference pointer double size of int. didn't use string.intern methods don't know how have been accomplished (also string.intern

css - How to use @media min-wdth and max-width to fix the width of the containers -

i have 3 sections in webpage. when reduce window size, keeps on resizing. want stop resizing @ point contents in web page not overlap. here code: <div class="section1"> //code here </div> <div class="section2"> // code here </div> <div class="section3"> // code here. </div> here css. .section1{ width:14%; } .section2{ width:26%; left:14%; } .section3{ width: 60%; left: 40%; } i noticed @ 900px width page contents good. used statement. @media (min-width:900px) { .section1 { width: 5%; } .section2{ width: 28%; left: 5%; } .section3{ width: 67%; left: 33%; } } it still keep on resizing till 230 pixels want stop resizing @ 900 pixels. have specify width in pixels instead of percentage? you can wrap 3 div section div wrapper have predefined hardcode width of 900px. html wrapper: <div class="wrapper&q

node.js - Typescript declaration file for mongoose -

is there typescript declaration file mongoose? i've looked @ boris yankov's typed repo, there not seem one. know can d.ts file mongoose library? kind regards always. i found github project here . has mongoose typescript definitions in there.

html - Bootstrap - Using Push/Pull with col-12? -

i've discovered push/pull bootstrap, can see can re-order columns different screen sizes so:- <div class="col-md-4 col-sm-4 col-md-push-0 col-xs-push-4">1</div> <div class="col-md-4 col-sm-4 col-md-pull-0 col-xs-pull-4">2</div> <div class="col-md-4 col-sm-4">3</div> which works fine, in above example 2 comes before 1 on smaller screens. what if wanted sm columns 12? how work then? i've tried:- <div class="col-md-4 col-sm-12 col-md-push-0 col-xs-12 col-xs-push-12">1</div> <div class="col-md-4 col-sm-12 col-md-pull-0 col-xs-12 col-xs-pull-12">2</div> <div class="col-md-4 col-sm-12 col-xs-12">3</div> but 1 , 2 disappear on smaller screen sizes now? so wanting achieve:- <div class="col-sm-12">2</div> <div class="col-sm-12">1</div> <div class="col-sm-12">3</div> for sm

ios - UITableViewCell with UIWebview that adjusts height to content size -

so pulling html string down api , trying load uiwebview in uitableviewcell , content scrolls in cell. need have webview's height adjust size of content , adjust cell accordingly. found post here in swift: uitableviewcell uiwebview dynamic height , tried doing same thing having trouble because using nsmutablearray store nsnumber float , trying load in cellforrowatindexpath , heightforrowatindexpath both execute before webview delegate method gets called index out of bounds error. so far have this: @interface fgcthreaddetailtableviewcontroller () @property (copy, nonatomic) nsarray<fgcthreadmodel*>* threads; @property (copy, nonatomic) nsmutablearray* contentheights; @end @implementation fgcthreaddetailtableviewcontroller - (void)viewdidload { [super viewdidload]; [self.tableview registerclass:[fgcthreaddetailcell class] forcellreuseidentifier:@"threaddetailcell"]; self.tableview.estimatedrowheight = 100; self.tableview.rowheight = uitabl

arrays - How to achive dynamic binding with ArrayList<T> in Java? -

it looks arraylist in java not support dynamic binding. when tried following code gave compile time error. code: class value { <some variables> <some methods> } class integervalue extends value { int value; } class charactervalue extends value { char value; } class main{ arraylist<value> values = null; public static void main(string args[]) { swtich(args[1]) { case "integer": values = new arraylist<integervalue>(); break; case "character": values = new arraylist<charactervalue>(); break; default: values = new arraylist<value>(); } } } looks arraylist not support dynamic binding array does. when did value[] values = new integervalue[maxsize], did compiled creating references of superclass type. if dont know size @ beginning , want dynamic behaviour data structure (something arraylist can do) ? there other way achieve ? there oth

c# - Alternatives to nested Select in Linq -

working on clustering project, stumbled upon this, , i'm trying figure out if there's better solution 1 i've come with. problem : given list<point> points of points in r^n ( can think @ every point double array fo dimension n), double mindistance , distance func<point,point,double> dist , write linq expression returns, each point, set of other points in list closer him mindistance according dist. my solution following: var lst = points.select( x => points.where(z => dist(x, z) < mindistance) .tolist() ) .tolist(); so, after noticing that using linq not best idea, because calculate every distance twice the problem doesn't have practical use my code, if bad looking, works i have following questions: is possible translate code in query expression? , if so, how? is there better way solve in dot notation? the problem definition, want "for each point, s

jquery - Building JSON to include attributes for use in DataTables -

i've been playing jquery datatables few months , @ stage using json build tables opposed html (ridiculously quicker level of data being pulled). due age of servers , software involved i'm using vbscript (classic asp) build json calling follows: $().ready(function(){ $("#example").datatable({ "sscrollx": "90%", "sscrollxinner": "100%", "ajax":'ajax.asp?rt=test' }); }); i'm building json in ajax.asp file so response.expires=-1 requesttype=request.querystring("rt") if requesttype = "test" ajaxsql="select * table" set ajaxrs=myconn.execute(ajaxsql) ajax="{ 'data': [ " while not ajaxrs.eof ajax=ajax&"['"&ajaxrs("column1")&"', '"&ajaxrs("column2")&"', '"&ajaxrs("column3")&"'],"

Windows messages and their deterministic properties -

i'd confirm think true. when use windows sendmessage() , deterministic call in execute (will not return until message processed) opposed postmessage() non-deterministic can preempted other message happens in queue @ moment in time (in fact not executed until hits message loop). is fair assessment, or missing something? that true in-process calls. cross-process sendmessage works similar, processing of message doesn't begin until receiver process calls getmessage (or kin). your ui thread has message pump looks like: while (getmessage(&msg)) dispatchmessage(&msg); postmessage causes message put onto message queue. getmessage removes oldest message queue (fifo*). dispatchmessage causes wndproc associated message's target window called message. sendmessage bypasses chain , calls wndproc directly (more or less). a lot of standard window messages result in chain of sendmessage calls sending 1 message sends sends another. chain referred "

ios - NSUserDefaults. Retrieving incorrect values -

i saving few dictionaries in nsuserdefaults way: if ([[nsuserdefaults standarduserdefaults] objectforkey:@"event_states"] == nil) { nsdictionary *dict0 = [nsdictionary dictionarywithobjectsandkeys: @"923381dc-3dcb-46ca-a6cf-c58a7af33b89",@"guid", @"В планах",@"name", //this string returned corrupted [nsnumber numberwithint:12632256],@"color", [nsnumber numberwithint:0],@"isclosed", [nsnumber numberwithint:0],@"isfinish", nil]; // , few more dictionaries same way .... [[nsuserdefaults standarduserdefaults] setobject:@[dict0,dict1,dict2,dict3] forkey:@"event_states"]; [[nsuserdefaults standarduserdefaults] synchronize]; } nsarray *event_states = [[nsuserdefaults standarduserdefaul

javascript - How to count duplicate words in array and add a count number to EACH word? -

my goal turn ['sara', 'mike', 'sara','sara','jon'] into 'sara', 'mike', 'sara(1)','sara(2)' 'jon' ive seen solutions when counting total number of duplicates, however, couldnt find trying do.. ps. cannot use sort() names should stay in original array.. i tried using regular loop nothing worked, think map approach good, cant figure out how that. thank you! edit: i came here: function words(arr){ var result=[]; var count=0; (var i=0; i<arr.length; i++){ if (result.indexof(arr[i])==-1){ result.push(arr[i]); } else { count++; result.push(arr[i]+"("+count+")"); } } return result.join(','); } words(['sara', 'mike', 'sara','sara','jon'] ); and works except returns 'sara,mike,sara(1),sara(2),jon' instead of 'sara','mike,'sara(1)','sara(2)&

stomp - Spring Websocket url hits RequestMapping but not MessageMapping -

i'm having trouble setting websocket configuration in existing web application. @configuration @enablewebsocketmessagebroker public class websocketconfig extends abstractwebsocketmessagebrokerconfigurer{ @override public void configuremessagebroker(messagebrokerregistry config) { config.enablesimplebroker("/mobile"); config.setapplicationdestinationprefixes("/mobile-server"); config.setuserdestinationprefix("/mobile-user"); } @override public void registerstompendpoints(stompendpointregistry registry) { registry.addendpoint("/mobile-socket") .withsockjs() .setinterceptors(new httpsessionhandshakeinterceptor()); } } controller @controller public class websocketinboxcontroller{ @messagemapping("/inbox") @sendtouser("/mobile") public map<string,object> inbox( ){ map<string,object> res = new hashmap<>

javascript - how to register YUI drag event -

i've read http://yuilibrary.com/yui/docs/dd/ , still have no clue how register drag event. i'm using jsplumb.draggable make .w class divs draggable, , wanted call hander when element gets dragged. is following coding valid? jsplumb.draggable(y.all(".w")); y.all(".w").on('drag:drag', function() { alert('do here'); }); thanks, i don't think can listen drag event using jsplumb. yui has drag class 1 fires drag event. you'd create instance of class , enough make node draggable. var dd = new y.dd.drag({ node: '#foo' }); dd.on('drag:drag', function () { // }); but jsplumb creates hidden drag instance , keeps itself. there doesn't seem way retrieve drag instance. recommendation open issue in jsplumb's github asking way this.

c# - why is my startup class not the same as all the examples? -

i've volunteered code reviewer asp.net project of buddy of mine. figured c# knowledge should able figure out enough of basics though know little of how asp.net structured , built. i'm assuming tons of packages installed nuget using mvc package version 5.2.3. 1 of suggestions use di , move data stuff data project don't have depend on ef. give examples of how started researching how add di mvc 5. 2 or 3 examples found mentioned adding few lines of code startup class, method doesn't match , throwing me loop. here class in question using microsoft.owin; using owin; [assembly: owinstartupattribute(typeof(permitchecker.startup))] namespace permitchecker { public partial class startup { public void configuration(iappbuilder app) { //configureauth(app); } } } vs2015 complains partial on startup since there not multiple startup classes. compare class blog di ( blog post ) , says make configureservices method this, can s

c# 4.0 - How to call an item from a list of items in c# -

i got list this, method isn't working, appreciated. //my list of values list<string> values = new list { "$100","$300","$500"}; in button1_click method int = 2; object o = values[i];//i want have value 2 this.button1.text = convert.tostring(i); //i want button text out value values[i]. you're converting wrong item. this.button1.text = convert.tostring(i); //<---- should o change to: this.button1.text = convert.tostring(o); but shouldn't converting string object , string . could use: this.button1.text = values[i];

Java: Hit Detection improperly detecting overlap among two objects -

so have rowing game in boat object must dodge randomly placed obstacle objects using arrow keys. if boat hits 1 of obstacles, boat takes random amount of damage. boat 27x52 picture (with 2 pixels of nothing on either side code shows 2-25) , obstacles rectangles. i have hit detection working part; however, whenever boat on right side of rectangle taller wide, it'll take damage, if boat 5-10 pixels away right edge of rectangle. refer image better understanding of issue: http://imgur.com/pqdlmrl in code, create array of 15 obstacles. obstacles take parameters(color color, int damagedealt, int xpos, int ypos, int width, int height, boolean hashit). //create array of obstacles for(int x = 0; x < 15; x++) { obstacles[x] = new obstacle((new color(rand.nextint(81), rand.nextint(51), rand.nextint(51))), rand.nextint(21) + 10, rand.nextint(601), (-x * (rand.nextint(51) + 31)), (rand.nextint(31) + 5), (rand.nextint(31) + 5), false); } here hit detecti

c - Converting text to a binary file -

i need convert text file of following format binary: the first line contains number of products in inventory, following lines contains: product name '\t' product price '\t' quantity '\n' (there can more 1 \t between columns) for every product binary output file contain int representing length of product name, chars hold product name, int representing price , int representing quantity. sample input file: asus zenbook 1000 10 iphone 5 750 22 playstation 4 1000 0 i have wrote following code, , understood i'm supposed see string in plain text while integers show gibberish (in binary): int converttexttobinary(char *filename) { file *ptext, *pbinary; int size, i; char *currprodname; int currprodnamelen, currquantity, currprice; if (checkfileexists(filename) == false) { printf("- given file not exists!\n"); return error; } else ptext = fopen(filename, &q

Does anyone know where OSX stores the settings in System Preferences > Keyboard > Modifier Keys? -

Image
i'm apparently not 1 wants know ( how can change modifier keys in "system preferences > keyboard > modifier keys..." ). i've tried watching system preferences app dtruss, doesn't seem possible on 10.10.3 (which i'm on right now), , i'm not sure that @ useful if system preferences getting settings cfprefsd. watching cfprefsd dtruss doesn't seem catch relevant file access. does know of api information? in gestalt perhaps? ok - answering own question. threw little program uses kqueues watch file system changes. watched file system modifications when changed setting in system preferences, , saw: '/users/ted/library/preferences/byhost/.globalpreferences.3f1c...9c34.plist.v1ut9hp' kevent: ident=44, filter=kq_filter_vnode, flags=kq_ev_add|kq_ev_clear, fflags=kq_note_write|kq_note_child|kq_note_pdatamask so setting in ~/library/preferences/byhost/.globalpreferences.<uuid>.plist . i'm not sure uuid - opendirectory? (

How to trigger click on "Save to Google Drive" button -

how trigger "click" on save google drive button, mean, have own design "save google drive" button. there programaticly trigger open "save google drive" popups in javascript? thanks edit i want modify api https://developers.google.com/drive/v3/web/savetodrive#getting_started you can try: html: <html> <head> <title>save drive</title> </head> <body> <input type="button" id="doitbutton" value="save chat history in drive"> <input type="button" id="authorizebutton" value="authorize" onclick="checkauth()"> <script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleclientload"></script> </body> </html> js: var client_id = 'client_id'; var scopes = 'https://www.googleapis.com/auth/drive'; function handleclientload() { window.settimeo

Android getIntent() returns current activity -

i have question getintent(); makes activity(activity a) call activity(activity b). it's different package name. problem when use getintent(), return of getintent activity b. intent.getextras() null. problem? think getintent() should return activity a. it's work start activity b. activity a intent intent = new intent(); intent.setclassname(b package, b activity); intent.putextra("test", test); startactivityforresult(intent, request_ok); activity b intent intent = getintent(); log.d(tag, "" +getintent()); if(intent.getextras() != null){ string name = intent.getstringextra("test"); } thanks. activity a as public void testintentcall(view view) { intent intent = new intent(this,testintent.class); intent.putextra("test","test"); startactivity(intent); } with activity b protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); l

http - How to get the raw content of a response in requests with Python? -

trying raw data of http response content in requests in python. interested in forwarding response through channel, means ideally content should pristine possible. what way this? thanks much! if using requests.get call obtain http response, can use raw attribute of response. here code requests docs . >>> r = requests.get('https://github.com/timeline.json', stream=true) >>> r.raw <requests.packages.urllib3.response.httpresponse object @ 0x101194810> >>> r.raw.read(10) '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

c# - check if a DataGridView has a DataSource -

i have module imports excel file , display contents in datagridview object . @ same time, have module export contents of datagridview object 's datasource datatable excel file . how can check if datagridview has datasource not doing if(datagridview1.rows.count == 0){} condition. this because have noticed if user imports or open empty excel file datagridview object still display single column . this why want try , check if datagridview object has datasource im looking code if(datagridview1.datasource == true) { // datasource if found or bound } else { //do datasource not found or not bound } edit -- using code filter empty datasources: assuming that: var dtlist = new dictionary<string, datatable>() { { "datagridview1", (datatable) (datagridview1.datasource) }, { "datagridview2", (datatable) (datagridview2.datasource) }, { "datagridview3", (datatable) (datagridview3.datasource) }, { "datagridvi

update attributes - Rails common method for updating a database field -

i new rails , have task write common method update specific database field given value. , should able invoke method anywhere in app. (i understand security flaw , on.. asked anyway) in application controller tried def update_my_model_status(model,id,field, value) @model = model.find(id) @model.update(field: value) end of course doesn't work.. how achieve this? right way this? , if possible how pass model argument method? if you're using rails, why not use rails? compare update_all : mymodel.where(id: 1).update_all(banned: true) or maybe update_attribute : my_model.update_attribute(:banned, true) to: update_my_model_status(mymodel, 1, :banned, true) notice how, despite being shorter, first 2 approaches more expressive last - more obvious happening. not that, more familiar rails developer off street, while custom 1 has learning curve. this, combined added code unnecessary method adds maintenance cost of application. additionally, rails

javascript - open html with css in ms word 2010 -

how can open html file 1 http://coolwanglu.github.io/pdf2htmlex/demo/cheat.html in ms word 2010 keeping same formatting , spacing? tried taking out images , javascript did not work , left aligns text , tables gone. here version without javascript or images you can't. that file isn't html , css; contains vast quantity of sophisticated javascript code displays pdf in web page. displayed, many parts of document (including table borders , fraction bars) dynamically rendered large transparent images. there absolutely no way convert word document. it's quite possible of equations in document cannot rendered in word document @ all, manually. if want tex source document, it's available online at: https://web.cs.ship.edu/~tbriggs/cheatsheet/index.html

javascript - Pass params to function when using on() in jquery -

a senior of mine advise me write using snytax 2, have issue passing parameters. if function coloring has 2 params, how pass them in? //snytax 1 $("body").on("li","click",function(){ $(this).css({'color:red'}); }); //snytax 2 $("body").on("li","click", coloring); function coloring(param1,param2){ //what here? } you can use event.data below: sample code: $(document).ready(function() { $(".btn").on("click", { a: 1, b: 2 }, callme); }); function callme(event) { var data = event.data; alert(data.a) alert(data.b) } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn">click me!</button> in case wondering if can directly this: $(".btn").on("click", callme(a,b)); // call function when event bound. so, without cli

linux - Cannot allocate memory -

i'm using virtual machine work. i given volume capacity 32mb. according "cat /proc/meminfo", have approximately of 1.4gb memory available. more enough mounted. however, whenever mounted, automatically unmounted cannot allocate memory (as seen on below pic). tried adjust heap size result still same. please take @ pic i solved problem. assign more memory virtual machine though more sufficient hold volume capacity

jquery - Get post data using AJAX -

i'm perusing attempt learn ajax , json, , i'm having trouble finding decent resource. still have many questions i'm looking resource. my aim pull content wordpress posts. tried looking tutorials , discussions solutions found wouldn't work me or didn't like, wan't understand i'm doing wrong. i have included efforts far below, but not primary question . loaded scripts. wp_enqueue_script( 'my-ajax-request', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-request', 'myajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); javascript jquery(document).ready(function($) { $('.ajax a').click(function(event) { event.preventdefault(); var id = $(this).data('id'); $.ajax({ type: 'post', url: myajax.ajaxurl, data: {'action' : 'ajax_request', 'id': id}, d

javascript - Node JS, createServer, and the Event Loop -

behind scenes in node, how http module's createserver method (and callback) interact event loop? possible build functionality similar createserver on own in userland, or require change node's underlying system code? that is, general understanding of node's event loop event loop ticks node looks callbacks run node runs callbacks event loops ticks again, process repeats ad-infinitum what i'm still little fuzzy on how createserver fits event loop. if this var http = require('http'); // create http server , handle simple hello world message var server = http.createserver(function (request, response) { //... }); i'm telling node run callback whenever http request comes in. doesn't seem compatible event loop model understand. seems there's non-userland , non-event loop that's listening http requests, , running callback if 1 comes in. put way — if think implementing own version version of createserver , can't think

swift - Function with generic type -

i have function can calculate sum of numbers in array condition so: func sumofarraywithcondition(array: [int], filter: (element: int) -> bool) -> int { var result = 0 in 0..<array.count filter(element: array[i]) { result += array[i] } return result } now want work int, float, double type. have tried, didn't work. protocol addable { func +(lhs: self, rhs: self) -> self } extension int: addable {} extension double: addable {} extension float: addable {} func sumofarraywithcondition<t: addable>(array: [t], filter: (element: t) -> bool) -> t { var result = 0 in 0..<array.count filter(element: array[i]) { result += array[i] // <-------- error here } return result // <-------- error here } but says: binary operator '+=' cannot applied operands of type 'int' , 't' so how it. any helps appreciated. thanks. first issue compiler inferring type int

Code improvement, Python the hard way ex48 -

i completed exercise after confusion , made code complies tests. word_types = { 'verb' : ['go', 'kill', 'eat'], 'direction' : ['north', 'south', 'east', 'west'], 'noun' : ['bear', 'princess'], 'stop' : ['the','in','of'] } def scan(sentance): listy = [] counter = 0 word in sentance.split(): try: count = counter key, value in word_types.iteritems(): ind in value: if ind == word: counter += 1 listy.append((key,ind)) if count == counter: raise keyerror except keyerror: try: value = int(word) listy.append(('number',value)) except valueerror: listy.append(('error',word)) return listy the autho

Getting UnparsedFlagAccessError when trying to import glog in python -

i trying use glog in python code , when trying import, throws following error: /usr/local/lib/python2.7/dist-packages/glog.py:171: runtimewarning: trying access flag verbosity before flags parsed. raise exception in future. setlevel(flags.verbosity) file "<stdin>", line 1, in <module> file "/usr/local/lib/python2.7/dist-packages/glog.py", line 171, in <module> setlevel(flags.verbosity) file "/usr/local/lib/python2.7/dist-packages/gflags/flagvalues.py", line 390, in __getattr__ traceback.print_stack() e0602 09:45:07.674463 4695 flagvalues.py:399] trying access flag verbosity before flags parsed. traceback (most recent call last): file "/usr/local/lib/python2.7/dist-packages/gflags/flagvalues.py", line 391, in __getattr__ raise exceptions.unparsedflagaccesserror(error_message) unparsedflagaccesserror: trying access flag verbosity before flags parsed. my code follows. import gflags import glog log i have searche

ruby on rails - 'Login' form not accessing user database -

i trying build simple user authentication application. think problem 'login' form not pointing :user database. when create new user, have set auto-login. function works great, when go login same user in login form, returns error of "username null limit 1. using rails 4.2.5 . when go rails console, can see user still exists. i apologize in advance horrible coding habits, i've been teaching myself. thank in advance help. sessions controller: class sessionscontroller < applicationcontroller def new end def create user = user.find_by_username(params[:username]) if user && user.authenticate(params[:username][:password]) session[:user_id] = user.id redirect_to root_path, notice: "you logged in." else redirect_to '/login', notice: "incorrect email or password! " end end def destroy session[:user_id] = nil redirect_to root_path, notice: "logged ou

unit testing - Using Enzyme to test React components that don't use classes or IDs -

i have following in render method of 1 of components:' return <paper key={insight._id} style={styles[viewmode]}> {cardcover} <div style={styles[viewmode].content}> <div style={styles[viewmode].name} ontouchtap={_ => onclickinsight(insight._id)} > {insight.title} </div> [...] it seems since enzyme works around using selectors, best option use put classname="something" on divs, if i'm not using them css classes @ all. otherwise, have figure out how many divs within material ui's paper component, , work out overly complicated query dig x levels deep divs, clickable div want test. not mention, if happen move clickable div down or bit, breaks test though div technically still being rendered , still clickable. unless there's way? enzyme gives few options here on top of css selectors. find() using react component constructor first find paper component, , use