Posts

Showing posts from August, 2015

android - Load CSS file from assets to a WebView with custom HTML and predefined Base URL -

i need load html construct @ runtime webview , apply css file placed in assets directory . , already have base url need provide webview's loaddatawithbaseurl function. code snippet (not applying css file): stringbuffer buff = new stringbuffer(); buff.append("<head>"); buff.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/my_css_file.css\"/>"); buff.append("</head>"); buff.append("<div class=\"announcement-header\">"); buff.append("header"); buff.append("</div>"); buff.append("<div class=\"announcement-separator\"></div>"); buff.append("<div class=\"announcement\">"); buff.append("content"); buff.append("</div>") webview.loaddatawithbaseurl(my_base_url, buff.tostring(), "text/html", http.utf_8, null); i've looked @ ...

Compile R script into standalone .exe file? -

is there easy way compile r script standalone .exe file matlab does? as matter of fact there way achieve solution meet requirements. have @ article on deploying desktop apps r on r-bloggers. detailed in article, end using few more things single exe file. also draw attention rgtk2 use of rgtk2 attempt develop own interface in r. if push comes shove, trust pack r code portable version of r , dependencies 1 installer , make , app that, create illusion of single exe file. in question asked whether it's easy develop standalone executable file interpreting r code. wouldn't it's easy. if have strong desire run r code application, in simpler manner using rcaller java or r.net .

javascript - Why the Ternary Operator isn't working right? -

well, i'm working in chat room website... , have problem... reason ternary operator doesn't give me right output... that's code piece of code job... html = html.replace(/(@[a-za-z0-9]{1,})/, "<span class='" + (myusername == "$1".replace('@', '') ? "highlighted-username" : "") + "'>$1</span>"); let's name "jimisdam" , writes in chat "@jimisdam"... so... i'm getting $1 , removing '@' compare myusername(which "jimisdam") what's wrong ?? js doesn't know want substitute $1 place before doing replacement. sees method call html.replace takes 2 arguments: the regex match the string replace with to calculate second parameter, evaluates expression: "<span class='" + (myusername == "$1".replace('@', '') ? "highlighted-username" : "") + "'>$1...

IOS Swift - How can I use 2 table views in a collectionview with different data -

i developing app have collectionview 2 different tableviews. need know how can recognize tableview filled data @ moment. each uiview object has tag property, used identify uiview @ runtime . you set this: mytableview1.tag = int.min mytableview2.tag = int.max and in delegate , datasource methods: func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int { let rowcount: int if tableview.tag == int.min { rowcount = self.datafortableview1.count } else { rowcount = self.datafortableview2.count } return rowcount } use tag value identify right tableview , that's it.

java - Creating an RDD after retrieving data from cassandra DB -

i'm using cassandra , spark project, wrote retrieve data db: results = session.execute("select * foo.test"); arraylist<string> supportlist = new arraylist<string>(); (row row : results) { supportlist.add(row.getstring("firstcolumn") + "," + row.getstring("secondcolumn"))); } javardd<string> input = sparkcontext.parallelize(supportlist); javapairrdd<string, double> tuple = input.maptopair(new pairfunction<string, string, double>() { public tuple2<string, double> call(string x) { string[] parts = x.split(","); return new tuple2(parts[0],string.valueof(new random().nextint(30) + 1)); } it works, want know if there pretty way write above code, want achieve is: in scala can retrieve , fill rdd in way : val datardd = sc.cassandratable[tablecolumnnames]("keyspace", "table") h...

python - uploading a plot from memory to s3 using matplotlib and boto -

this working script generates plot, saves locally disk, uploads s3 , deletes file: plt.figure(figsize=(6,6)) plt.plot(x, y, 'bo') plt.savefig('file_location') conn = boto.s3.connect_to_region( region_name=aws_region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, calling_format=boto.s3.connection.ordinarycallingformat() ) bucket = conn.get_bucket('bucket_name') k = key(bucket) k.key = 'file_name' k.set_contents_from_filename('file_location') os.remove(file_location) what want skip disk writing , upload plot directly memory. any suggestions how achieve that? putting together: img_data = io.bytesio() plt.savefig(img_data, format='png') img_data.seek(0) s3 = boto3.resource('s3') bucket = s3.bucket(bucket_name) bucket.put_object(body=img_data, contenttype='image/png', key=key) thanks @padraic-cunningham , @guyb7 tips!

c++ - Queue implementation is losing track of head node -

i have queue add function implemented void queue::add(myobj info) { node* node = new node; node->info = &info; //<---suspect node->next = null; if(head == null){ head = node; } else{ tail->next = node; } tail = node; count++; } every time gets visited head node's data points whatever i'm passing in. realize there template trying build one, because need practice. i trying keep pointers pointed original objects. wanted pass in object , point refrence. the node struct myobj * info , node * next info parameter of function, passed value. in case, &info address of parameter, , not of original data. this undefined behaviour , can give weird results. one possible solution be: void queue::add(myobj& info) // pass reference { ... // unchanged code } in case, &info refer address of original object.

How to publish the angularjs project from Webstorm -

there lot out there on how webstorm great editing angular, , built-in template quite good; however, can't find on do when i'm happy app. say create default template, how can nice folder structure app can ftp remote server? better yet, possible 'compile' (package) entire angular dependancies , modules 1 .js file , example have index.html reference somehow? you can inspire excellent yeoman generator . i'm using , when i'm done coding , testing gulp serve release app compiling source code gulp build command. architecture follow , found that's 1 : ├── src/ │ ├── app/ │ │ ├── components/ │ │ │ └── navbar/ │ │ │ │ ├── navbar.controller.js │ │ │ │ └── navbar.html │ │ ├── main/ │ │ │ ├── main.controller.js │ │ │ ├── main.controller.spec.js │ │ │ └── main.html │ │ └── index.js │ │ └── index.(css|less|scss) │ │ └── vendor.(css|less|scss) │ ├── assets/ │ │ └── i...

c# - Foreach loop to get an IEnumerable<T> -

when using foreach loop loop through collection of values types, necessary ienumerable<t> interface instead of non-generic ienumerable interface, prevent unwanted intermediate luggage instructions unbox appear in compiled code? is necessary it not necessary (necessary in context means required). is idea: yes. saving unboxing in cases micro-optimisation (except in inner loops of cpu limited data processing). if know have collection of type of value type keeping information not waste time on box-unbox cycle , makes code easier work with. the last point, given ide's intellisense capabilities, far valuable.

sql server - Export EXCEL-Table to MS-SQL with VBA -

i want export excel-worksheet table sql-function, imports received table in database. what have tried is, transmit each line ado in vba, works fine. have on 300 lines in excel , every time new connection each line bit difficult. hoping :-) regards

python - Django REST framework - HyperlinkedRelatedField with additional parameter -

i'm building rest web api django rest framework. have many-to-many relation between categories , wallets. starting category retrieve wallets linked to, , shell works fine models: class wallet(models.model): nome = models.charfield(max_length=255) creato = models.datetimefield(auto_now=false) utente = models.foreignkey(user) wallettype = models.foreignkey(wallettype) payway = models.manytomanyfield(payway, through = 'wpw', blank = true) defaultpayway = models.foreignkey('wpw', related_name = 'def_pw', null = true) def __unicode__(self): return self.nome class category(models.model): nome = models.charfield(max_length=255) creato = models.datetimefield(auto_now=false) enus = models.foreignkey(enus) wallet = models.manytomanyfield(wallet) utente = models.foreignkey(user) owner = models.manytomanyfield(user, related_name='owner_cat') urls: urlpatterns = patterns( '', ...

Create Outlook appointment via C# .Net -

i need create outlook appointment using microsoft.office.interop.outlook , while can work locally on own workstation , works if run web application via server's browser, not work when connect server externally. hence, think might permission issue. i changed application pool identity " localsystem " don't access denied error. unfortunately, doesn't work. the app behaves if appointment created, appointment doesn't appear in outlook. here include file on top of aspx.cs page using outlook = microsoft.office.interop.outlook; here code using pop appointment. outlook.application apptapp = new outlook.application(); outlook.appointmentitem appt = apptapp.createitem(outlook.olitemtype.olappointmentitem) outlook.appointmentitem; appt.subject = txtfirstname.text + " " + txtlastname.text; appt.body = txtcomment.text; appt.alldayevent = false; appt.start = datetime.parse(txtreminderdate.text + " 8:00 am"); appt.end = datetime.p...

django - Python- Iterating through columns in csv file -

i working on project have iterate through csv file. want see if 4 column(3rd slot) of each row have email address in dictionary has person's name , email address. if want send them attachment. i'm not familiar python, want see if i'm heading in right direction here sample code: import csv with open("file.csv") csv_file: row in csv.reader(csv_file, delimiter=','): if row[3] in data_dict: email = emailmessage('subject', 'body', [address@something.com]) email.attach_file('/folder/name.csv') email.send() when involved attachments i'd advise yagmail package (full disclose: i'm developer) obtain running: pip install yagmail # python 2 pip3 install yagmail # python3 then: import yagmail yag = yagmail.smtp('myemail', 'mypassword') open("file.csv") csv_file: row in csv.reader(csv_file, delimiter=','): row = row.split(',') if r...

javascript - How to insert text dynamically in CKEDITOR -

i use plugin ckeditor word editor in web. inside editor have table have 2 columns . want achieve in first column if user input number add (50) , result automatically appear in second column. easy using jquery not work. tried codes: function insertintockeditor(str){ ckeditor.instances['editor1'].inserttext(str); } but code insert automatically above text area of editor. use setdata() function insertintockeditor(str){ ckeditor.instances['editor1'].setdata(str); }

ios - How to remove back button from scrollview in Xcode/Swift -

Image
i trying remove automatically generated button scrollview in xcode. thanks. you using uinavigationcontroller , uiscrollview not have uinavigationbar inside it. need set normal uiviewcontroller or hide button in uinavigationbar in following way: self.navigationitem.sethidesbackbutton(true, animated:true) or in way : let backbutton = uibarbuttonitem(title: "", style: uibarbuttonitemstyle.plain, target: navigationcontroller, action: nil) self.navigationitem.leftbarbuttonitem = backbutton i hope you.

asp.net mvc 4 - First run FileResult to download file, then RedirectToAction -

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

mysql - Possible to improve the performance of this SQL query? -

i have table has on 100,000,000 rows , have query looks this: select count(if(created_at >= '2015-07-01 00:00:00', 1, null)) 'monthly', count(if(created_at >= '2015-07-26 00:00:00', 1, null)) 'weekly', count(if(created_at >= '2015-06-30 07:57:56', 1, null)) '30day', count(if(created_at >= '2015-07-29 17:03:44', 1, null)) 'recent' items user_id = 123456; the table looks so: create table `items` ( `user_id` int(11) not null, `item_id` int(11) not null, `created_at` timestamp not null default '0000-00-00 00:00:00', primary key (`user_id`,`item_id`), key `user_id` (`user_id`,`created_at`), key `created_at` (`created_at`) ) engine=innodb default charset=utf8 collate=utf8_unicode_ci; the explain looks harmless, minus massive row counts: 1 simple items ref primary,user_id user_id 4 const 559864 using index i use query gather counts specific...

Convert PHP string to javascript string -

for example, have php string: "2015-06-26". want assign javascript var. i tried string("2015-06-26"), it's substracting numbers, result this: "1983". how supposed it? thanks. use json_encode() convert php value corresponding javascript literal: var datestring = <?php echo json_encode($datestring); ?>;

java - calling multiple methods in oncreate method in android -

i have multiple methods called when activity started. have added methods in oncreate method. problem when activity started methods called or not called. how call methods when activity started. my code is protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); asynchttpclient client = new asynchttpclient(); requestparams params = new requestparams(); client.post("http://localhost/website/getdbrowcount.php",params ,new asynchttpresponsehandler() { public void onsuccess(string response) { try { log.d("home", "success"); jsonobject obj = new jsonobject(response); log.d("home", obj.tostring()); system.out.println(obj.get("count")); syncdb(); sync(); subsync(); ...

How do I free a *char allocated via FFI in Rust? -

i'm calling llvm api via rust's ffi. llvmprintmoduletostring uses strdup create string . however, when wrap pointer in cstring , error when rust drops it. #![feature(cstr_memory)] use std::ffi::cstring; extern crate llvm_sys llvm; fn main() { let llvm_ir_cstring; unsafe { let module = llvm::core::llvmmodulecreatewithname(b"nop\0".as_ptr() *const _); let llvm_ir_char_ptr = llvm::core::llvmprintmoduletostring(module); llvm::core::llvmdisposemodule(module); llvm_ir_cstring = cstring::from_ptr(llvm_ir_char_ptr); } println!("llvm_ir_cstring: {:?}", llvm_ir_cstring); } valgrind error: ==10413== invalid read of size 4 ==10413== @ 0x4870586: pthread_mutex_lock (in /usr/lib/libpthread-2.21.so) ==10413== 0x17f89b: je_arena_dalloc_small (in /home/wilfred/projects/bfc/target/debug/bfc) ==10413== 0x178c30: je_sdallocx (in /home/wilfred/projects/bfc/target/debug/bfc) ==10413== 0x10fa57: heap::imp::d...

oracle - ORA-00979: not a GROUP BY expression when sum(col) -

select invoicem.emp_no, employees.emp_name, invoicem.inv_no, sum(invoicem.sum_amt), invoicem.sal_date, invoicem.branch invoicem join employees on invoicem.emp_no = employees.emp_no group invoicem.emp_no,emp_name help me you can select field in group statement or aggregation function in oracle: select invoicem.emp_no,employees.emp_name,sum(invoicem.sum_amt) invoicem join employees on invoicem.emp_no = employees.emp_no group invoicem.emp_no,emp_name

How could I group by time(HH:MM) with mongoid or ruby -

how group time(hh:mm) mongoid or ruby i want group following data departure_at (hh:mm). how easier rails or mongoid expect result: { '06:40': [item125, item131], '10:20': [item126], .... query result mongoid [125] #<tiger _id: 811_0640_1010_tpe_kix, to: "kix", from: "tpe", price: 4899,departure_at: 08-11 06:40:00 utc>, [126] #<tiger _id: 811_1020_0305_tpe_kix, to: "kix", from: "tpe", price: 5450,departure_at: 08-11 10:20:00 utc>, .... [131] #<tiger _id: 812_0640_1010_tpe_kix, to: "kix", from: "tpe", price: 4899,departure_at: 08-12 06:40:00 utc>, first, make array of ["hh:mm", object] . can use trick this question array = @your_objects.map{|obj| [obj.date_departure.strftime("%h:%m"), obj]} hash[ array.group_by(&:first).map{ |k,a| [k,a.map(&:last)] } ]

gradle set a global property for all projects from gradle -

i set property within gradle (for example settings.gradle) in way similar gradle.properties or -d . possible? the following code demonstrates trying not working: import org.gradle.internal.os.operatingsystem def getarchitecture() { return system.getproperty("os.arch") } def getname() { if(operatingsystem.current().ismacosx()) { return "darwin" } else if(operatingsystem.current().islinux()) { return "linux" } else { throw exception("the operating system use not supported.") } } allprojects { ext { // variable has visible projects // , .gradle files in same way if set // gradle.properties file buildmachine = getname() + "_" + getarchitecture() } } edit i property defined in settings.gradle , visible in other .gradle file edit2 i have number of build machines , don't want specify value of variable buildmachine (in settings , in oth...

Python Merge Algorithm -

this seems working now... open criticism welcome. ty tsroten. debug = 1 #list merged a=[1,2,3,4,5,6,1,2,3,4,5,6,7] #artificial variables calling function p=0 r=len(a) q=int(((p+r)/2)-1) #list append merged values b=[] #end of list end=len(a) if debug: print ('mid: %d\n' % (q)) print ('end: %d' % (end)) #left , right lists sentinels l=a[:q+1] r=a[q+1:] l.append(none) r.append(none) #init counters i=k=j=l=0 if debug: print ('a:%s' %(a)) print ('\n') print ('l:%s' %(l)) print ('r:%s' %(r)) print ('\n') #merge left , right lists k in a: if debug: print ('iteration:%d' % (l)) l+=1 print ('i=%d, j=%d' % (i, j)) print ('b:%s' %(b)) print ('\n') if l[i] not none , l[i]<=r[j]: b.append(l[i]) i+=1 else: b.append(r[j]) j+=1 print ('result:',b) i trying write merge algor...

TextField Draggable in Swift iOS -

i want drag textfield around view. im having small problem code. here code override func touchesbegan(touches: set<nsobject>, withevent event: uievent) { var touch : uitouch! = touches.first as! uitouch location = touch.locationinview(self.view) bottomtextfield.center = location } override func touchesmoved(touches: set<nsobject>, withevent event: uievent) { var touch : uitouch! = touches.first as! uitouch location = touch.locationinview(self.view) bottomtextfield.center = location } problem if tried touch on textfield , drag doesn't work. if touch somewhere else , drag finger textfield start drag. want t make if touch on textfiel. you can achieve adding gesture text field: override func viewdidload() { super.viewdidload() var gesture = uipangesturerecognizer(target: self, action: selector("userdragged:")) bottomtextfield.addgesturerecognizer(gesture) b...

user interface - C# Ping.Send causing GUI to freeze -

first time using stackoverflow i'll try best. i making little app ping servers, issue i'm having gui of program locks while waits response. have far, button_click "ping ip" button, ping_box textbox contain response time, ip_address ip address in form of string. private void button_click(object sender, routedeventargs e) { stopwatch s = new stopwatch(); s.start(); while (s.elapsed < timespan.fromseconds(2)) { using (ping p = new ping()) { ping_box.text = (p.send(ip_address, 1000).roundtriptime.tostring() + "ms\n"); if (ping_box.text == "0ms\n") { ping_box.text = "server offline or exceeds 1000ms."; } } } s.stop(); } so in current state pings ip address repeatedly 2 seconds , puts response time textbox, during time gui locks though. need recorrect w...

c# - WCF NetTCPBinding in a Load Balanced Environment; what is the correct configuration? -

i have been battling resolve wcf issues on our production servers. 1 of errors thrown "the server rejected upgrade request." among other weird errors i'm receiving. our applications runs on citrix environment front end , our application servers host our wcf services. have 2 application servers set load balancing , kemp server supports sticky ip's since using nettcpbinding. however, not sure if have configured our nettcp settings correctly application uses 100% cpu, when more 5 users log onto application. after iisreset, takes hour re-occur. please find below configuration of nettcpbinding below: <bindings> <nettcpbinding> <binding name="nettcplargebindingendpoint" closetimeout="00:05:00" opentimeout="00:05:00" receivetimeout="00:15:00" sendtimeout="00:15:00" transactionflow="false" transfermode="buffe...

okhttp - Instrumenting OkHttpClient -

i'm writing small wrapper library that'll allow me monitor internals of okhttpclient using dropwizard metrics: https://github.com/raskasa/metrics-okhttp . i'm having trouble instrumenting connectionpool - specifically, periodically calling getconnectioncount() monitor number of open tcp connections. when instance of okhttpclient created, getconnectionpool() null - i'm expecting. also, subsequent attempts access pool still return null during/after executing network requests. i'm assuming there proper way monitor connectionpool because part of public api, i'm not seeing @ moment. so: is there way access connectionpool @ point okhttpclient.getconnectionpool() not null ? if isn't best approach, advice going better way? try this: okhttpclient client = ... client.setconnectionpool(connectionpool.getdefault()); that'll give same connection pool you'll anyway, it'll give sooner.

FloatingActionButton icon animation (Android FAB src drawable animation) -

i trying find documentation how create icon animation of fab's (of design support library), after searching while couldn't find information , animationdrawable reference in android developers doesn't work fab's if class child of imageview. but manage workaround works fine. the technic used similar 1 exposed on drawableanimation documentation, , using property animation api doc. first use valueanimator class, , int array containing ids of drawables you're going use in animation. final int[] ids = {r.drawable.main_button_1,r.drawable.main_button_2,r.drawable.main_button_3,r.drawable.main_button_4,r.drawable.main_button_5,r.drawable.main_button_6, r.drawable.main_button_7}; fab = (floatingactionbutton) findviewbyid(r.id.yourfabid); valueanimator = valueanimator.ofint(0, ids.length - 1).setduration(youranimationtime); valueanimator.setinterpolator( new linearinterpolator() /*your timeinterpolator*/ ); then set animationupdatelisten...

javascript - Uncaught ReferenceError: jQuery is not defined - requireJS -

i have few libraries use jquery instead of $ . i'm using requirejs load javascript, i'e encountered error message in title. how can tell requirejs allow jquery available under alias jquery $ ? app.js require.config({ paths: { app: '../app', "jquery": "lib/jquery/jquery-2.1.4.min", "jqueryui": "lib/jquery-ui.min", "easyloader": "lib/easyui/easyloader", 'domready': 'lib/domready' }, shim: { 'bootstrap': { deps: ['jquery'] }, } }); require(['jquery', 'bootstrap'], function($) { }); adding dependency shim configuration solves this. 'bootstrap-wizard': ['jquery']

python - Want to check this script I wrote to read a Fortran binary file -

i'm working on project requires me read fortran binary files. understanding fortran automatically puts 4-byte header , footer each file. such, want remove first , last 4 bytes file before read it. trick? a = open("foo",rb) b = a.seek(4,0) x = np.fromfile(b.seek(4,2),dtype='float64') it might easier read entire file , chop 4 bytes off each end: a = open("foo","rb") data = a.read() a.close() x = np.fromstring(data[4:-4], dtype='float64') for similar question, see how read part of binary file numpy?

regex - Mac OS/X, Grep and Whitespace issues -

i trying use grep on text file in os/x test. known contain following text, including whitespace characters. (10) business day my regex search pattern follows: [\(][0-9]{1,3}[\)] business day however, doesn't work: $ grep -eoi '[\(][0-9]{1,3}[\)] business day' *.txt if remove "day" above, this: $ grep -eoi '[\(][0-9]{1,3}[\)] business' *.txt (10) business which expected output egrep -oi or grep -eoi above line. neither this: $ grep -eoi '[\(][0-9]{1,3}[\)]\sbusiness\sday' *.txt nor this: $ grep -eoi '[\(][0-9]{1,3}[\)] business\sday' *.txt nor this: $ grep -eoi '[\(][0-9]{1,3}[\)][[:space:]]business[[:space:]]day' *.txt nor this: $ grep -eoi '[\(][0-9]{1,3}[\)] business[[:space:]]day' *.txt yield desired result, is: (10) business day instead, yeild this: $ (nothing) i have wasted hours pounding head on desk hours on this. grep not rocket surgery, missing here????? sol...

php - Solved with answer: How to change format of "date string" in scrapy spider? -

i scraping several websites using scrapy. 1 problem "post_date" item has different formats on different websites, example "06/01/2015" vs "1 june 2015". know how convert date string "06/01/2015" "1 june 2015", make date strings have same format in mysql. hypothetically, date on website provided as: <div class="date">06/01/2015</div> the following parse function in scrapy spider: def parse(self, response): hxs = htmlxpathselector(response) sites = hxs.select('//*') site in sites: il = exampleitemloader(response=response, selector=site) il.add_xpath('post_date', 'div[@class="date"]/text()') ^^^^^^^^^^^^^^^^^^^^^^^^^^ yield il.load_item() the above code collect date string "06/01/2015". on other hand, when try convert date string "01 june 2015" following code, didn't work. il.add_xpath('post_da...

javascript - Cordova PhoneGap upgrade to 5.1.1 from 2.2.0 -

i have cordova application version 2.2.0. want upgrade, have done upgrade part, after upgrading, application images not display, came blank screen. splash screen not came. here code now reached level. have simulated application, sqliteplugin issue. when open database db.cordova not define how database installation - copy database db folder android installation location. worked fine. this database: var db = new object(); db.isdbsupported = false; db.isdbcreated = false; db.vocabdb = null; db.tables = ['userresponses', 'wordgroups', 'words', 'wordmapping', 'checkexists', 'patch_version'] db.createdtables = 0; db.setupcallback = null; db.curqp = null; db.accountstatus = false; db.sfx = true; db.showwarnings = true; db.firstlaunch = false; db.initdb = function(callback) { this.setupcallback = callback || function(){/*console.log("null ...

REST get resource by two ids -

i have 2 entities: articles , users. users may write comment articles, specified user may write 1 comment specified article. so, comment can identified article_id , user_id . the classic rest request comment is: /comment/:id . in case don't have comment_id because useless. think /comment/:article_id/:user_id or /comment/:article_id!:user_id requests. what best practice such cases? i wouldn't call missing commentid 'useless', situation when need it. if @ possible, should create surrogate primary key (with no business meaning , created automatically db) in comments table - instead of compound key of userid + articleid. this allow more flexibility when/if requirements change. perhaps users allowed post more comments or comments need threaded. if database unchangeable legacy, agree urls given @gerino

c3 - Pubnub EON chart rendering multiple data in the chart -

Image
i following follwoing example publish data using pubnub , eon charts. when publish 1 data stream i.e 'checkpointsize' chart renders fine minute enter data2 i.e 'checkpointlength' gives me error uncaught error: source data missing component @ (1,1)! i can see data in pubnub console, means getting data stream cannot rendered chart. var pubnub = pubnub({ subscribe_key : 'your_subscribe_key_here' }); eon.chart({ pubnub : pubnub, history : false, channel : 'orbit_channel', flow : true, generate : { bindto : '#chart', data : { x : 'x', labels : true }, axis : { x : { type : 'timeseries', tick : { format : '%h:%m:%s' }, zoom: { enabled: true } } } }, transform : functio...

ios - How can you display info screen on iPhone during call -

Image
how can (using api) display on-call / during call information in iphone? i searched in api couldn't s solution far. screenshot below shows example relaso 1 android app. you can't. when phone application running in control of screen , application suspended.

PHP Parse error: syntax error, unexpected T_STRING on line X -

this question has answer here: php parse/syntax errors; , how solve them? 12 answers i have problem when did php , try call function again can help? php parse error: syntax error, unexpected t_string on line 12 code: <?php function greetings($name) { echo "greetings, " . $name . "!"; } $n = "magnus" greetings($n); ?> you forgot add ";" in code $n = "magnus"; // use ;

Minimising client processing - c socket programming -

i working on client/server model based on berkeley sockets , have finished i'm stuck way know of data has been received whilst minimising processing being executed on client side. the client working has little memory , battery , deployed in remote conditions. means wherever possible trying avoid processing (and therefore battery loss) on client side. following conditions on client outside of control: the client sends data 1056 bytes @ time until has ran out of data send (i have no idea number 1056 came if think know interested) the client unpredictable in when send data (it attached wild animal , sends data determined connection strength , battery life) the client has unknown amount of data send @ given time the data transmitted though grsm enabled phone tag (not sure relevant i'm assuming information help) (i emulating data expecting receive client through localhost, if seems work ask company interning invest in static ip address allow "real" tcp transfe...

ios - How to getback from external link in webview in iPhone application -

i using phonegap show website in phone application. have used window.open , it's working fine when click on external link not have option come in iphone. so there back? can know viewing external website can open phone browser or other solution. you can show toolbar cordova inappbrowser plugin has back, forward , close buttons. further customize app browser, please refer inappbrowser plugin documentation . code open website in modal webview. window.open("https://www.google.com", _blank', 'toolbar=yes') this behavior can changed replacing _blank 1 of following attributes: _self: opens in cordova webview if url in white list, otherwise opens in inappbrowser. _blank: opens in inappbrowser. _system: opens in system's web browser.

Difference between Task ID vs Message ID vs Stream ID in Storm? And how "anchoring tuples" and "acker tasks" are related to the context? -

i want know difference among them, , how related each other, , roles of "anchoring tuples" , "acker tasks". if possible, please detailed explanation , examples. have read official documentation , related articles, have unclear understanding on topic. streamid : per default there single (logical) stream called default . in use-cases necessary, have not single (logical) stream multiple (with different data in each stream). can declare other stream , assign id (ie, name) them distinguish them (this done in declareoutputfields(...) method). when "plugging" topology together, per default, assign default stream (as input stream), can specify name of stream want receive explicitly. taskid . each spout/bolt has assigned parallelism (ie, degree of parallelism, dop ). thus, each spout/bolt executed in multiple tasks, , each task id assigned such can distinguished. messageid : if want use fault-tolerance mechanism, need assign unique id each tuple e...

vb.net - Listview Flicker and Out Of Memory issues -

in application having memory issues adding tot listview, once it's running can't @ listview contents becuase flcikers , slows down, once xx,xxx items added , try view listview in tabcontrol out of memory error. i have closed can: doc = nothing allhtml = nothing tables_1 = nothing tables_2 = nothing gc.collect() which on initial insertion, it's when view listview crash occurs. thanks guys!

What Does Really Bind and Binding means in Programs Like PHP and JavaScript -

can please let me know meaning of bind , binding in php , javascript programming? example in php mysqli_stmt::bind_param -- mysqli_stmt_bind_param — binds variables prepared statement parameters. mean, really? you can think of prepared statement kind of function; ready executed once knows parameters are. bind function, tell statement value parameters. call execute function executes statement. the advantage of binding functions take care of possible hacking attempts sql injection, , escape characters quote ( ' ) lead invalid sql statements. furthermore, can reuse existing prepared statements binding them again. (note involves php - javascript plays no role in executed on client side.)

mime types - What is correct mimetype with Apache OpenOffice files like (*.odt, *.ods, *.odp)? -

i want *.ods , *.odt files on website open in openoffice when clicked, not saved on desktop, or opened embedded in browser etc. depends on how configured each user, what's best mimetype , other settings achieve of time? i know older *.doc documents enough: header("content-type: application/msword") ; i solution open office. my /etc/mime.types says it's: application/vnd.oasis.opendocument.text *.odt application/vnd.oasis.opendocument.spreadsheet *.ods application/vnd.oasis.opendocument.presentation *.odp it makes sense, it's corporate standard (vnd), designed oasis organization, used different formats of opendocuments. if don't want bother sending correct mime types, may use finfo class you: $finfo = new finfo(fileinfo_mime); header('content-type: ' . $finfo->file('/path/to/file'));

arrays - PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" -

i running php script, , keep getting errors like: notice: undefined variable: my_variable_name in c:\wamp\www\mypath\index.php on line 10 notice: undefined index: my_index c:\wamp\www\mypath\index.php on line 11 line 10 , 11 looks this: echo "my variable value is: " . $my_variable_name; echo "my index value is: " . $my_array["my_index"]; what these errors mean? why appear of sudden? used use script years , i've never had problem. what need fix them? this general reference question people link duplicate, instead of having explain issue on , on again. feel necessary because real-world answers on issue specific. related meta discussion: what can done repetitive questions? do “reference questions” make sense? notice: undefined variable from vast wisdom of php manual : relying on default value of uninitialized variable problematic in case of including 1 file uses same variable name. majo...

php - PDO SQLSRV Using bindValue for SELECT TOP -

i'm trying use pdo sqlsrv select data table limit (top). however, when this. $limit = 20; $sql = "select top :rowslimit * table order id desc"; $query = $this->db->prepare($sql); $parameters = array(':rowslimit' => $limit); $query->execute($parameters); i error this. warning: pdostatement::execute(): sqlstate[42000]: syntax error or access violation: 102 [microsoft][odbc driver 11 sql server][sql server]incorrect syntax near '@p1'. i tried removing paremeters , adding bindvalue instead, same error occurs either of these. $query->bindvalue(':rowslimit', (int) trim($limit), pdo::param_int); or $query->bindvalue(':rowslimit', intval(trim($limit)), pdo::param_int); so how can bind parameter top in pdo sqlsrv? you can't use parameters top value, there workaround issue. what need use row_number() over() syntax , manually filter out top @x rows. see sqlfiddle example .

How can I parse a java property file with php? -

hi have little problem in parsing java property file right way. need array every id, because want store in sql database. posting achieved until now. maybe have idea how right way: content of 01.meta: 12345.filename=myfile.jpg 12345.path=files/myfile.jpg 12346.filename=myfile2.jpg 12346.path=files/myfile2.jpg my php: <?php $file_path = "files/01.meta"; $lines = explode("\n", trim(file_get_contents($file_path))); $properties = array(); foreach ($lines $line) { $line = trim($line); if (!$line || substr($line, 0, 1) == '#') // skip empty lines , comments continue; if (false !== ($pos = strpos($line, '='))) { $properties[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1)); } } print_r($properties); ?> the result: array ( [12345.filename] => myfile.jpg [12345.path] => files/myfile.jpg [12346.filename] => myfile2.jpg [1...

prolog - Check if any solution exists -

i have code in form plan([],_). plan([ item | remainingitems ], groups) :- dostuff(groups, item, updatedgroups), rulesobeyed(updatedgroups), plan(remainingitems, updatedgroups). dostuff have 1 possible sub tree, rulesobeyed can have endless based on number of groups rules can obeyed in several ways. results in plan returns same solutions on , over. is there way like solution_exists(rulesobeyed(updatedgroups)) so not take possible solutions rulesobeyed account? the solution use once/1 - or \+ \+ false posted.

Polymer 1.0: What native methods are available to event targets? -

this documentation describes polymer's event retargeting. following documentation, have obtained "normalized event object" (neo) using polymer.dom(event) . neither event retargeting documentation nor api documentation describes native methods available (like .getattribute() ). example, see amit's answer this question . what native methods available normalized event object? , documented? a normalized event object has 3 properties listed: roottarget , localtarget , , path . first 2 element/node objects while path array of nodes @ event passes through. little snippet above solved using either of first two, i'd suggest using localtarget instead since it's retargeted one. var obj = polymer.dom(event).localtarget; var arg = obj.getattribute('data-foo'); // or obj.dataset.foo

windows - My bashrc stopped working when I moved it to a new enviornment? -

i moved files windows os x ( on macbook air ). used bash shell on windows , thought using same bash shell ( or similar ) on mac. 1 on windows came installation of git. os x has 1 built in already, called terminal. .bash_profile has single line source /root/config/bashrc.sh and bashrc.sh looks this: warp() { cd /c/root/ ; } launch() { git add -a . ; git commit -m $1 ; git push heroku master ; echo $1 ; } #defaults export visual=sublime_text export editor="$visual" #aliases alias i="ipconfig" alias s="sublime_text &" alias l="ls -a -l" #commands warp #grunt watch & #sublime_text & clear #output echo "" echo "************************************************" echo " - .bashrc loaded , sourced bashrc.sh" echo " - added functions warp() , launch()" echo " - added alias (i)pconfig (s)ublime (l)s -a -l" echo "**********************************************...

javascript - Not able to set chrome user agent from spec in protractor -

i have test need launch 2 browsers, 1 android user-agent , other windows-mobile user agent. have set android user agent in conf file. windows mobile, trying following: driver1 = new protractor.builder() .usingserver('http://localhost:4444/wd/hub') .withcapabilities(protractor.capabilities.chrome()).setchromeoptions(new chrome.options().addarguments("--user-agent=" + useragent)).build(); on run, says: failed: chrome not defined

junit - Static field injection in Spring Unit test -

i using junit4 in application tried test userservice , current test case simple: create user named 'admin' , save database. other test case rely on user. so use beforeclass insert record, have use userservice save user, spring not support inject static fields. when tried create userservice manually, found have fill dependencies myself, wonder if there alternative? or there wrong how use junit? @runwith(springjunit4classrunner.class) @contextconfiguration(locations = {"classpath:spring/application-config.xml"}) public class userservicetest { @rule public final expectedexception exception = expectedexception.none(); @autowired private userservice userservice; //@autowired // sprint not suport private static userservice us; private static user u; @beforeclass public static void before() { = new userserviceimpl(); // userservice instance can not used, since have fill dependencies manually us.clear()...

plsql - copy data after comparing a specific value -

i want make procedure in parameters. more specific, have tables folowing table1 |col1 | col2 | col3 | col4 | col5 | col6| ---------------------------------------- |600 | 140 | 2 | 10 | 1600 | 1 | ---------------------------------------- |600 | 140 | 2 | 20 | 1200 | 4 | ---------------------------------------- |600 | 140 | 2 | 15 | 1100 | 3 | ---------------------------------------- |600 | 140 | 2 | 35 | 1700 | 2 | ---------------------------------------- |600 | 140 | 3 | 10 | 1300 | 6 | ---------------------------------------- |600 | 140 | 3 | 15 | 1100 | 5 | ---------------------------------------- for same col1 , col2/col3 , check select different values col4 instance col1=600 , col2=140/col3=2 , col2=140/col3=3 return 20 , 35 and insert in table table1 rows 600 , 140 , 3, 20 , 1200 , 7 (seq number) 600 , 140 , 3, 35 , 1700 , 8 (seq number) but don't know how can insert statement :( procedure ...

javascript - How to remove jQuery element added by .append()? -

general info i'm working on intranet based administration system distribution centre. situation basicly have contenteditable table user data. except passwords of course. compare webbased excel sheet. using jquery ui dialog, i'm popping op form allows admin (company manager) of system change employees passwords if clicked on button. to make sure password change applied correct user, i'm passing along used id function pops dialog. using .append() i'm adding id form. point works fine. problem if password change cancelled, id must removed form again. otherwise end appending more , more ids form on each user clicked. same goes when password change succeeded. i've tried doing jquery .remove() , doesn't seem work, though can't find issue code. code function changepass(id){ var addid = $("<input>") .attr("type", "text") .attr("id", "userid") .attr("name", ...