Posts

Showing posts from September, 2014

angular - Add class name into div in ionic 2 -

Image
i using alert components need insert class name animated zoomin div near <div class="alert-wrapper"></div> it's possible ? doalert() { let alert = alert.create({ cssclass: 'animated zoomin', title: 'new friend!', message: 'your friend, obi wan kenobi, approved friend request!', buttons: ['ok'] }); this.nav.present(alert); } if want custom try create alert this: let alertpopup = alert.create({ title: 'title', subtitle: 'message', cssclass: 'animated_zoomin', buttons: [{ text: 'btntype', cssclass: 'buttoncss' }] }); this.nav.present(alertpopup); in app.core.scss or page scss, define cssclass this: .buttoncss{ color:#e74c3c; /*any other style wish apply*/ } .animated_zoomin{ color:#e74c3c; /*any other style wish apply*/ } ----make sure page scss imported----

php - Laravel5 Session::flash() persist for more requests than only one -

i'm solving quite strange problem: i try log in user, if credentials incorrect, flash message session , redirect user bach login page. there shown message, flashed session. anyway, after reload of page, there still message in session, however, should disappear. could provide me help? here code, flash message session: public static function verify($email, $password) { $verified = auth::user()->attempt([ 'email' => $email, 'password' => $password ]); if($verified) { $user = auth::user()->get(); session::flash('message', [ 'title' => trans('user.logged_in'.($user->sex != null ? '_'.$user->sex : '')), 'status' => 'success' ]); return redirect(route('admindashboard')); } else { session::flash('message', [ 'tit...

c# - Specifying multiple SSL protocols to be used in winform application causes exception when calling webservice for TLS1.0 server -

i have winform application built on .net framework 4.5 . want application support multiple ssl protocols, hecnce add following code: system.net.servicepointmanager.securityprotocol = securityprotocoltype.ssl3 | securityprotocoltype.tls | securityprotocoltype.tls11 | securityprotocoltype.tls12 ; but when call webservice hosted on server using tls 1.0 . following exception: the request aborted: not create ssl/tls secure channel. i have tried different combination of ssl protocols, worked in 3 scenarios, i didn't specify protocol. system.net.servicepointmanager.securityprotocol =securityprotocoltype.tls; system.net.servicepointmanager.securityprotocol =securityprotocoltype.ssl3 | securityprotocoltype.tls; so, problem server? or doing wrong? also, if don't specify ssl protocol, able call webservices hosted @ s...

java - JSON Parsing Exception: Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character '"' (code 0x22) in base64 content -

using jackson , i'm trying encode data in json & it's giving exception. i tried string data & byte[] data: string representation of same data here: bytes converted string-------->> { "appname": "aaa", "devicetype": "diehdcj", "reporteddate": "2015-05-03t15:38:45+00:00", "sessionid": "5366372183482-6736-23562378", "deviceid": "2151272389", "commandname" : "wqgduwusdue", "protocolversion" : "0.1", "protocolname" : "whjs_ashk_ask", "data" : "false" } java 16:50:46.065 [] [] error aaatshconnector [http-apr-10.40.120.85-80-exec-3] - json parsing exception: failed decode value_string base64 (mime-no-linefeeds): illegal character '"' (code 0x22) in base64 content here's code parsing: java @consumes(mediatype.application_json) @produces(mediatype.a...

c++ - Convert a point on an inclined image to a non-inclined point -

Image
i have image of image, inner image inclined , has own coordinate table (visible on edges): now need convert point of actual image (x cm, y cm) point on inclined image. say, want know (x cm, y cm) coordinates bottom left corner ( (0, img.height()) ) of actual image has. is, if inner image's coordinate table extrapolated. i know: the angle a of inclined image two points p1 , p2 selected manually inclined image the cm coordinates p1cm , p2cm these 2 points i can scale of image comparing 2 points , getting ratio between cm distance , actual distance: double dcmx = p1cm.x() - p2cm.x(); double dcmy = p1cm.y() - p2cm.y(); double dcm = sqrt(pow(dcmx, 2) + pow(dcmy, 2)) double dpointx = p1.x() - p2.x(); double dpointy = p1.y() - p2.y(); double dpoint = sqrt(pow(dpointx, 2) + pow(dpointy, 2)) double scale = dpoint / dcm; but have no idea how coordinates of left bottom corner in cm coordinates. this kind of transformation (using scale , tilt angle) call...

NetBeans - How to hint the IDE about file type? -

for example, have javascript file, reasons can not add .js extension @ end of filename, bin/mytool . possible hint netbeans ide javascript file? like: #!/usr/bin/env node /* @mime-type: application/javascript */ var env = process.env; or maybe hint in separate file .mimerc : bin/mytool application/javascript if feature not supported natively maybe there plugin? there plugin want: https://github.com/junichi11/netbeans-noext-mime-resolver . available, well, in list of available plugins of ide nb-noext-mime-resolver .

ios - Read JSON from URL with authentication -

i try read json url, authentication didn't work. found al lot of examples in net, every time authentication fails... this ist actuelly code : let requesturl: nsurl! = nsurl(string: "http://example.com")! let request = nsmutableurlrequest(url:requesturl!); let username = "username" let password = "pw" let loginstring = nsstring(format: "%@:%@", username, password) let logindata: nsdata = loginstring.datausingencoding(nsutf8stringencoding)! let base64loginstring = logindata.base64encodedstringwithoptions(nsdatabase64encodingoptions()) request.setvalue(base64loginstring, forhttpheaderfield: "authorization") let task = nsurlsession.sharedsession().datataskwithrequest(request) { (data, response, error) -> void in let httpresponse = response as! nshttpurlresponse let statuscode = httpresponse.statuscode print(statuscode) } task.resume() any ideas wh...

google chrome - Asterisk sslv3 alert handshake failure -

i using ubuntu v14.04.3 lts , asterisk 13.3.2. when try call extension sipml5 client play demo-congrats audio, call gets disconnected instantly. when check asterisk log, got following error: [2016-08-24 06:07:49] error[31730][c-0000000c]: res_rtp_asterisk.c:2042 __rtp_recvfrom: dtls failure occurred on rtp instance '0x7f547c013c68' due reason 'sslv3 alert handshake failure', terminating [2016-08-24 06:07:49] warning[31730][c-0000000c]: res_rtp_asterisk.c:3911 ast_rtcp_read: rtcp read error: unspecified. hanging up. [2016-08-24 06:07:49] warning[31730][c-0000000c]: app_playback.c:493 playback_exec: playback failed on sip/104600-00000007 /var/www/html/fetch_prompt [2016-08-24 06:07:49] error[31730][c-0000000c]: utils.c:1402 ast_carefulwrite: write() returned error: broken pipe also using chrome v54. i think error openssl, doesn't correct , complete answer yet solve issue. 1 know how solve issue? solved issue upgrading openssl. use below commands up...

c# - Maximize Window and restore to normal in wpf -

hi want maximize window in wpf , use below lines: private void mnu_maximize_click(object sender, routedeventargs e) { if (main.windowstate == system.windows.windowstate.maximized) main.windowstate = system.windows.windowstate.normal; main.windowstate = system.windows.windowstate.maximized; } but problem when click again restore window normal state it's not working , it's stuck in maximized state. how can fix this? add else part : if (main.windowstate == system.windows.windowstate.maximized) main.windowstate = system.windows.windowstate.normal; else main.windowstate = system.windows.windowstate.maximized; updates: in given code, conditional statement( if ) doing nothing, in case main.windowstate set maximized . that's why told introduce else there.

audio - Adding sound when button is clicked in javascript -

i've started coding. i've made quiz , want sound played when students click correct answer, , sound played when click incorrect answer. i've found posts online not working. can help? thank in advance! javascript: function checkanswer(){ myanswer=$('#inputbox').val(); if(myanswer.slice(myanswer.length-1,myanswer.length)==" "){ myanswer=myanswer.slice(0,myanswer.length-1);} if(currentanswer==myanswer){ score++; $('#feedback').append('<img src="tick.png">'); $('#inputbox').css("background-color","green"); $('#inputbox').css("color","white"); } else{ $('#feedback').append('<img src="cross.png">'); $('#inputbox').css("background-color","red"); $('#inputbox').css("color","white"); $('#in...

android - Text from EditText not saving in Shared Preferences -

i have edittext , want save text in edittext string in shared preferences if string not empty or null. app crashing following code: activity.java: button buttonnext = (button) findviewbyid(r.id.buttonnext); assert buttonnext != null; buttonnext.setonclicklistener(new onclicklistener() { @override public void onclick(view view) { if (checkforguardiannames()) { log.i("guardian names: ", "check passed"); log.i("activityedittext", inputguardian1.gettext().tostring()); toast toast = toast.maketext(userinfoactivity.this, inputguardian1.gettext().tostring(), toast.length_long); toast.show(); saveguardiannames(); } else { prompttofillfield("guardian"); log.i("guardian names: ", "check failed"); // toast toast = toast.maketext(userinfoacti...

javascript - ES6 equivalent of the following pattern? -

i want use static class properties (stage-0) in es6 classes - class button { static size = { small: "small", big: "big" } } class uilibrary { consturctor() { this.button = new button(); } } // can't access static properties of class instance :( const librarya = new uilibrary(); console.log(librarya.button.size.small); what best alternative this? edit : this question not creating class properties in es6/7 supported in stage-0, nor creating static methods. looking find pattern allows attaching of enum-like objects class instances. hence none of duplicate question suggestions valid. i can't access static properties of class instance :( yes, if static properties need access them on constructor: console.log(button.size.small); console.log(librarya.button.constructor.size.small); (see here discussion of differences) i looking find pattern allows attaching of enum-like objects class instances. if want th...

angular - Change selected Tab after CRUD operation - Ionic2 -

the app simple workout entry tool. basic api call crud operations. app display i can't reload workout tab after new entry created , stored database. able manipulate navcontroller set root display updated data it's under add workout tab. workouts updated in add workout tab when tab workout tab. displays result first image attached. i presume because constructor , ngoninit initialized once. how can around this? this code workout tab. export class workoutpage { navctrl; workoutservice; workouts; static parameters() { return [navcontroller, workoutservice]; } constructor(navctrl, workoutservice) { this.navctrl = navctrl; this.workoutservice = workoutservice; this.workoutservice.getworkouts().subscribe(workouts => { this.workouts = workouts; }) } ngoninit() { this.workoutservice.getworkouts().subscribe(workouts => { this.workouts = workouts; }) } workoutselected(event, workout) { this.navctrl.push(workoutdetailpage, { work...

GuideWire BC configuration with SQL Server database -

currently working on pc-bc integration. need configure studios sql server database, pc working fine, bc i'm getting error. if knows please me sort out. <database name="billingcenterdatabase" dbtype="sqlserver" autoupgrade="true"> <dbcp-connection-pool jdbc-url="jdbc:sqlserver://localhost:1433;databasename=billingcenterdatabase;user=username;password=pass#1121"/> <upgrade defer-create-nonessential-indexes="false"> <versiontriggers dbmsperfinfothreshold="600" /> </upgrade> </database> my username "username" , password "pass#1121" database name : billingcenterdatabase the error i'm getting gw.pl.exception.gwlifecycleexception: no appropriate database found in configuration: env = 'null' you should have mention environment name in tomcat.conf in tomcat config file if deploying application on tomcat. java_opts...

scheme - Why are `not-equal?` and similar negated comparisons not built into Racket? -

in racket (and other schemes, can tell), way know of check whether 2 things not equal explicitly apply not test: (not (= num1 num2)) (not (equal? string1 string2)) it's (not (that-big-of-deal?)) , it's such common construction feel must overlooking reason why it's not built in. one possible reason, suppose, can rid of not using unless instead of when , or switching order of true/false branches in if statement. doesn't mimic reasoning you're trying convey. also, know negated functions easy define, <= , example, , built in. what design decisions not having things not-equal? , not-eqv? , not-eq? , != in standard library? first, correct (not (that-big-of-a-deal?)) 1 the reason racket doesn't include out of box because adds lot of primitives without benefit. admit lot of languages have != not equal, in java, if want deep equality check using equals() (analogous equal? in racket), have manually invert result ! yourself. hav...

ios - Set image in UICollectionViewCell with af_setImageWithURL cost to much memory -

i have memory issue using afi. have uicollectionview custom cell, , each cell has uiimageview . in cellforitematindexpath , set image af_setimagewithurl . the problem memory usage getting high. if set cell's image local image, use 27mb memory. when fetch image af_setimagewithurl , memory usage going 87mb. so doing mistake? thank you. check documentation setimagewithurl , it cached image locally, keep image in cache memory reusability tableview or collectionview reuse cell, not download image everytime , can use cache memory. so, may take more memory because of cache think!

c# - Multiple time executing cell paint event in datagridview view (Winform) -

i wanted keep functionality search , highlight data row cell content in datagridview row. i using cellpaint event same. i setting search matching cell content again , time on event highlighting cell. i need suggestion whether alternative event can used same purpose. because have noticed event executing cells, above cell modified cell. below code snaps //re setting cell content highlight datagridview1.rows[rowindex].cells[0].value = ""; datagridview1.rows[rowindex].cells[0].value = "test"; void datagridview1_cellpainting(object sender, datagridviewcellpaintingeventargs e) { //highliting here if match search content }

javascript - stop d3js globe auto rotate -

i have d3js globe , found code auto rotate need code stop rotate. 1 can help? here code. var rotate = [.001, 0], velocity = [.013, 0], time = date.now(); function rotateglobe() { d3.timer(function() { var dt = date.now() - time; projection.rotate([rotate[0] + velocity[0] * dt, rotate[1] + velocity[1] * dt]); redraw(); }); } $(document).ready(function(){ $("#stop").click(function(){ stopglobe() }); function stopglobe() { //need stop code here } }); you can stop timer timer.stop() ;: var rotate = [.001, 0], velocity = [.013, 0], time = date.now(); var timer;//make timer global. function rotateglobe() { timer = d3.timer(function() { var dt = date.now() - time; projection.rotate([rotate[0] + velocity[0] * dt, rotate[1] + velocity[1] * dt]); redraw(); }); } $(document).ready(function(){ $("#stop").click(function(){ stopglobe() }); function stopglobe() { timer.stop(); ...

javascript - Why my source code doesn't work? -

i run success on fiddle: http://jsfiddle.net/donhuvy/hfq4ycvs/ but when run (file progress_bar.html ) in local, nothing happen. <!doctype html> <html> <head> <title>progress bar...</title> <style type="text/css"> .progress { display: block; text-align: center; width: 0; height: 3px; background: red; transition: width .3s; } .progress.hide { opacity: 0; transition: opacity 1.3s; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(function () { var data = []; (var = 0; < 100000; i++) { var tmp = []; (var = 0; < 100000; i++) { tmp[i] = 'hue'; } data[i] = tmp; ...

python xarray - groupby.apply method taking more than one arguments -

in xarray document, groupby.apply method can apply function different groups. in documentation, in [11]: def standardize(x): ....: return (x - x.mean()) / x.std() ....: in [12]: arr.groupby('letters').apply(standardize) however, how can put argument standardize function? i.e. def standardize(x, y): ....: return (x - x.mean()) / x.std() + y.sum() arr.groupby('letters').apply(standardize(x, y))?? it obvious not right. now, there no way call apply method. to apply operation on multiple variables @ once, put multiple dataarray objects single xarray.dataset , e.g., # foo , bar xarray.dataarray objects ds = xarray.dataset({'x': foo, 'y': bar}) def standardize(ds): return (ds.x - ds.x.mean()) / ds.x.std() + ds.y.sum() ds.groupby('letters').apply(standardize)

haskell - sudden yesod tls exception, DecodeError -

i've started encountering following errors when attempting use gmail authentication ( yesod.auth.googleemail2 ) in yesod application: failedconnectionexception2 "www.googleapis.com" 443 true sendbuf: resource vanished (broken pipe) and tlsexceptionhostport (handshakefailed (error_packet_unexpected "alert [(alertlevel_fatal,decodeerror)]" " expected: change cipher")) "www.googleapis.com" 443 the second error more common. it's still possible log in---reloading after error gives statuscodeexception (status {statuscode = 400, statusmessage = "bad request"}) [("content-type","application/json; charset=utf-8"),("cache-control","no-cache, no-store, max-age=0, must-revalidate"),("pragma","no-cache"),("expires","mon, 01 jan 1990 00:00:00 gmt"),("date","wed, 24 aug 2016 01:13:02 gmt"),("content-encoding","gzip...

PowerShell ISE Git GPG Signed Commit Error -

if in command line git sign commit in powershell ise (as admin or not) following error: c:\users\myname\myrepo> git commit -s -m "testing signed commit in powershell ise." git : gpg: warning: unsafe permissions on homedir 'c:\users\jerry\appdata\roaming\gnupg' @ line:1 char:1 + git commit -s -m "testing signed commit in powershell ise." + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : notspecified: (gpg: warning: u...\roaming\gnupg':string) [], remoteexception + fullyqualifiederrorid : nativecommanderror gpg : cannot open tty no tty': no such file or directory error: gpg failed sign data fatal: failed write commit object signed commits work in command prompt , powershell console (as admin or not), i'm guessing gpg having issue ise? error permissions unsafe on "homedir" (where gnupg lives), don't know how make windows permissions directory safe gpg...

angular - Property 'currentUser' does not exist on type 'FirebaseAuthState' -

trying currentuser in angularfire2. type exposes this? https://firebase.google.com/docs/reference/js/firebase.auth.auth it's not obvious me exploring observable: constructor(private auth: firebaseauth) { auth.subscribe((user) => console.log('user is', user)); } the user object receive firebaseauth observable contains following properties: provider uid auth the last of these - auth - currentuser . if @ source , can see auth property firebase user . you can verify using instanceof : constructor(private auth: firebaseauth) { auth.subscribe( (user) => { if (user) { console.log('user.auth user instance = ' + (currentuser instanceof firebase.user)); let currentuser = user.auth; // ... } else { console.log('no user signed in'); } } ); }

My Android Application Crashes when I shared it to other devices -

my application crashes after sending apk other devices, installed yet when tried open ,even @ beginning crashes. me please sampleacct01 application crashes.means have check error @ log cat crash application, lots of resons may 1. if min sdk version not matched other device 2. higest sdk version have used in application 3.cooding mistakes ..likes..example .getting directly integer value in string lots of reasons there. use log cat in every methods & after getting veriables so can confirm why getting problem so first have check..min sdk version..and maximum sdk version check cooding

java - how to query dynamodb with LSI and mapper -

i trying load info dynamo db table using lsi , dynamodb mapper class. assume have following code conisder class class employee { @dynamodbhashkey public string getid() { return id; } @dynamodbrangekey public string getfirstname() { return firstname; } @dynamodbindexrangekey(localsecondaryindexname = "my-lsi") public string getlastname() { return lastname; } public string getmyotherfield() { return myotherfield; } } consider piece of code retrieve info using lsi , dynamodb mapper employee obj = new employee(); obj.setid("221"); obj.setlastname("someone"); dynamodbqueryexpression<employee> queryexpression = new dynamodbqueryexpression<>(); queryexpression.sethashkeyvalues(obj); queryexpression.setindexname("my-lsi"); queryexpression.setprojectionexpression("myotherfield"); paginatedquerylist<employee> paginatedquerylist = mapper.query(empl...

c++ - Qt plugin using host app's classes -

i have linking problems creating qt c++ plugin extend functionality of application. code compiles , everithing works, long use qt library classes, qstring example. moment give plugin's class reference object classes defined in host app, project not linked anymore. creating plugin follow procedure qt documentation , take consideration given examples - echo , plug&paint. however, such case not covered there. update here error: myplugin.obj:-1: error: lnk2019: unresolved external symbol "public: class qstring __cdecl myclass::answer(void)const " (?answer@myclass@@qeba?avqstring@@xz) referenced in function "public: virtual class qstring __cdecl myplugin::echo(class myclass *)" (?echo@myplugin@@ueaa?avqstring@@peavmyclass@@@z) and here project causes it: plugtest.pro template = subdirs subdirs += \ host \ plugin host.pro qt += core gui greaterthan(qt_major_version, 4): qt += widgets target = host template = app sources...

git - Can't push to github from Android Studio all of a sudden -

i wasn't having problems pushing remote repository, i'm getting following error: 8:48:11 pm emptythrowable: repository not found root c:\*\src\main\res\drawable-mdpi i checked remote repository , looks drawable-mdpi folder not there. i'm not sure why, shouldn't git resolve since i've added , committed files local repository?

sql - QUALIFY keyword in Teradata, Is there any equivalent in Oracle? -

below query in teradata gives latest record id_field select * table qualify row_number() over(partition id_field order update_date desc)=1 is there equivalent keyword qualify in oracle. as per knowledge, have write inner query in oracle same operation or self join. there simple ways in teradata. appreciate response much. select * ( select table.*, row_number() over(partition id_field order update_date desc) record_order table ) record_order=1

django - Creating ModelAdmin that has more then 1 view -

i'm working on project has more of complex admin page. currently i'm trying accomplish when user adds report report checks bunch of data , create list of people within area (less 10 km). when add report when click save changes view view lists people found , emails, can select people want add , press button more stuff. my code follows: admin.register(report) class reportadmin(admin.modeladmin): change_form_template = 'admin/phone/index.html' # inlines = [subjectinline] def response_change(self, request, obj): """ determines httpresponse change_view stage. """ opts = self.model._meta msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} context = {} if "_email" in request.post: msg = _('report saved - please select store below notify.') % msg_dict self.message_user(request, msg, messag...

Building a ruby script with Ocra for cross platform uses but i get the 'relative_path_form' with a stacktrace -

i'm trying build .exe execute script on windows without ruby installation. i'm using ocra have stack trace. also note there 2 files runs whole sc , use rvm , didn't sudo gem install since use rvm. gems used in first file : require 'rubygems' require 'nokogiri' require 'open-uri' require 'colorize' require 'colorized_string' gems used in second file : require 'libnotify' require './firstfile' require 'os' require 'twilio-ruby' here ocra gives me: >ocra --output test.exe firstfile.rb secondfile.rb /home/xxxx/.rvm/gems/ruby-head/gems/ocra-1.3.6/bin/ocra:41:in `relative_path_from': undefined method `path' "/home/xxxx/.rvm/gems/ruby-head@global":string (nomethoderror) /home/xxxx/.rvm/gems/ruby-head/gems/ocra-1.3.6/bin/ocra:779:in `block in build_exe' /home/xxxx/.rvm/gems/ruby-head/gems/ocra-1.3.6/bin/ocra:762:in `each' /home/xxxx/.rvm/gems/ruby-head/gems/ocra-1....

r - Quickly find value from data.frame in list with matching element names -

i have list xnumber of named elements, each element containing series of numbers. i have data.frame containing 2 columns: column1: names matching of list elements (though not in order) column2: vector of numbers i want determine location of value of each row of data.frame in list given list element equals each given data.frame row's value in data.frame's name column. the end goal produce vector containing list value of each appropriate element preceding value i've matched each row of data.frame. my data has 200,000 rows i'm trying optimize process. example i have list , data.frame: a = 1:5; b = 6:10; c = 4:8; l1 <- list(a,b,c) # list d1 <- data.frame(name = c('c','a','b'), val = c(7,3,8)) #a data.frame so first want know each value occurs in list (such element matches name same row in data.frame) : where <- ???? >where [1] 4 3 3 # 7 = 4th number in c, 3 = 3rd # in a, , 8 = 3rd # in b but want outp...

ionic2 - Acess data from Start Page using Ionic 2 + Angular 2 -

edit i have web service rest provides menu this: { "items": [ { "content-type": "one", "title": "title1", "url": "url1"; }, { "content-type": "two", "title": "title2", "url": "url2" } ] } in start page menu, , gives dynamic content, provides different pages. @component({ providers: [apiclient], templateurl: 'build/app.html', selector: 'my-app' }) class myapp { @viewchild(nav) nav: nav; rootpage: = somecomponent; @input() url: string; pages: array<{ title: string, component: any, url: string }>; constructor(public platform: platform, private _apiclient: apiclient) { this.initializeapp(); this._apiclient.get("http://localhost:8080/myapp/context/menu", 'menu', null, ...

Which CSS selector is faster in performance? Class in Class vs tagName in Class? -

note: question not have similar match on so. i aware css selectors read right left. aware css class selectors should not additionally qualified tagname. but among these faster (not talking specificity): .group div { ... .group .item { ... for html: <div class="group"> <div class="item"></div> </div> since right left, doesn't mean in first case, browser search div s (and faster) compared second case, browser search every element has class of item (before comparing parent .group class)? i expect .group .item (neglibibly) faster. that's because, probably, number of div elements greater number of elements class item . so if use .group div , every div match div part, , browser have ensure there .group ancestor. if use .group .item , every .item match .item part, , browser have ensure there .group ancestor. for better performance, want avoid false positives, , if selector not going match elem...

c++ - Calling functions from a std::map -

i'm trying construct object serve handler functions. explain why, i'll use scan user input, check map match. if match found, call function , copy rest of user-inputted line function; class object { public: object(std::map<std::string, void(*)(const std::string&)> map) {/*...code...*/}; }; quick example code: class main { public: void testfunc(const std::string& a) { } void construct() { object{ std::map<std::string, void(*)(const std::string&)> { {"exit", [](const std::string &a){ exit(1); }}, //{"test1", (void(main::*)(const std::string&))&testfunc}, //{"test2", [](const std::string &a){ testfunc(a); }}, //{"test3", [this](const std::string &a){ testfunc(a); }}, {"null", null} } }; } }; neither of commented lines wo...

cancan - Accessing an external table from a Rails application -

rails 3.2 i using api gem. client wants, keep table wants whitelist email addresses can used access api, in seprate table, can access through phpmyadmin. this single table: api_users with single column: email (in addition id, created_at, updated_at) the email addresses go in table, exist in users table rails application. if create model: models/api_user.rb: class apiuser< activerecord::base attr_accessible :email and, in models/api_ability.rb, add following: class apiability include cancan::ability def initialize(user, params = {}) user ||= user.new if apiuser.find_by_email(user.email) can :manage, :api end end end will work? that sounds absolutely doable. might want add like def readonly? true end to apiuser class make sure no 1 try create instances of within rails. apart don't see reason not way given clients requirements.

ios - Is it a possible for an objective-c class to implement a swift protocol in the .h -

is possible objective-c class implement swift protocol in .h other swift classes can reference objective-c class swift protocol type? let myswiftprotocol swift protocol type, assume have in .h class: @protocol myswiftprotocol; @interface myobj : nsobject< myswiftprotocol> then i'll warning: cannot find protocol definition myswiftprotocol warning no good, doesn't work. so let's assume in .m , remove references protocol in .h . @interface myobj () <myswiftprotocol> then end not being able cast objects of type myobj type myswiftprotocol in swift classes. so neither approach above works. please help! according apple. forward declarations of swift classes , protocols can used types method , property declarations . further apple says, an objective-c class can adopt swift protocol in implementation (.m) file importing xcode generated header swift code... basically cannot mark obj-c class conforming swift protocol in .h. ...

How to create a json from subproccess in python -

i'm not sure if i'm titling question correctly, have following situation: i subprocessing scala script ingests json file, , output string in json format. right have following code: with open("stdout.txt", "w") out: p = subprocess.popen(['sbt', '--error', 'run /jsonfolder/example.json'], cwd = basedir, stdout = out) print out which writes stdout.txt file in directory containing outputted string in json format. however, i'd "transform" .txt file .json "pretty" , "structured." i've tried with open("stdout.json", "w") out: instead, did not work.

How does sort function works in algorithm in C++, and how to improve this code? -

here homework challenge: question: write program prom night, in girl can dance taller boy. what trying do: b no. of boys, g no. of girls stored in vector sort vector compare heights , result like boy girl can dance? 1 98 90 yes 2 90 91 no 3 85 82 yes 4 78 75 yes 5 70 72 no what want know: how can improve code. how sort function works? type of sorting uses? can applied on arrays well? my code: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int b,g,i,j,h,r,count=0; vector<int> boys, girls; //input -no. of boys , girls , heights cout<<"enter number of boys: "; cin>>b; cout<<"enter number of girls: "; cin>>g; if(g>b) { cout<<endl<<"no! girls can't dance, because no. of boys less'"; exit(1)...

r - igraph permute() method bug -

Image
i want node permute graph. see test graph have created, below. when use permute() method igraph r library, no changes occur in new graph permute() makes. happening? testg <- vector(mode="list", length=6); #assign initial probabilities testg = list("gene1"=0, "gene2"=0, "gene3"=0, "gene4"=0, "gene5"=0, "gene6"=0); adjacency_test <- matrix(c(0,1,1,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0), nrow=6, ncol=6); rownames(adjacency_test) <- c("gene1", "gene2", "gene3","gene4","gene5","gene6"); colnames(adjacency_test) <- c("gene1", "gene2", "gene3","gene4","gene5","gene6"); require(igraph) p <- graph.adjacency(adjacency_test, mode="undirected", weighted=true); vids.permuted <- c(6,5,4,3,2,1) p2 <- permute(p, permutation=vids.permuted) plot(p) plo...

sql - Calculate the sum of a values across multiple columns in a table in Postgres (plpgsql) -

i have table formatted: fcst_month | idx1 | idx2 | idx3 | val1 | val2 | ... | valn i sum of of 'val's each fcst_month. seems way of doing transpose table using tablefunc crosstab() ( https://www.postgresql.org/docs/9.3/static/tablefunc.html ) , passing in column particular fcst_month, reading docs , other examples on so, i'm not understanding how use function achieve goal. could give me example of crosstab() achieve or similar task? or perhaps suggest alternative achieving goal? you can unpivot table using json functions row_to_json() , json_each_text() . additionaly, use with ordinality column numbers. example: create table a_table (fcst_month int, val1 int, val2 int, val3 int); insert a_table values (1, 10, 20, 30), (2, 40, 50, 60); select fcst_month, ordinality, key, value a_table, json_each_text(row_to_json(a_table)) ordinality; fcst_month | ordinality | key | value ------------+------------+------------+------- 1 | ...

javascript - Angular 2 animating transition based on dynamic value instead of time -

while understand angular 2's animate used animate transition between states in fixed time, not convenient. in case, have slide-able element, wish animate based on how far have moved default position. is, want provide handler dynamically with, example float number between 0 , 1 representing how far along animation should be. can angular 2 framework handle this? can perhaps, somehow, bypass default animate(time) property , , directly call underlying function changes css? i'm not 100% clear on problem, don't think you're asking possible angular animations. angular's animations built on top of web animation api, streamlined means of interacting css animations. css animations defined keyframes + durations (see https://css-tricks.com/almanac/properties/a/animation/ ). theoretically, create complex set of keyframes "stepped through" based on position of slide-able element, hack , not you're asking for. to accomplish goal, think you'l...

Is there a spinner module for Angular 2 RC5 -

i have angular 2 rc5 project basic form shown user. i'm looking spinner can show after user performs form submission. current rc5 module available showing spinner?

python - Convert '%m/%d/%Y' string index into pandas datetime index -

my index datetime string format '%m/%d/%y' ('09/26/2007') when try convert index datetime index using pd.to_datetime function pd.to_datetime(df.index) , got error message outofboundsdatetime: out of bounds nanosecond timestamp: 1-01-01 00:00:00 it looks pandas can't detect right string format, how can convert index datetime index? thanks the of error message, appears may have string '1/1/0001' in index. example, df = pd.dataframe([1,2], index=['09/26/2007', '1/1/0001']) pd.to_datetime(df.index) raises outofboundsdatetime: out of bounds nanosecond timestamp: 1-01-01 00:00:00 this error arises because datetimeindex uses array of numpy datetime64[ns] s can not represent date 0001-01-01. datetime64[ns] dtype can represent dates in range [1678 ad, 2262 ad] . there pandas github issue discussing limitation. for now, recommended solution use periodindex instead of datetimeindex: df = pd.dataframe([1,2], index=[...

java - System.out.println prints the string but System.out.print does not -

i trying store words in file separated coma in java array file is age,income,student,credit rating,class: buys computer youth,high,no,fair,no youth,high,no,excellent,no middle aged,high,no,excellent,no senior,medium,no,fair,yes senior,low,yes,fair,yes senior,low,yes,excellent,no public class test { public static void main(string args[]) throws filenotfoundexception, ioexception{ fileinputstream f=new fileinputstream("f:\\pr\\src\\dmexam\\inp2.txt"); int size,nr=7,nc=5,j=0,i=0; char ch; string table[][]=new string[nr][nc]; size=f.available(); table[0][0]=new string(); while(size--!=0){ ch=(char)f.read(); if(ch=='\n') { i++; if(i>=nr) break; table[i][0]=new string(); j=0; continue; } if(ch==',') { j++; table[i][j]=new string(); conti...

java - Activiti Explorer - Request resource is not available -

i have big problem run activiti-explorer when try access: http://localhost:8080/activiti-explorer/ tomcat shows me http status 404 - requested resource not available. i'm don't have idea why dosen't work. can me? this have done on pc: i'm using 5.19.0 version of activiti-explorer 7.0.63 tomcat jdk 1.8.0.77 (i think there no point downgrade java previous versions (<=1.7) becouse main application using version) i'm sure have correctly configured environment variables ( java_home , jre_home , path , catalina_home ) i configured data base connection ( db.properties , context.xml ) in activiti-explorer.war , moved file tomcat/webapps i don't have errors activiti during tomcat start check if activiti explorer deployed tomcat in manager. http://{host}:{port}/manager/html more info in https://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html

android - Should FirebaseDatabase.getInstance() be used sparingly? -

for example when use sqlitedatabase in android, not idea open/close lots of sqlitedatabase helpers. instead better create sort of singleton makes sure have 1 database open. say have class static methods doing lots of firebase operations require databasereference. example: static void checkifuserismatched(...) static void notifyuser(...) static void modifyuser(...) is ok call firebasedatabase.getinstance() inside every method? create new databasereference inside each method? or better pass databasereference calling activity? static void notifyuser(muserreference, hisuserid) vs static void notifyuser(myuserid, hisuserid) --> create reference inside method what im looking optimize network usage , performance. or not matter , firebase handle me? firebasedatabase , databasereference objects can considered relatively cheap references underlying resources. the firebase sdk manages such things behind scenes. first call firebasedata.getinstance() set work, s...

angularjs - How to fix No 'Access-Control-Allow-Origin' header in Angular -

i trying access strava api , recieve error xmlhttprequest cannot load https://www.strava.com/api/v3/segments/626273/leaderboard?per_page=1&page=1&gender=f&access_token=xxxxx. no 'access-control-allow-origin' header present on requested resource. origin 'https://s3.amazonaws.com' therefore not allowed access. i can access link directly, not through request. below code based of off other solutions tried, didn't work. hosting in s3 bucket don't have server side trying solution in angularjs. app = angular.module('myapp', []); app.config(['$httpprovider', function($httpprovider){ $httpprovider.defaults.withcredentials = true; }]); app.controller('myctrl', function($scope, $http) { $http.get("https://www.strava.com/api/v3/segments/626273/leaderboard?per_page=1&page=1&gender=f&access_token=xxxxx").then(function(response) { $scope.mywelcome = response.data; }); });

ios - How to validate that a user is accessing your url from the app store? -

i'm trying save development time of adding user creation logic in ios app, , considering scenario: user purchases app through app store. via app, give them url lets them create signon site (since have purchased app). how validate signup legit (besides url)? apple provide kind of id check user against? edit: option provide additional button says "sign up", in addition current "sign in" button. take little more time, though. edit 2: change make non-opinion based. what if take app's receipt , send directly server? nsstring *receiptpath = [[[nsbundle mainbundle] appstorereceipturl] path]; nsdata *receiptdata = [nsdata datawithcontentsoffile:receiptpath]; nsstring *encodedreceipt = [receiptdata base64encodedstringwithoptions:null]; // send encodedreceipt server you server can validate receipt, use (original) transactionid app unique key, , credit user.

protocol buffers - bazel rules for the protobuf C++ compiler -

i'm using bazel , google's protocol buffers. want add bazel rule can generate c++ api .proto files. in gnu make, (simplified example): %.h: %.cc %.cc: %.proto protoc --cpp_out=. $< how can accomplish same (i.e. generate api whenever mymessage.proto changes) using bazel? native support cc_proto_library has landed in bazel: http://bazel.build/blog/2017/02/27/protocol-buffers.html . tl;dr, after setting workspace file once, cc_proto_library( name = "person_cc_proto", deps = [":person_proto"], ) proto_library( name = "person_proto", srcs = ["person.proto"], deps = [":address_proto"], ) ... then, $ bazel build :person_cc_proto there's example @ https://github.com/cgrushko/proto_library . the gist define proto_library "import" .proto file bazel, , cc_proto_library compile c++. protocol buffer compiler , runtimes taken default @com_google_protobuf//:protoc ...