Posts

Showing posts from August, 2011

swift - odd numbers for operator precedence levels -

just curious..is there particular reason (historical or sort) why swift uses numbers 160 90 express default precedence levels of operators. thanks according apple's operation declaration documentation the precedence level can whole number (decimal integer) 0 255 although precedence level specific number, significant relative operator. the simple answer 90 160 fall near center of 0 255 range. now if check of apple's binary expressions documentation , see default operators range precedence of 90 precedence of 160, stated in question. range of 70 , because precedence values relative each other, starting/ending point range chosen. however, if made default values 0 70 or 185 255 when user created custom operator, not give lower precedence 0 or higher precedence 255, causing operator equal precedence of assignment operators or exponentiative operators respectively. therefore, logical thing start range in middle of 0 255 range , rather set default

c# - How do you XAML bind data from a related table into a datagrid column? -

a stack overflow user @jtk posted question here wpf/dataset: how xaml bind data related table datagrid column? no answer found there posting here. @highcore commented use ef. using ef , facing same issue. i have table called delivery has foreign key columns transporter_id, pump_id. columns refers other tables transporter table has 2 columns (transporter_id , transporter_name) how display actual name rather id column in gui? need update them gui. how achieve update , delete?

c# - Highlighting keywords in a richtextbox in WPF -

i'm making program needs through paragraph of text , find how many times keyword/keywords appear. has highlight each of these key words in text. i have managed make interface , can track how many times word appears stuck how highlight keywords appear. post code below, appreciated on how search , highlight text inside richtextbox. since in wpf obvious richtextbox.find() not avaliable use. class textanalyser { public int findnumberofoccurances(list<string> keywords, string email) { int occurances = 0; foreach (string keyword in keywords) { occurances += email.toupper().split(new string[] { keyword.toupper() }, stringsplitoptions.none).count() - 1; } return occurances; } public void turntextred(list<string> keywords, string email, richtextbox textbox) { foreach(string keyword in keywords) { } } public list<string> converttexttolist(string text) {

c# - DatePicker Styling in Windows Phone 8.1 -

i require use date picker windows phone 8.1 project. need apply customs styles such changing border, background , display date. i tried using dayformat, monthformat properties in xaml found/realized ignored on phone platform. how should go this? example need display date "23 march 2015" in date picker display. provide gray background , remove border.

How can I use Qt to encrypt/decrypte/play a video? -

i looking way encrypt video file , use decrypt ram , play directly. setmedia takes qiodevice second argument: #include <qmediaplayer> #include <qapplication> #include <qfile> int main(int argc, char ** argv) { qapplication app(argc,argv); qstring filename = app.arguments().at(1); qfile io(filename); io.open(qfile::readonly); qmediaplayer player; player.setmedia(qurl("test.mp3"), &io); player.play(); return app.exec(); } but in case really mean qdatastream: qdatastream buffered io, qiodevice direct io, they're not compatible, have double buffer this: #include <qmediaplayer> #include <qapplication> #include <qfile> #include <qbuffer> #include <qdatastream> int main(int argc, char ** argv) { qapplication app(argc,argv); qstring filename = app.arguments().at(1); // our double buffer qbytearray bufferspace; // our strea

sqlite3 - SQL foreign key mutex -

i not know know how name question because i'm still learning sql. use sqlite3 simple tests , problem following: i have 2 tables primary key. first table auto increments key on insert , second references key. let's inserted first table , after insert second table previous inserted key. have foreign key constraint. works let's before start insert second table thread deletes key first table , inserts key. have same primary key integer value (i've read in sqlite documentation). data inconsistent. what solution case? wrapping 2 inserts in transaction here? if you've created foreign key, insert fail error if key didn't exist in first table. that's point of creating fk relationships: ensures data remains consistent. similarly, if insert rows both tables , try delete row 'parent' table, throw error unless you've set cascading deletes, delete related rows in second, 'child', table. either way, consistency preserved.

ios - Xcode Change View when app is in the backgorund -

i'm building app "locked" folder (locked view) inside of it, , wanted know how can change view when app in background. want every time user press home button, app return "asking password" view. my problem dont know how segue view through didenterbackground method in appdelegate thanks help! you can not customize home button. when user presses home button inside app, go home screen (springboard). there no way change public apis. if somehow manage achieve goal, app not accepted itunes store. , don't know of private apis allow this. don't think possible on non-jailbroken device. may possible on jailbroken device if app has root powers.

Any way to convert Realm database file in to sqlite? -

i have realm database (.realm) existing application, has more 400k records. i dug head in more 3-4 hours, couldn't find fruitful results towards converting .realm file in sqlite file. any data conversion far has been done manually. people have converted core data realm grabbing objects core data , saving them realm. i imagine best bet similar here. grab each object realm , convert tables/rows/and columns in sqlite. can take file anywhere.

xcode6 - index.io.bundle not found while using iOS simulator to run first React Native app -

following getting started documentation react native , html page red background containing <p>the requested url /index.ios.bundle not found on server.</p> rendered when hitting cmd+r run first app. why happening when expected result should homepage rendered index.ios.js ? i had program listening port 8081 used localhost serve bundle ( /index.ios.bundle ), hence had stop program listening port 8081 in order have react packager working properly. i figure program listening using following command: lsof -n -i4tcp:8081 | grep listen

algorithm - Is it possible to search a node/element in a Heap Binary Tree and display it's children/child? -

it's not assignment question, started learning heap , heapsort in c++ language , i'd know if possible. of course. given node n's children @ 2n , 2n+1. same applies them, , children until reach end of heap.

bluetooth lowenergy - On Android 5.0 is it acceptable to continuously scan for BLE advertisements? -

suppose need detect ble advert transmitted @ 1 hz 60 seconds, , don't know when in day be. need scan continuously. the official docs say because scanning battery-intensive, should observe following guidelines: as find desired device, stop scanning. never scan on loop, ... but excludes use case. the latest ble chips (e.g. cc2560) use 5 ma while scanning, assume reduced on duty cycle when using scan_mode_low_power . question is, if use mode, ok scan 24/7 (and inform user)? also how ios ibeacons? it sounds stuck having listen continuously satisfy requirements. not ideal power consumption reasons, have indicated. whether ok depends on how being used. specific application known user base needs functionality , knows power hogging behavior? if so, it's ok. general users? no, not ok. my understanding ibeacon transmits every x seconds. receiver hear ibeacons in area, needs listen x seconds. in design, both beacons , receivers can limit power

ios - How do I add didSet to view property of UIViewController? -

in uiviewcontroller , add code view property set: var view:uiview! { didset { //(view myview).delegate ... } } obviously, doesn't work because cannot override variable of super class. is there workaround achieve want? the view set once, , @ time viewdidload called. go flow , override viewdidload , set delegate there.

ios - Xcode not replacing Core Data managed objects -

in xcode when chose "create nsmanagedobject subclass..." , selected "replace" when "the following files exist , replaced:" prompted, xcode did not replace managed objects files @ all. ended manually deleting files before trying create managed objects files again. any suggestions have missed? have tried cleaning build? product-> clean

JavaScript/jQuery: Show DIV until user stops typing in Textbox -

i use few textboxes on website (input type=text) , have 1 div, hidden (display: none). now i'd user enter text in 1 of textboxes , @ moment, div should appear few seconds , hide, when user stops adding text. div should wait until user stops hovering div. tried hard couldn't done correctly. here jsfiddle-example show mean: var infoboxhovered = false; $(".textbox1").on("input", function() { $(".infobox").fadein(); settimeout(function () { $(".infobox").fadeout(); }, 3000); }); $(".textbox2").on("input", function() { $(".infobox").fadein(); if (!infoboxhovered){ settimeout(function () { $(".infobox").fadeout(); }, 3000); } }); $(".infobox").mouseenter(function(){ infoboxhovered = true; }) $(".infobox").mouseleave(function(){ infoboxhovered = false; }) // - - - - - - - - -

python - facebook page info using Graph Api 2.2 -

i have unique id of 1000 facebook pages inside google spreadsheet . want crawl pages info (likes, email etc) should do? cannot run search query in browser , run script. plz detailed possible. thank u :) i tried make python script works 1st entry only. import urllib url2 import json f=open('ids.txt') in f: url="http://graph.facebook.com/"+str(int(i))+"?fields=likes" data = url2.urlopen(url).read() print data data2=json.loads(data) print "number of likes on page id "+str(data2["id"])+" has "+str(data2["likes"])+" likes !" f.close() the ids.txt file contains id of facebook pages. 1 493343230696447 2 1767379894975 3 122116091270024 4 545044065615713 a file object line iterator, not word iterator. need change: for in f: url="http://graph.facebook.com/"+str(int(i))+"?fields=likes" to: for in f: # holds line, not index

Android Studio Start Failed - ClassNotFoundException: com.intellij.ide.plugins.PluginManager -

after installing android studio on new win8.1x64 machine, whenever try launch classnotfoundexception: com.intellij.ide.plugins.pluginmanager , studio not start. have tried unzipping instead of installing, restarting computer several times, cleaning android studio related settings , files, still no result. i have installed latest jdk , sdk. java_home variable set well. idea going on? it's driving me nuts already. appreciate help! here 3 different errors randomly come when try launch android studio. java.lang.classnotfoundexception: com.intellij.ide.plugins.pluginmanager @ com.intellij.util.lang.urlclassloader.findclass(urlclassloader.java:148) @ java.lang.classloader.loadclass(classloader.java:424) @ java.lang.classloader.loadclass(classloader.java:357) @ java.lang.class.forname0(native method) @ java.lang.class.forname(class.java:348) @ com.intellij.ide.bootstrap.main(bootstrap.java:37) @ com.intellij.idea.main.main(main.java:84) . java.lang.noclassdeffounderror: co

c# - How do I write to specific cells in Excel? -

how write specific cells in excel? this works writing cells have titles "id" , "name" in first row. string stsheetname = "sheet1"; string sql = "insert [" + stsheetname + "$] (id,name) values('5','e')"; mycommand.commandtext = sql; mycommand.executenonquery(); this not work: string sql = "insert [" + stsheetname + "$a2:b2] set a2 = '5', b2 = 'e'"; i found problem. (oledbconnection) hdr=yes must hdr=no. following work. string sql = "update [" + stsheetname + "$b2:b2] set f1='e'";

javascript - npm WARN package.json CrackingJS@0.0.1 No repository field -

i trying support how crack interview repository i trying crack interviews js position they using mocha , chai, trying commit code in js i trying execute below steps failing @ below step, npm install git clone https://github.com/gaylemcd/ctci.git cd ctci/javascript npm install npm install -g mocha mocha --recursive i getting below error i have installed node.js after tried npm install in ctci folder of javascript providing link screensshot show node installed , kept ctci https://drive.google.com/file/d/0b3ibjkenge7rmgluywzua2lzy3c/view?usp=sharing anis-macbook-pro:javascript raj$ npm install npm warn package.json crackingjs@0.0.1 no repository field. that warning, not error. pointing out package.json not contain "repository" field, recommended field have convenience. can safely ignore warnings, ones one.

Has SQL changed very much from 2011 -

i considering purchasing sql book, all-in-one dummies , written in 2011. how has sql changed since 2011, , changes significant enough pointless buy because outdated? the table of contents divides sql all-in-one dummies 8 "books." beginner user of mysql, need focus on books 1 through 3, , possibly book 5. news of content in these particular books material not have changed since book published in 2011. book should fine particular case. by way, can same information free internet. here 2 great online tutorials using sql: http://www.tutorialspoint.com/mysql/ - specific mysql http://www.w3schools.com/sql/ - general sql tutorial , reference

Get list "What to watch" video on Youtube using GTLServiceYoutube v3 on iOS -

i'm making ios app allows users sign in youtube , videos on it. there's section called "what watch". how can use gtlserviceyoutube class , gtlqueryyoutube videos on section below code allows list uploaded videos, don't find way list of watch videos gtlserviceyoutube *service = [[gtlserviceyoutube alloc] init]; service.apikey = api_key; gtlqueryyoutube *query = [gtlqueryyoutube queryforplaylistitemslistwithpart:@"id,snippet"]; query.playlistid = uploads_list_id; query.maxresults = max_results; [service executequery:query completionhandler:^(gtlserviceticket *ticket, id object, nserror *error) { if (!error) { gtlyoutubeplaylistitemlistresponse *playlistitems = object; (gtlyoutubeplaylistitem *playlistitem in playlistitems) { [self.identifiers addobject:playlistitem.snippet.resourceid.json[@"videoid"]]; } [self getvideos]; }else { nslog(@"%@", error);

Convert array to customized format using php -

i have code count frequency of alphabet in string. . code : <?php $str = "iamtheone"; $freq_count = array(); ($i = 0; $i < strlen($str); $i++) { $index = $str[$i]; $freq_count[$index]++; foreach (range('a', 'z') $char) { //echo "<pre>".$key . " " . $char."</pre>"; $index = $char; if (isset($freq_count[$index])) { } else { $freq_count[$index] = "0"; } } } echo "<pre>"; print_r($freq_count); echo "</pre>"; ?> the output is: array ( [i] => 1 [a] => 1 [b] => 0 [c] => 0 [d] => 0 [e] => 2 [f] => 0 [g] => 0 [h] => 1 [j] => 0 [k] => 0 [l] => 0 [m] => 1 [n] => 1 [o] => 1 [p] => 0 [q] => 0 [r] => 0 [s] =

python - map with lambda vs map with function - how to pass more than one variable to function? -

i wanted learn using map in python , google search brought me http://www.bogotobogo.com/python/python_fncs_map_filter_reduce.php have found helpful. one of codes on page uses loop , puts map within loop in interesting way, , list used within map function takes list of 2 functions. here code: def square(x): return (x**2) def cube(x): return (x**3) funcs = [square, cube] r in range(5): value = map(lambda x: x(r), funcs) print value output: [0, 0] [1, 1] [4, 8] [9, 27] [16, 64] so, @ point in tutorial, thought "well if can write code function on fly (lambda), written using standard function using def ". changed code this: def square(x): return (x**2) def cube(x): return (x**3) def test(x): return x(r) funcs = [square, cube] r in range(5): value = map(test, funcs) print value i got same output first piece of code, bothered me variable r taken global namespace , code not tight functional programming. , there got t

ios - Generate a localized random NSString -

apologies if has been asked, google search not find it. does please know of method generate random string in ios respects current language of device? the idea quick 'unlock code' can generated using function; trouble languages other english entering code using keypad not quick or intuitive, particularly if user not have english keyboard enabled. one easy option generate string using digits 0-9. present standard number pad. however, should verify standard number pad shows digits 0-9 locales. ones verify arabic, chinese, , japanese locales, don't recall sure shows in cases.

Parsing list items from html with Go -

i want extract list items (content of each <li></li> ) go. should use regexp <li> items or there other library this? my intention list or array in go contains list item specific html web page. how should that? you want use golang.org/x/net/html package . it's not in go standard packages, instead in go sub-repositories . (the sub-repositories part of go project outside main go tree. developed under looser compatibility requirements go core.) there an example in documentation may similar want. if need stick go standard packages reason, "typical html" can use encoding/xml . both packages tend use io.reader input. if have string or []byte variable can wrap them strings.newreader or bytes.buffer io.reader . for html it's more you'll come http.response body (make sure close when done). perhaps like: resp, err := http.get(someurl) if err != nil { return err } defer resp.body.close() doc, err

ImageIO.write Permission denied issue Ubuntu Java -

i using struts2,java webapplication, ubuntu server i trying upload image in application,it works perfect in local machine (ubuntu), using same code trying upload image in ubuntu server machine . throws error,i have image resize code in application imageio.write used.the following code used thumbnail=scalr.resize(image,scalr.method.speed,scalr.mode.fit_to_width,480,10,scalr.op_antialias); imageio.write(thumbnail, ext, resizefile); fileutils.copyfile(resizefile, desfile); while reaching imageio.write point following exception thrown java.io.filenotfoundexception: 1342e10.jpg (permission denied) @ java.io.randomaccessfile.open(native method) @ java.io.randomaccessfile.<init>(randomaccessfile.java:236) @ javax.imageio.stream.fileimageoutputstream.<init>(fileimageoutputstream.java:69) @ com.sun.imageio.spi.fileimageoutputstreamspi.createoutputstreaminstance(fileimageoutputstreamspi.java:55) @ javax.imageio.imageio.createimag

Jasmine - expected parameter -

this first time looking @ jasmine , tdd in general. experimenting jasmine @ minute , have written function console logs passed in parameter. writing test ensures function called necessary parameter. describe("get suggestions function", function(){ it("should have parameter - value", function(){ expect(getsuggestions).tothrow(); }); }); the above code passes in jasmine's specrunner, unsure if correct method of testing. you can use tohavebeencalledwith function in jasmine working. you'll need spy on getsuggestions function , like it("tracks spy called", function() { expect(getsuggestions).tohavebeencalledwith('foobar'); });

javascript - If a request hit to my socket at '/' route this function gets executed is it posiible to execute this code async? -

exports.check= function(fn){ process.nexttick(function(){ while (true) { settimeout(function(){iconsole.log('what');fn(1)},15000) console.log('ok') } }) } var express = require('express') , http = require('http') , path = require('path'); var app = express(); tt=require('./tt') app.get('/test',function(req,res){ tt.check(function(err,data){ console.log(err) console.log(data) if(err){res.status(500).json({error : err})} else{res.send(data)} }) }) , check function defined in question.

python - Tkinter: How to get frame in canvas window to expand to the size of the canvas? -

Image
so i've been using canvas widget in tkinter create frame full of labels has scrollbar. working except frame expands size of labels placed in - want frame expand size of parent canvas. this can done if use pack(expand = true) (which have commented out in code below) frame in canvas then scrollbar doesn't work. here's appropriate bit of code: self.canvas = canvas(frame, bg = 'pink') self.canvas.pack(side = right, fill = both, expand = true) self.mailbox_frame = frame(self.canvas, bg = 'purple') self.canvas.create_window((0,0),window=self.mailbox_frame, anchor = nw) #self.mailbox_frame.pack(side = left, fill = both, expand = true) mail_scroll = scrollbar(self.canvas, orient = "vertical", command = self.canvas.yview) mail_scroll.pack(side = right, fill = y) self.canvas.config(yscrollcommand = mail_scroll.set) self.mailbox_frame.bind("<configure&

vb.net - MSAccess not opening database when started using System.Diagnostics.Process.Start() -

i having trouble start access database (msaccess.mdb) programmatically using system.diagnostics.process.start(). this scenario: vb.net aspx page starts [installpath]\cmd\erpimport.exe erpimport.exe reads settings sql server db (pgmname, params, execdir) uses again process.start() start batch file [installpath]\cmd\import.cmd import.cmd contains these 3 lines: g: cd \esvonix "c:\program files (x86)\microsoft office\office14\msaccess.exe" "g:\esvonix\esvonix.mdb" /runtime the esvonix.mdb programmed start data manipulation in startforms onopen event. startform set in db settings. now strange part: if start import.cmd double click windows explorer fine if start erpimport.exe (with connection string parameter expects) command line works fine but: if start erpimport.exe within vb.net page, start import.cmd correctly , import.cmd start msaccess.exe (as can see in taskmgr). however, access not open database (no ldb file created) , not start process

eclipse - BPEL Assign a list and display it in the output -

i'm using bpel designer eclipse , ode apache bpel server. want simple assign of list input output. in oracle assign have copy rule change "copy" "copylist" assign list, can't found option ode. any help, i'm new bpel? without knowing concrete structures difficult help. have @ ode's xpath extensions , in particular insert-after .

In C, what happens in memory when we do cast int to struct*? -

typedef struct block { size_t size; struct block* next; } node; static char arr[1000]; what happens arr when do node* first_block = (node*)arr; ? i understand equal to node* first_block = (node*)&arr[0]; but sizeof(node) = 8; sizeof(arr[0])= 1; so first element override next 7 elements in arr, because it's struct ? can explain me cast, please ? when write node* first_block = (node*)arr; you not changing in memory, pointer area in memory, type of pointer determines how area treated in regard pointer arithmetic. first_block->next pointer determined characters in array. as comparison have char* pointer same array (if arr declared @ global scope contain 0's) char* q = arr; node* p = (node*)arr; arr[1000] +----------------------+ q -> | | | | | | 0 | 0 | ... | 0 | p -> | | | | | +----------------------+ when do q = q + 1;

How to add custom places to the Google maps API in the search box in ios? -

how can add custom-places-to-the-google-maps-api-in-the-search-box in google map want show search hospitals, clinics, related shops, pharmacies, health , fitness centers , see how far km. these places locations going shown in google map along marker.

ios - what does the location of the SDK file mean? -

Image
ios noob here, basic question in file tree shown below: bolts.framework, parse.framework, , parsefacebookutils.framework under main project code folder "tinder", other frameworks (that added going build phases menu) under root tinder folder. what mean have different .framework files in different locations? matter? (for ex: facebooksdk.framework not @ same folder location bolts.framework - matter?) it not matter saved. though right click root (in case tinder) , create new group called frameworks. drag parse , bolts it. making sure folder still highlighted add other dependencies in normal way , go in group also. keeps clean can minimise folder , loose eyesore list of dependencies. hope helps. cheers.

c - GCC - Linux - Set the stack to zero before returning? -

context linux 64 bits question is possible instruct stack zeroed before returning function ? i want not valid information left on stack, if overwritten right after other values. explicitly want waste time doing so. is possible in automated manner that cannot bypassed when compiled in controlled environment ? thanks one way use "-finstrument-functions" option. allows hook in entry , exit function each regular function call entry , exit. clear stack in exit hook. name suggests intended instrumentation. nothing stop using other purposes.

javascript - React Native flexible view sizing within a paged scrollview -

i'm trying use scrollview (with paging enabled) in react native page through series of images. know how make image views fill each page of scroll view? far i've had luck hard coding width , height values image style. here's i'm doing: render: function() { return ( var images = [{ url: 'http://url/to/image.jpg' }, { url: 'http://url/to/another-image.jpg'}]; <scrollview horizontal={true} pagingenabled={true} style={styles.myscrollviewstyle}> {images.map(image => { return ( <image source={{uri: image.url}} style={styles.myimagestyle} /> ); })} </scrollview> ); } the way images show if hardcode width/height number in style. i've been unable image flex fill 1 whole page. scrollview style: scrollview: { flex: 1, backgroundcolor: '#000000', } image style: image: { width:375, height:667, flex: 1, backgroundcolor: 'rgba(0,0,0,0)', }

Reading various parts of binary file in c -

i writing program read specific parts of binary file , having trouble getting read right lengths of binary @ right locations in file. i've been trying figure out i'm doing wrong time no success. here code looks like int project(char * rel, char * atr){ takes in name of relation in , name of attribute char tmpstr[max_len+5], tmpstr2[max_len+5], attr[max_len+5], type[max_len+5], names[max_len+5];//attr attribute read pass of fscanf() int numbytes = 0, numtups = 0, nummove = 0, skip = 0, = 0; //the length in bytes of atr, number of tuples read file* f1; file* f2; strcpy(tmpstr, rel); strncat(tmpstr,".sch", 4); // appends '.sch' extension file name if((f1 =(file*)fopen(tmpstr, "r")) == null){ // opens "insertfilenamehere.sch" return -1; } if(fscanf(f1, "%d", &numattr) != 1){ return -1; } strcpy(tmpstr2, rel); strncat(tmpstr2,".dat", 4); // appe

javascript - Returning a new function instead of an object in factory -

is there drawback instead of returning object? .factory('box', function(){ var box = (function(){ var privatevar; return { watch: { song: undefined, artist: undefined, id: undefined }, update: function() { } } }); return new box; }) the reason want way function can function prototype , use this. no there isnt draw back, can use , take advantage of this in returning function .factory('example', ['$http', function($http) { return function(a, b) { this.a = a; this.b = b; }; }]); and can make object outside also var 1 = new example('a', 'b');

java - Volley retry if JSON request contains special status -

my application uses search service, takes long time return result. service returns {status : "not_ready"} if results not ready , {status: "ok"} , if search finished. can implement retries depending of content of json response in volley framework?

Spring + Hibernate DAO injection fails in Netbeans -

i have controller class logindata.java @controller @managedbean(name = "login") @sessionscoped public class logindata implements serializable{ @autowired private logindao logindao; private string username; private string password; public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public void validateuser(){ try{ logindao.login(username, password); }catch(businessexception e){ } } } i trying autowire dao , implementation: logindao public interface logindao { public boolean login(string username, string password)throws businessexception; public boolean register(string username, string password, usertype type)throws businessexception; } logindaoimpl public class logindaoimpl implements logindao{ private string username; p

php - Substring right after another substring -

so have big string, includes in middle following: "(...) status: ativo identificador: f36ce5 meio de pagamento: cartão de crédito data de contratação: 25/03/2015 data de expiração: 25/03/2017 (...)" * "(...)" identify there more content before , after part my goal isolate part right after "identificador:" , i.e., need grab value "f36ce5" (which different every time, of course) , set variable. i tried following code: $initialstring = "status: ativo identificador: f37ce5 meio de pagamento: cartão de crédito data de contratação: 25/03/2015 data de expiração: 25/03/2017"; $arr = explode(":", $initialstring); $important = $arr[2]; echo $important; but getting f37ce5 meio de pagamento what should f37ce5 ? is there way tell php: "give string right after 'identificador:', , nothing more" ? use regular expression. like: <?php $pattern = '/identificador: (\w+)/'; preg_matc

Yarn autorestart failed application -

we've streaming application running on yarn , ensure running 24/7. is there way tell yarn automatically restart specific application on failure? have tried hadoop yarn - resourcemanger restart yarn restart driver if fails feature “yarn.resourcemanager.am.max-attempts”, , default it’s 2.

python - Sqlalchemy get results in the same order -

i using query users = user.query.filter(user.id.in_(user_ids)).all() i want users in same order in user_ids . there anyway can directly in query or have sort again? if have sort again, pythonic way of sorting lists of objects based on list of ids. this possible, though ugly, postgresql 9.4+ , sqlalchemy 0.9.7+ . build map of id -> ordinal, use jsonb -> operator find ordinal each user id ( -> requires text json keys from sqlalchemy.sql.postgresql import jsonb, text sqlalchemy.sql import cast id_order = { str(v): k k, v in enumerate(user_ids) } users = user.query.filter(user.id.in_(user_ids)).\ order_by(cast(id_order, jsonb)[cast(user.id, text)]) this create sql order similar to order cast('{"1": 2, "3": 0, "2": 1}' jsonb) -> cast(user.id text) for other databases sort in client - though means cannot browse through results. the efficient code sort on client is: id_order = { v: k k, v in en

c++ - Overriding ofstream operator<< -

why still have error: exepected identifier in std::ofstream << val on line below? msvc. std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; } class ofstreamlog : public std::ofstream { private: std::mutex m_lock; public: ofstreamlog() : std::ofstream() { } explicit ofstreamlog(const char* filename, ios_base::openmode mode = ios_base::out) : std::ofstream(filename, mode) { } std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; } std::ostream& operator<< (short val); std::ostream& operator<< (unsigned short val); std::ostream& operator<< (int val); std::ostream& operator<< (unsigned int val); std::ostream& operator<< (long val); std::ostream& operator<< (unsigned long val); st

javascript - Adding Html using innerHTML property doesn't fire jQuery ready event -

i having performance issues using .html() method of jquery because being slow. searched alternatives , found some: jquery html() acting slow http://blog.stevenlevithan.com/archives/faster-than-innerhtml so replacing .html() method suggested. have problem: javascript inside html added not being executed. i have written simple fiddle show happening: javascript not being executed can suggest how solve because need javascript executed. you might need eval() script: var container = document.getelementbyid("container"), content = document.getelementbyid("content"); $("#button2").on("click", function(){ container.innerhtml = content.innerhtml; var scripts = container.getelementsbytagname('script'); for(var i=0, l=scripts.length; i<l; i++) eval(scripts[i].innertext); }); js fiddle demo

php - Laravel 5 Post-login actions/hooks -

in laravel 5, want add custom user-specific data session variable after user has logged in. understand there may way overriding postlogin() in authentication controller, think there may way using middleware? however, not sure place middleware executed straight after authentication has succeeded. you can place in middleware/redirectifauthenticated.php if ($this->auth->check()) { //place code here return new redirectresponse(url('/home')); }

basic - How to parse a time in years in QBasic -

how parse time (month/date/year) in microsoft qbasic, needed testing. s = 'pt1h28m26s' i get: num_mins = 88 you can parse such time string code below, real question is: still uses qbasic in 2015!? cls s$ = "pt1h28m26s" ' find key characters in string posp = instr(s$, "pt") posh = instr(s$, "h") posm = instr(s$, "m") poss = instr(s$, "s") ' if 1 of values zero, multiplying 0 if ((posp * posh * posm * poss) = 0) ' 1 or more key characters missing nummins = -1 numsecs = -1 else ' values string shour$ = mid$(s$, posp + 2, (posh - posp - 2)) smin$ = mid$(s$, posh + 1, (posm - posh - 1)) ssec$ = mid$(s$, posm + 1, (poss - posm - 1)) ' string integer, can calculate ihour = val(shour$) imin = val(smin$) isec = val(ssec$) ' calculate totals nummins = (ihour * 60) + imin numsecs = (ihour * 60 * 60) + (imin * 60) + isec end if ' display results print "n

python - MongoEngine schemata - name error -

i have following schema in file called model.py from mongoengine import * class subject(document): uri = stringfield(required=true) resources = listfield(referencefield(resourcesubject)) class resourcesubject(document): subject = referencefield(subject,reverse_delete_rule=cascade) resource = referencefield(resource) class resource(embeddeddocument): uri = stringfield() title = stringfield() snippet = stringfield() image = stringfield() source = stringfield() adapter = stringfield() for reason when try initialize subject, subj = subject(uri="hello").save() getting name error : nameerror: name 'resourcesubject' not defined . i cant understand reason, guess related framework? tried separating classes in individual files , importing, still same error. missing ? the error thrown on line: resources = listfield(referencefield(resourcesubject)) put resourcesubject quotes : resources = listfield(referencefiel

How to push some data from Json into new array in AngularJS? -

let's have json .. { "name": "mark", "gender": "male", "account1": { "accountno": 1201, "balance": 300 }, "account2": { "accountno": 1354, "balance": 5000 } } what expect .. $scope.myarray = [ { "accountno": 1201, "balance": 300 }, { "accountno": 1354, "balance": 5000 } ]; in angularjs, how can pick part of json data , push array iteratively( mean, when have account1, account2 account3 or more, can still add them array). you assign array over, in scenario not option because array psuedo. ideally able answer (related question) does: how return , array inside json object in angular.js simply $scope.myarray = json.accounts; however, noted, not have accounts array need make one. var accounts = []; for(var key in

php - dual database compare and update inventory value zencart stock function -

things lost or broken, basically, want compare actual inventory database against zencart store stock , update zencart stock if greater real inventory database. i have table 'products' in first database (zencart) , second database (inventory), this: products_id products_model products_quantity zencart.products : products_id : 3 | products_model : j293-04 | products_quantity : 4 | [...] inventory.products : products_id : 15 | products_model : j293-04 | products_quantity : 1 | [...] the inventory.products database actual count of products available. when zencart stock query function tests if goods available, want compare stock quantity inventory database. if zencart stock quantity > inventory stock, update zencart stock quantity = inventory stock. the zencart stock functions use zencart.products.product_id zencart.products.products_model has used compare 2 databases. this have come replace zencart stock count function. seems overly complex, , not s

security - Understanding the causes of the stack overflow attack -

go deeper causes of vulnerability, such stack buffer overflow, have number of questions, find difficult answer: maybe stupid question, still, why in os, such windows, buffer recording on stack occurs in direction recorded information: http://s27.postimg.org/udizo3itf/stack_overflow_2.png , not that: http://s18.postimg.org/q6kje5up5/stack_overflow_22.png then, if allocated memory not enough contain buffer, program crashes (an attempt appeal unallocated memory) , return address function not overwrites. does stack overflow attack make sense when target program has high permissions in system? how vulnerability helps attacker, example, create backdoor? if stack overflow attack needs inject shellcode, means attacker gets system control , can want(stack overflow attack unnecessary), or means user has needed attacker(in case, attacker can persuade user run executable file needs - stack overflow attack unnecessary). please specify reasoning wrong. here answers: the

conditional statements - Wordpress - is_page_conditional -

i struggling hard is_page_template conditional. the problem when "include" template functions file ( country_template_functions.php ) functions.php file, is_page_template conditional doesn't work anymore. if remove "include(template...)" functions.php work again, no solution since file has included functions.php make work. can explain me might wrong? is_page conditional works in both cases. if (file_exists(thesis_custom . '/country_template_functions.php')){ include(thesis_custom . '/country_template_functions.php'); } function test() { if ( is_page_template( "country_template.php" ) ){ echo "is page template works"; } } add_action('thesis_hook_before_header','test'); i using thesis theme. edit: seems cause problem not sure why. causes cannot use is_page_template after thesis_hook_before_content_area add_action('thesis_hook_before_content_area', 'countr

css - Unable to use calc to size image in carousel -

i'm hoping simple answer i'm overlooking. i've been toying around ui-bootstrap carousel directive, , wanted size dynamically fill space between header , footer. my header , footer each divs 70px in height. carousel works fine when let it's own thing, , plug images in. images rather large , not same size. thought maybe issue img tag changed div , set images background of each 1 height set calc(100% - 70px - 70px) . div's never seem calculated height (they have height of 0). after searching online, have set html , body tags height: 100% already, isn't issue. given it's kind of hard explain, please reference this plunkr heights given percentages work if parent element has explicit height set – don’t have here, can’t work, whether used in calc() or height: x% directly. but of course use calc(100vh - 140px) , if ok limited support in older browsers ¹. 100vh 100% of viewport height, doesn’t need have height set on parent elements html

java - Multithreading in Reactor 2.0 - why can't I spin signals out to multiple threads -

i'm running problems reactor 2.0 release. namely trying set reactive signal flow, fans out signal pool of waiting threads. i'm familiar rx , reactive cocoa, there basic missing here. i have basic transformation follows: workqueuedispatcher dispatcher = new workqueuedispatcher("dispatch", 10, 64, {... exception handle code here ...} return objectstream .partition(partitions) .dispatchon(dispatcher) .merge() .map(new function<object, object>() { @override public object apply(object o) { try { return extension.eval(o, null); } catch (unabletoevaluateexception e) { e.printstacktrace(); return null; } } }); i've tried flow 7 or 8 different ways, including different dispatchers, etc. i've tried breaking down gr

caching - Best way to provide `delta` of changes in database record -

we have rest api used mobile application. distilled version, let's assume api provides list of books , contents such author's name, publisher, year , content of pages. the mobile app needs cache last 10 books in local storage has 10 books available offline. books might updated @ server , app must sync latest changes. a new book added a books updated a book deleted etc we need way, @ server, provide changes have been made since last time mobile synced. instead of requesting whole latest 10 books request has changed since last fetch. this has been implemented in version management systems git looking simple way database records. what very simple way implement such delta ? this simple. need store utc date-time each book created/modified in database, , in app. app needs store last date-time requested update of book information. then when app requests book list, can provide 'last check' utc date-time api, , api can respond books have changed sin