Posts

Showing posts from June, 2015

Leaflet SVG icon from JavaScript with image -

it's possible create leaflet icon svg: var icon = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='10' height='10'><path stroke='red' stroke-width='2' fill='none' d='m 0,0 l 10,10 m 10,0 l 0,10 z'/></svg>"; var svgurl = "data:image/svg+xml;base64," + btoa(icon); var mysvgicon = l.icon({ iconurl: svgurl }); but when trying add image svg (with absolute url, seems doesn't working relative url either) this: var icon = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='10' height='10'><img src='http://www.gravatar.com/avatar/abc'/></svg>"; the image not dispayed. update: not working valid svg attributes, too: var icon = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='10' height='10'><image xlink:href='http://www

jquery - Javascript replace with regex not affecting string -

i have webapp task manager. the app recognises day/month in string. i have function replicate selected tasks today, trying make function update date in string. so, example, do task! 29/5 become do task! 1/6 . the function looks this: var d = new date(); var mon = d.getmonth()+1; var day = d.getdate(); $('input.replicatecheck:checkbox:checked').each(function(){ //string of row (nam) var nam = $(this).parent().find('input.row-name').val(); //replace existing date current date nam = nam.replace('\d{1,2}\/\d{1,2}',day+'/'+mon); console.log(nam); }); however isn't replacing date in string. the issue line: nam = nam.replace('\d{1,2}\/\d{1,2}',day+'/'+mon); why isn't working? edit following answers, requested, here working version of i'm trying achieve: $('button#go').click(function() { var text = $('#testinput').val(); var d = new date(); var mon = d

objective c - how to communicate between Native iOS custom plugin with Cordova 3.8 index.html via javascript in a phone gap application? -

i have referred many links maintaining bridge between ios custom plugin cordova index.html file using -(void)methodname:(cdvinvokedurlcommand*)command; and referred : ios javascript bridge but want maintain direct connection myplugin index.html.can suggest me better way implement this. i have created myplugin.js , myplugin.h , myplugin.m classes update location every 10sec. want send these (latitude , longitude parameters)from myplugin.m(ios plugin class) index.html class arguments my plugin.js //mybutton1 function myplugin() {} myplugin.prototype.sayhellocustom = function(data,data2) { exec(function(result){ alert('succescallback :' + result);}, //1.success callbal function(error){alert("error" + error); }, // 2.error call "myplugin", //3.native plugin calss name "sayhellocustom",

ruby on rails - devise_token_auth , bcrypt check equality on tokens -

i'm using devise_token_auth gem build public api. destroy session (sign_out) have send : uid (mail), client_id, , access-token (associated client_id) this method devise_token_auth gem checks if token still available, , if valid. github code def token_is_current?(token, client_id) # ghetto hashwithindifferentaccess expiry = self.tokens[client_id]['expiry'] || self.tokens[client_id][:expiry] token_hash = self.tokens[client_id]['token'] || self.tokens[client_id][:token] return true if ( # ensure expiry , token set expiry , token , # ensure token has not yet expired datetime.strptime(expiry.to_s, '%s') > time.now , # ensure token valid bcrypt::password.new(token_hash) == token ) end i have issues line bcrypt::password.new(token_hash) == token what know : token_hash token extracted db token came header of request the line using bcrypt "==" method compare, is def ==(secret); super(bcrypt::engine.hash_secr

javascript - Reload parent page(redirect to another page) after downloading file -

i have script wav files download: down.php : <?php if (isset($_get['file'])) { $file = $_get['file'] ; if (file_exists($file) && is_readable($file) && preg_match('/\.wav$/',$file)) { $filename = basename($file); header('content-type: application/wav'); header("content-disposition: attachment; filename=".$filename); readfile($file); } } else { header("http/1.0 404 not found"); echo "<h1>error 404: file not found: <br /><em>$file</em></h1>"; } ?> so when click on hyperlink in mypage.php : <a href=<?php echo "down.php?file=full_file_path"?>><?php echo "file_name"?></a> a file gets downloaded! how can reload mypage.php after download dialog box gets closed, when file gets downloaded? i've tried few things none of worke

c# - Collection of objects shared in different viewmodels -

in wpf application i've collection of objects received via socket. collection composed of dictionary<int, imyobject> , it's periodically filled/updated when object received on socket. i've 4 different viewmodel s gets subset of collection (i've myobjectholder static instance holding item , subset of doing as public ilist<myobject> listtypeone { { mylist.where(x => x.type == mytype) } } each time item inserted/updated, send notifyofpropertychanged on properties typeone typen . is there better implementation don't see? i've not heavily stress tested don't know how performs when i've large number of objects in collection. i'm not sure if best solution, here's do. create static instance of collection (you've done already.) have service, or something periodically update collection (you've done already) push notifications viewmodels force them refresh bindings. (the tricky part)

r - RStudio .rd-file - Binomial cofficient in Help file -

Image
i got minor problem keeps bugging me: i'm creating own r package , need documentation/help files that. i'm far, try work out how use \choose command in .rd-files. keeps producing weird output in pdf create via .rd-files. use that: \deqn{p(k \leq x \leq s) = \sum\limits_{i = k}^{s} \choose(s,j)u^j(1-u)^{s-j} } which delivers me which wrong. if leave out choose command, want here (missing binomial coefficient of course). tried combination think of \choose{s,k}, \choose{s}{k} , gives me same output. ideas? thanks in advance! choose odd. try {{s}\choose{j}}

sql server 2008 r2 - SQL - check if the dates are in correct sequence -

i have table this: id start end 1 1-1-2015 29-1-2015 2 30-1-2015 28-2-2015 3 1-3-2015 30-3-2015 .... now need sql query check if date missed between end date of row , start dat e of next row. e.g. if end date 29-1-2015 start date of next row should next date of i.e. 30-1-2015 . if date missed should return error. you can use apply next record (assuming defining next using order of id), filter out start of next record not match end of current record: select * yourtable t1 cross apply ( select top 1 t2.[start] yourtable t2 t2.id > t1.id order t2.id ) nextstart nextstart.[start] != dateadd(day, 1, t1.[end]); if id column has no gaps, use join: select * yourtable t1 inner join yourtable nextstart on t2.id = t.id + 1 nextstart.[start] != dateadd(day, 1, t.[end]); if start of 1 period should day after end of previous, why not stor

android - How update the values using http put method asynctask -

i new android , trying update these values , should httpput method. know , post method please can guide me convert put method. in post method jsonobject json = new jsonobject(); json.put("id", "15"); json.put("lid", enid); json.put("name",assetname); json.put("des",description1); httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(url); jsonobj = json.tostring(); httppost.setentity(new stringentity(jsonobj)); httppost.setheader("accept", "application/json"); httppost.setheader("content-type", "application/json"); httpresponse httpresponse = httpclient.execute(httppost); int statuscode = httpresponse.getstatusline().getstatuscode();

javascript - How to programmatically srcoll to the extreme left point in Highcharts -

i new highcharts please pardon me. actually, using highcharts (type: column) , scrollbar enabled. requirement programmatically select column might have scrolled extreme left. i able select column need manually scroll there in order see selection. although, tried setting extremes using setextremes() method , redrawing chart using chart.redraw(). works fine , selected column in display area. but, know there better way of doing same, need not redraw entire chart every time. please let me know if need further details.

mysql - How can I write this SQL query? -

i wondering if on sql query. it´s test failed , wanted learn. i've spent lot of time on it, watched tutorials on sql still don't how written.. there 2 tables (flights, occupation_flights) flight information , task to: write query gives list of flights next 7 days, , shows flight, number of available seats, number of occupied seats , % of occupied seats. flights: flight id_company date origin destination places 1003 d3 20/01/2006 madrid londres 40 1007 af 20/01/2006 paris malaga 12 1003 15 30/01/2006 madrid londres 20 1007 af 30/01/2006 paris malaga 17 (places show number of places offered on each flight) occupation_flights: flight id_company date passenger seat 1003 ib 20/01/2006 07345128h 01v 1003 ib 20/01/2006 1013456213 01p 1003 ib 20/01/2006 08124356c 02v 1003 ib 20/01/2006 57176355k 02p 1007 af

How to change a MD5 password for an admin/control panel in phpMyAdmin? (PHP/MySQL) -

i have php site admin area, on setup selected simple password. e.g. '123456'. not intended permanent solution. when comes changing password on database using phpmyadmin, become stuck. used md5 generate password (this fact might not relevant), if update password in database md5 hashed password. e.g. 'newpassword' ('5e9d11a14ad1c8dd77e98ef9b53fd1ba') save it. making no difference admin login area. although database updated, password remains previous, in example '123456'. there must else needs updating not sure start looking. you have to: check if script create caches (delete caches in case). call script's support problem another solution can't offer because don't know script use.

php - How do I create a dynamic array for a google combo chart with a database? -

i trying make combo chart (googlecharts) needs dynamic corresponding database data. i got database table called planning, has user_id, project_id , status of planning. want make combo chart show number of projects (status) per week every employee. so numbers hardcoded in array numbers want make variable database data, have no idea how begin building array. i using laravel(eloquent) if wondering doing models. $fd = input::get('fd'); $ld = input::get('ld'); $pid = input::get('pid'); $getplanning = planning::wherebetween('date', array($fd, $ld))->where('project_id', $pid)->get(); $getemployees = (project::find($pid)->users); $employees[] = 'days'; foreach($getemployees $employee) { $employees[] = $employee->firstname.' '.$employee->middlename.' '.$employee->lastname; }

javascript - multiple operations using jquery ajax -

i want perform operation , simultaneously show progress in html5 , javascript. since using ie 8, <progress> element not supported, approach thought of using jquery ajax method this: <div class="progress-bar" role="progressbar" id="id" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">complete</span> </div> $(document).ready(function(){ $("button").click(function(){ $.ajax({ url: "perform server side operation", success: function(result){ progressbarupdate(20); } }); }); }); var progressbarupdate = function(value) { value = value + 10; $("#id").css("width", value +"%"); } but issue here how perform operation , update progress bar simultaneously? because after coming success: part of ajax request, directly showing 100% progress doesn'

typechecking - to check type of input in c++ -

## check type of data entered in cpp ## int main() { int num; stack<int> numberstack; while(1) { cin>>num; if(isdigit(num)) numberstack.push(num); else break; } return(0); } if declare variable interger, , input alphabet, 'b', instead of number, can check behavior of user? code above exits when first number entered , not wait more inputs. first of all, std::isdigit function checks if character digit. secondly, using input operator >> make sure input number, or state flag set in std::cin object. therefore e.g. while (std::cin >> num) numberstack.push(num); the loop end if there's error, end of file, or input not valid int .

reactjs - React - REST Defined List of components by REST -

i'm going explain i'am trying achieve in flux/react application. this routing : var routes = ( <route name="layout" path="/" handler={layout}> <route name="page" path=':section/:detail' handler={page} /> <route name="login" path='/login' handler={login}/> <defaultroute handler={layout}/> </route> ); exports.start = function() { router.run(routes, function (handler, state) { var params = state.params; react.render(<handler params={params}/>, document.body); }); } i have rest service giving returning array of components described objects : { "components" : { "header" : { //data }, "tabs" : { //data } } } basically tough have page.jsx component can handle data given rest api , define page structure. i'm having trouble understanding how mana

How to use TIME type in MySQL? -

i'm building first db through mysql workbench. in table need store time attribute contains minutes , seconds. in regard, wanted use time data type. argument required type time(...)? thanks i solved, entered time without parentheses. thought type time required input parameter. create table if not exists cookingdb . recipe ( ... cookingtime time null, ...

java - Change jspinner (date) min and max values from (database) variables SOLVED FOR MIN -

so problem, i pull data set database, , populate combobox it. so can see in shoot http://prntscr.com/7bscob .. min , max jspinner values should depend on combobox selected item . so i've tried set minimal value dynamically, sends illegalargumentexception @ line did that. for(int i=0; i<turniri.size(); i++) { if (turniri.get(i).getnaziv().equals(selectedturnir)) { t=turniri.get(i).getid(); long l = turniri.get(i).getdatumpocetka().gettime(); spinner.setmodel(new spinnerdatemodel(new date(1431986400000l), new date(l), new date(1433109600000l), calendar.day_of_year)); } } edit: thanks @dragondraikk exception in thread "awt-eventqueue-0" java.lang.illegalargumentexception: (start <= value <= end) false @ javax.swing.spinnerdatemodel.<init>(unknown source) @ gui.izvjestajrezultatazajedantakmicarskidan$3.ac

jsf 2 - jsf composite component convert -

i have composite component <cc:interface> <cc:attribute name="value" required="true" /> <cc:editablevalueholder name="converter" targets="jsfunction"/> </cc:interface> <a4j:jsfunction name="update"> <a4j:param name="val" assignto="#{cc.value}" id="jsfunction" /> </a4j:jsfunction> which used as <my:update value="#{bean.value}" > <f:converter converterid="beanconverter" for="converter"/> </my:update> when opening page following error caused by: java.lang.classcastexception: org.richfaces.component.uiparameter cannot cast javax.faces.component.valueholder @ com.sun.faces.facelets.tag.jsf.convertertaghandlerdelegateimpl.applyattachedobject(convertertaghandlerdelegateimpl.java:120) [javax.faces-2.2.11.jar:2.2.11] @ javax.faces.view.facelets.faceletsattachedobjecthandler.applyattachedo

Php web application can't process clearDB mysql service on bluemix -

i'm trying deploy php web application on bluemix. have bound cleardb mysql service application. vcap_service variable provided me. when use variable perform simple sql query, application page nothing, while same code doing xamp localhost. please me. here code : <?php $servername = "us-cdbr-iron-east-02.cleardb.net"; $username = "b23807********"; $password = "********"; $dbname = "ad_70723170af1****"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } // sql create table $sql = "create table flybird ( id int(6) unsigned auto_increment primary key, firstname varchar(30) not null, lastname varchar(30) not null, email varchar(50), reg_date timestamp )"; if ($conn->query($sql) === true) { echo "table flybird created successfully"; } else { echo "

emacs - How to define a function with a variable number of arguments? -

instead of this: ((lambda (a b) (apply '+ (list b))) 1 2) it possible write in scheme: ((lambda args (apply '+ args)) 1 2) now possible pass more 2 arguments function. when try in emacs lisp error: invalid function. how define function in emacs lisp? in emacs lisp, can put &rest in argument list of function, remaining arguments list: (lambda (&rest args) (apply '+ args))

c++ - how to emplace_back(pair) efficiently? -

i have using namespace std; // convenience in question vector<pair<array<int,3>, int>> foo; and want emplace_back element pair::first holding {i,j,k} , pair::second holding q . way compiling rather clumsy foo.emplace_back(piecewise_construct, forward_as_tuple(i,j,k), forward_as_tuple(q)); is efficient (i.e. guaranteed tuple s optimised away)? or there way guaranteed efficient? (i tried foo.emplace_back(std::initializer_list<int>{i,j,k}, q); but no avail gcc 4.8.1). know can avoid problem defining struct element : std::pair<std::array<int,3>,int> { element(int i, int j, int k, int q) { first={i,j,k}; second=q; } }; vector<element> foo; foo.emplace_back(i,j,k,q); but i'd prefer without such code. std::array<t, n> doesn't have constructor taking std::initializer_list<u> u , not u = t . don't mistake fact can initialised braced-init-list presence

css - Bootsrap Form Group & Input Group -

Image
i've been playing below code hours. essentially, i'd small input field 2 buttons next it! i'm unable buttons line text field, , combination of classes seems have shrunk text field drastically. what's missing/needs changing buttons appear correctly alongside text field? <form method="post"> <div class="form-group col-xs-3"> <label for="cuein">cue in</label> <div class="input-group col-sm-10"> <input type="text" class="form-control" id="cuein" name="cuein" value="<?php if(isset($id3_tags_mairlist_cuein)) { echo $id3_tags_mairlist_cuein; } ?>"> <span class="input-group-addon"> <button type="button" class="btn btn-default btn-sm glyphicon glyphicon glyphicon-time" aria-label="left align" aria-hidden="true" id="b

c# - Math.Net Numerics: Error in sampling from Negative Binomial -

i'm using math.net sample values overdispersed poisson distribution. i'm doing using negative binomial link, described here: https://stat.ethz.ch/pipermail/r-help/2002-june/022425.html my code looks this: private static double odpoisson(double lambda, double dispersion) { double p = 1 / (dispersion - 1); double r = lambda * p; if (dispersion == 1) { return poisson.sample(lambda); } else { return negativebinomial.sample(r, p); } } what i've found works low values of lambda. try sample lambda of 1000 , dispersion parameter of 2, code 'hangs', i.e. method keeps running no value returned. i've looped through method test various combinations of input parameters (lambda 1 1000, dispersion = 2), , code 'hangs' @ different combinations every time. it'll sample combinations lambda = 750, other times lambda = 500. happens re-running console app , making n

vb.net New line in string paragraph -

i'm going break line in paragraph. is there such thing \n break line in string? dim info string = "page name \n date , time" & datetime.now.tostring("yyyy-mm-dd, hh:mm:ss") & "\n printed admin" use vblf dim info string = "page name " & vblf & " date , time" & datetime.now.tostring("yyyy-mm-dd, hh:mm:ss") & "" & vblf & " printed admin"

iphone - Simulator Vs IOS Device Performance -

i'm creating platform app has ground nodes moving, being disposed , regenerating. when running app on simulator noticeable glitch in apparent, when running on device, can see there not glitch. my question is, should device perform better simulator or maybe not noticing glitch on device because small. previous article have suggested simulator should perform better, these articles in reference iphone 3gs, wondering if newer iphones out performing simulator. my device iphone 5 , running ios 8.2 , simulator version 8.3. it's general usage testing. device performs in entirely different environment computer, , it's best way make sure if push app out devices, nothing unexpected happen. example, phone/pad may have limited data coverage, low memory situations, incoming calls etc.. these situations lot more common on devices, when people emulate though simulator. on hardware point of view, device uses different processor architecture mac, needs accounted (not as

How to allow only POST calls to serve Nginx static json files -

hi trying serve static json files nginx. want serve these static files via post request , disable calls. is there way so. i refered looks hack , looking more reliable solution just include following in location block static files: limit_except post { deny all; } this send 403 every request not using post http method.. btw, there different ways achieve this, such cors, think it's out of scope here.

javascript - Express JS Router Middleware - Body Parser - req.body has hyphen -

i receiving parsed emails mailgun posted via api url end point set up. url receives http posts expressjs route mongodb using body parser middleware. have http post route working fine mongodb simple text keys 'sender', have issue format of of message parameters containing hyphens. instance "body-plain". express throws error if include parameter of "req.body.body-plain". have work around? i prefer not regex entire string. here example of email response being posted: recipient: 'postmaster@appmail.sisdaf.com', sender: 'kevsdaf@mail.com', subject: 'tewsgs', from: 'kevin psdit <kesdfit@gmail.com>', 'x-envelope-from': '<kasdftit@gmail.com>', 'body-plain': 'this test\r\n', received: [ 'from mail-qk0-f179.google.com (mail-qk0-f179.google.com [209.85.220.179]) mxa.mailgun.org esmtp id 556bfda1.7f7658358ef0- in01; mon, 01 jun 2015 06:37:21 -0000 (utc)'

java - Query to AD for unlimited results -

i using next code users in ad hashtable<string, string> env = new hashtable<string, string>(); env.put(context.initial_context_factory, "com.sun.jndi.ldap.ldapctxfactory"); env.put(context.provider_url, "ldap://grupoasisa.local:636"); env.put(context.security_protocol, "ssl"); env.put(context.security_principal, "domasisa\\"+user_service); env.put(context.security_credentials, password_service); try { dircontext ctx = new initialldapcontext(env, null); searchcontrols searchctls = new searchcontrols(); string returnedatts[]={"samaccountname", "description", "mail"}; searchctls.setreturningattributes(returnedatts); //specify search scope searchctls.setsearchscope(searchcontrols.subtree_scope); searchctls.settimelimit(0); searchctls.setcountlimit(0); //specify ldap search filter string searchfi

ios - Programatically create navigation controller with back button -

i haven't been able figure out in swift in appdelegate. i've been working on little problem weeks (in background, not continuously) lots of googling. must missing something. when remote notification comes in ios app i'd modally present view appropriate message, uinavigationcontroller has button. idea when user finished dealing notification, can press "back" , go were. can't "back" button show in navigation controller programatically. not of existing views embedded in navigation controllers. so, rather finding existing uinavigationcontroller in stack, i've been creating new uinavigationcontroller , trying set , present this: let mainstoryboard: uistoryboard = uistoryboard(name: "main", bundle: nil) var mvc = mainstoryboard.instantiateviewcontrollerwithidentifier("myviewidentifier") as! myspecialviewcontroller /* here setup necessary variables in mvc view controller, using data remote message. don'

javascript - youtube iframe player, video appears cropped in android -

i trying play youtube videos on android devices using webview , youtube iframe api. when tested on 4.4, 5.0, , 5.1. testing same on 4.3 video seems cropped. ie video occupies 70% of webview area. solutions ?!?! my code follows.. java code wvvideo = (webview)findviewbyid(r.id.wvvideo); wvvideo.setwebchromeclient(new webchromeclient()); websettings websettings = wvvideo.getsettings(); websettings.setjavascriptenabled(true); websettings.setmediaplaybackrequiresusergesture(false); wvvideo.addjavascriptinterface(new webappinterface(this), "android"); wvvideo.loadurl("http://test.com/iframeyoutube.html?videoid="+videourl); wvvideo.loadurl("javascript:playvideo();"); xml <webview android:id="@+id/wvvideo" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerinparent="true" android:background="#212121"></webview> html <!doctype html> <

c# - getting null while deserialization json -

i trying deserialize web response json object, @ time object getting null after deserialization. code: json response: { "@odata.context": "https://outlook.office365.com/api/v1.0/$metadata#me/calendarview", "value": [ { "@odata.id": "https://outlook.office365.com/api/v1.0/users('sathesh@newtechsolution.onmicrosoft.com')/events('aamkadqzmgvmnjzmlwy1yjatngfkys1hody0ltdimwzlzjzjymiwoabgaaaaaaaaluoeh9c2qq33mvktcqzgbwd1qtj3io57qawz9mzf6weaaaaaaaenaad1qtj3io57qawz9mzf6weaaaaaaa0kaaa=')", "@odata.etag": "w/\"9ue49ydue0glmftgreshmgaaaaanag==\"", "id": "aamkadqzmgvmnjzmlwy1yjatngfkys1hody0ltdimwzlzjzjymiwoabgaaaaaaaaluoeh9c2qq33mvktcqzgbwd1qtj3io57qawz9mzf6weaaaaaaaenaad1qtj3io57qawz9mzf6weaaaaaaa0kaaa=", "changekey": "9ue49ydue0glmftgreshmgaaaaanag==", "categories": [], "datetimecreated":

mongojs - mongodb update and/or change an array key without using the value -

i'm having trouble removing/renaming array object mongodb. { "_id" : objectid("556a7e1b7f0a6a8f27e01b8a"), "accountid" : "ac654164545", "sites" :[ { "site_id" : "example1.com" }, { "002" : "example2.com" }, { "003" : "example3.com" }, { "004" : "example4.com" }, { "005" : "example5.com" }, { "006" : "example6.com" } ]} } please take notice of array key "site_id", want change "001" either removing , appending it, know how do, or rename it. i've tried: db.accounts.update({'id':objectid("556a7e1b7f0a6a8f27e01b8a")}, {$unset: {sites.site_id}}) but says "unexpected token". tried: db.accounts.update({'id':objectid("556a7e1b7f0a6a8f27e01b8a")}, {$unset: {sites:site_id}}

javascript - Adding an id code into input value -

i have html code displaying geolocation : <span id="currentlat"></span>, <span id="currentlon"></span> combined javascript code works perfectly. problem want display above value in textfield. i did try : <input id="" value="<span id="currentlat"></span>, <span id="currentlon"></span>" size="30" /> but give me error. how add value textfield value? nb: i add javascript code used know what's wrong code, maybe code cannot working in text input field. <script> window.onload = function() { var startpos; if (navigator.geolocation) { navigator.geolocation.getcurrentposition(function(position) { startpos = position; document.getelementbyid("startlat").innerhtml = startpos.coords.latitude; document.getelementbyid("startlon").innerhtml = startpos.coords.long

objective c - issue while vibrating iPhone ios sdk -

i want vibrate , flash light simultaneously.but when use following code flash light . if (some condition) { audioservicesplaysystemsound(ksystemsoundid_vibrate); [self settorch:yes]; } but when use audioservicesplaysystemsound(ksystemsoundid_vibrate); my phone vibrates. i unable find issue. may useful you find gonna vibrate device alert user? read first both functions vibrate iphone. when use first function on devices don’t support vibration, plays beep sound. second function on other hand nothing on unsupported devices. if going vibrate device continuously, alert, common sense says, use function 2. audioservicesplayalertsound(ksystemsoundid_vibrate); audioservicesplaysystemsound(ksystemsoundid_vibrate);

youtube api - YouTubeAPI v3 - "Daily Limit Exceeded" error before my app reaches API quota limit -

daily, between 11:00pm , 2:00am edt, requests youtube v3 api start failing "dailylimitexceeded" error, status code 403. error stops @ 3:00am edt. app hasn't yet reached 50,000,000 units limit. idea why happening? { "error": { "errors": [ { "domain": "usagelimits", "reason": "dailylimitexceeded", "message": "daily limit exceeded" } ], "code": 403, "message": "daily limit exceeded" } } this started occurring on may 19th, though app's api usage hasn't changed since few weeks before 19th. since issue started, api units app has used 44,995,660 out of allowed 50,000,000. app ends each day between 42,000,000 , 45,000,000 units used. per-user-limit 3,000 requests/second/user (i highly doubt api calls users dense late @ night). any ideas on why

javascript - Jquery: get value of closest button -

here html code <div class="panel-footer"> <div class="input-group"> <input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="write message here..." ng-model="messagetosend"> <span class="input-group-btn"> <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="79">send</button> </span> </div> <div class="input-group"> <input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="write message here..." ng-model="messagetosend"> <span class="input-group-btn"> <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="80">send</button> </span> </div> </div> and here jquery code $(doc

python - Sorting large numbers -

if 1 has list of very large numbers in python, so compiler cannot value of them numbers. there function sort list (while keeping numbers integers) in more efficient way such comparing number number? (but without converting string) both python 2 , python 3 handle arbitrarily large integers: >>> [2**34, 2**38, 2**99, 2**122, 2] [17179869184, 274877906944, 633825300114114700748351602688l, 5316911983139663491615228241121378304l, 2] and sort them expected: >>> sorted(_) [2, 17179869184, 274877906944, 633825300114114700748351602688l, 5316911983139663491615228241121378304l] (python 2 show l integers larger sys.maxint in example here while python 3 shows integer values same smaller or larger integers)

php not connecting to mysql database MAMP -

so have php connect database i'am running using mamp not working. class.database.php (sorry code bit messy). guy think problem or else in code? help. <? class dbconnection { protected $db_conn; public $db_name = 'todo'; public $db_user = 'root'; public $db_pass = 'root'; public $db_host = 'localhost'; function connect(){ try{ $this->db_conn = new pdo("mysql:host=$this->db_host;db_name=$this",$this->db_user,$this->db_pass) return $this->db_conn; } catch(pdoexception $e) { return $e->getmessage(); } } } ?> you need replace db_name=$this with db_name=$this->db_name also, need place semi-colon @ end of line. with mistakes, should getting php , pdo errors. check php logs errors. can run script command line using

order - How to make a SQL request ordered by amount of true conditions -

imagine have 10 conditions in 'where' clausule of 'select' request. i need show results satisfied @ least 5 of conditions, , ordered amount of satisfied conditions: 10,9,8... how can posible? thanks lot :) this may vary based on dbms you're using, ms-sql, clause segmented separate case statements summed , sorted: select *, case when (condition 1) 1 else 0 end + case when (condition 2) 1 else 0 end (...) + case when (condition 10) 1 else 0 end matchcount mytable order matchcount desc you can wrap sub-query results matching @ least 5: select * ( select *, case when (condition 1) 1 else 0 end + case when (condition 2) 1 else 0 end (...) + case when (condition 10) 1 else 0 end matchcount mytable) t t.matchcount >= 5 order matchcount desc

iphone - Is there a popcount() for both Simulator and iOS device? -

the closest thing can find t popcount(t x) in metal standard library . is there simpler version, like: #include <x86intrin.h> __builtin_popcount(); which compiles simulator not iphone device ... don't #include <x86intrin.h> : // #include <x86intrin.h> __builtin_popcount();

python - How to integrate a --worker-class of gunicorn in supervisor config setting? -

i have configured supervisor on server this: [program:myproject] command = /home/mydir/myproj/venv/bin/python /home/mydir/myproj/venv/bin/gunicorn manage:app -b <ip_address>:8000 directory = /home/mydir i have installed gevent on virtual environment don't know how can implement on supervisor command variable, can run manually through terminal this: gunicorn manage:app -b <ip_address>:8000 --worker-class gevent i tried include path when call gevent in supervisor command python , gunicorn, it's not working, honestly, don't know what's correct directory/file execute gevent , not sure if correct way execute worker class in supervisor. running on ubuntu v14.04 anyone?thanks already made solution this. not 100% sure if correct, after searching hundred times, came working solution :) got here , i've created gunicorn.conf.py file on project directory containing: worker_class = 'gevent' and integrated file on supervisor confi

php - Limit 10 records from posts for each category -

this question has answer here: using limit within group n results per group? 14 answers i have 2 table categories , posts , don't want records each category. want limited rows each category. categories table below :- id name slug posts table below :- id [ pk ] title slug content category [key - foreign key] publish_date what trying achieve , want 10 records posts each category . what doing @ moment dangerous, runs lots of query, want minimize 1 query. <?php $fetchcat = $mysqli->query("select * categories"); while($row = $fetchcat->fetch_assoc()) { $fetchpost = $mysqli->query("select id, title, slug posts category=".$mysqli->real_escape_string($row['id'])." limit 10"); // processing code. } ?> can have " inner join " query, can reduce query

linux - Processing file paths with parentheses with Python subprocess -

the paths of files want process contain parentheses in them. path = "/dir/file (with parentheses).txt" i'm trying process them in python follows: subprocess.call("./process %s" % path, shell=true) however, following error /bin/sh: 1: syntax error: "(" unexpected how can pass correct string process proper path? try this subprocess.call('./process "%s"' % path, shell=true) i guess problem more space in file name. file names spaces in them should enclosed in quotes ./process "foo bar.txt" or escaped ./process foo\ bar.txt .

Laravel 5 event not working -

sr, try using laravel 5 example below, not working. namespace app\events; use illuminate\queue\serializesmodels; class didsomething extends event { use serializesmodels; public function __construct() { return; } } and handles namespace app\handlers\events; use app\events\didsomething; class dosomething { public function __construct() { } public function handle(didsomething $event) { dd($event); } } and eventserviceprovider.php namespace app\providers; use illuminate\contracts\events\dispatcher dispatchercontract; use illuminate\foundation\support\providers\eventserviceprovider serviceprovider; class eventserviceprovider extends serviceprovider { /** * event handler mappings application. * * @var array */ protected $listen = [ app\events\didsomething::class=>[ app\handlers\events\dosomething::class ] ]; /** * register other events application. * * @param \i

gaussian class in java -

i making class simulates gaussian integer. using constructor in addition method add 2 two parts of gint , return new gint sum. reason when trying implement method, java says gint required when initialize new gint , found void. why be? have included class below , indicated line causes error. public class gint { private int real; private int imag; public void gint(int r) { imag=0; real=r; } public void gint(int r, int i) { real=r; imag=i; } gint add(gint rhs) { gint added; int nreal=this.real+rhs.real; int nimag=this.imag+rhs.real; added= gint(nreal,nimag); //--> says requires gint , found void return added; } } use implementation , happy: public class gint { private int real; private int imag; public gint(int r) { imag=0; real=r; } public gint(int r, int i) { real = r; imag = i; }