Posts

Showing posts from September, 2012

security - SSL trusted for local web server is possible? -

i have local server in home, runs website, provides service, use of php. right i'm using http protocol, doesn't not provide security, due clear-text (the authentication service username , password access protected page). want upgrade https , of course need use ssl. know is, know differences between self-certificate, , 1 issued company. there different kind of class. because don't want users/friends alerted browser ssl certificate isn't trusted, i'm asking if there free trusted certificate non-domain web server (i use static ip let user access website). in case bought domain (it cheaper), can have free trusted certificate ? thank you. regarding ssl certificates ip address, see linked thread: is possible have ssl certificate ip address, not domain name? if register domain name site, can obtain free ssl certificate startssl ( https://www.startssl.com/?app=1 )

ios - iOS8 custom keyboard - add UIImageView -

i built keyboard keyboard extension available in ios 8. created custom view , want create button image background, image not appear in keyboard. needs done put image on custom keyboard? my code (call view): uiview *layout = [[[nsbundle mainbundle] loadnibnamed:@"kyyboardlogic" owner:self options:nil] objectatindex:0]; [self.inputview addsubview:layout]; thanks: yakir. instead of adding subview, use code. adds view input view given superview. self.keyboard = [[[nsbundle mainbundle] loadnibnamed:@"keyview" owner:nil options:nil] objectatindex:0]; self.inputview = (id)self.keyboard;

multithreading - Can mutli-threading java client cause high CPU utilization of SQL Server 2008? -

i java developer, not dba, , consult issue encountered in high cpu utilization in sql server 2008 (not in java app server) . the java client uses multi-threading, simplify: 40 threads each select / insert / update (simple sql statements) table x - autocommit on 10 threads each select / insert / update (simple sql statements) table y , selects (again simple) table x (to check existence) - autocommit on both set of threadpools run simultaneously. each thread assigned "message queue" (a file), loads / reads assigned "message", , inserts / updates corresponding table. these 2 thread pools connections single connection pool via datasouce, example: <resource auth="container" driverclassname="com.microsoft.sqlserver.jdbc.sqlserverdriver" maxactive="100" maxidle="10" maxwait="10000" name="jdbc/abc_datasource" password="p" type="javax.sql.datasource" url="jdbc:sqlserv

sharepoint search using rest api -

i doing search in sharepoint 2013 using rest api. working fine. when enter search term in search text box, crawls through whole content of site , shows pages in result contain search term. possible crawl through part of pages(e.g body content, leaving header , footer) , through page names only? i got answer. put class "noindex" on element don't want appear in search result. in case, put class "noindex" on divs containing header, footer , menuholder.

how to run and modify a cmd script or file in c -

@echo off set "yourdir=c:\users\asus\desktop" echo:list files: %%a in ("%yourdir%\*") echo %%~fa echo:list directories: /d %%a in ("%yourdir%\*") echo %%~fa echo:list directories , files in 1 command: /f "usebackq tokens=*" %%a in (`dir /b "%yourdir%\*"`) echo %yourdir%\%%~a pause i have cmd script , want include , run in c script and if possible modify (the cmd script contains variables ). do have solution ? update you can create script file on-the-fly in c program call from. note must handle characters " , \ , % specially when part of string literal, using \" , \\ , %% respectively. #include <stdio.h> #include <stdlib.h> void fatal(char *msg) { printf("%s\n", msg); exit (1); } void makebat(file *fp, char *dirname) { fprintf (fp, "@echo off\n"); fprintf (fp, "\n"); fprintf (fp, "set \"%s=c:\\users\\asus\\desktop\

regex - Regular expression java to extract the balance from a string -

i have string contains " dear user bal= 1,234/ " . want extract 1,234 string using regular expression. can 1,23 , 1,2345 , 5,213 or 500 final pattern p=pattern.compile("((bal)=*(\\s{1}\\w+))"); final matcherm m = p.matcher(text); if(m.find()) return m.group(3); else return ""; this returns 3 . regular expression should make? new regular expressions. you search in regex word characters \w+ should search digits \d+ . additionally there comma, need match well. i'd use /. bal=\s([\d,]+(?=/). / as pattern , number in resulting group. explanation: .* match before bal= match string "bal=" \s match whitespace ( start matching group [\d,]+ matches every digit or comma 1 ore more times (?=/) match former if followed slash ) end matching group .* matches thereaft this untestet, should work this: final pattern p=pattern.compile(".*bal=\\s([\\d,]+(?=/)).*"); final matcherm m = p.matcher(text); if

HttpURLConnection java.io.FileNotFoundException in android 5.0.2 -

i using below code downloading pdf file server , store sdcard. running fine on android 4.4 device. while not working on android 5.0.2 device. public static string downloadfile(string fileurl, file directory){ try { url url = new url(fileurl); httpurlconnection urlconnection = (httpurlconnection)url.openconnection(); urlconnection.setrequestmethod("get"); urlconnection.setdooutput(false); urlconnection.connect(); inputstream inputstream = urlconnection.getinputstream(); fileoutputstream fileoutputstream = new fileoutputstream(directory); int totalsize = urlconnection.getcontentlength(); byte[] buffer = new byte[megabyte]; int bufferlength = 0; while((bufferlength = inputstream.read(buffer))>0 ){ fileoutputstream.write(buffer, 0, bufferlength); } fileoutputstream.close(); resu

relativelayout - How to make 2 horizontal buttons to fill relative layout equally? -

Image
the corresponding xml layout: <relativelayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttons_holder" android:layout_below="@+id/list_holder" android:layout_alignparentbottom="true"> <imagebutton android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/previous_button" android:src="@android:drawable/ic_media_previous" android:layout_alignparentleft="true" android:minwidth="150dp" android:layout_alignparentbottom="false" android:layout_alignparentright="false" android:layout_alignparenttop="false" android:scaletype="fitend" /> <imagebutton android:layout_width="wrap_content" android:layout_height=&qu

zend framework - ZendFramework error: getaddrinfo failed: nodename nor servname provided -

i install mysql, php nginx on mac os x. first time install on mac, far i've used linux. i got error when try run zend application. i tried instead of localhost enter ip adress , 127.0.0.1, same error. fatal error: uncaught exception 'zend_db_adapter_mysqli_exception' message 'php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known' in zendframework-1.10.7/library/zend/db/adapter/mysqli.php:333 stack trace: 0 zendframework-1.10.7/library/zend/db/adapter/abstract.php(304): zend_db_adapter_mysqli->_connect() 1 zendframework-1.10.7/library/zend/db/adapter/mysqli.php(194): zend_db_adapter_abstract->getconnection() 2 zendframework-1.10.7/library/zend/db/table/abstract.php(823): zend_db_adapter_mysqli->describetable('site_page', null) 3 zendframework-1.10.7/library/zend/db/table/abstract.php(862): zend_db_table_abstract->_setupmetadata() 4 zendframework-1.10.7/library/zend

iOS banner notification -

Image
i noticed banner notification on iphone haven't seen before. can't find description of these banners, example here . here are: first of them appears when app goes in background. tap on banner shows app again. second appears when create hotspot , tap on shows hotspot settings. so, questions are: what these banners? why have different colors? how can create same banner in own app? the blue banner there if "personal hotspot" feature turned on, , other device using shared internet connection. the red banner shown example if app not in foreground accessing microphone. both banners provided operating system , not customizable app developers. these banners can make problems when app not prepared re-layout views result of banner appearing or disappearing. therefore, can simulate banner in ios-simulator pressing cmd-y (xcode6 ios simulator => hardware => toggle in-call status bar). furthermore, these banners not "notifications",

Prestashop show cart summary in the bankwire payment execution page -

in prestashop want show cart summary contents in default payment module bankwire. lets user select payment method bankwire redirect bankwire payment page cart summary showing @ top of page. so can tell me how total cart summary contents in bankwire payment execution page. , suggestions appreciable. thanks this done module .

c# - Drawing some elements over others on canvas -

i have list of figures, have different coefficients. draw figures higher coefficient above have lower. how can accomplish task? set panel.zindex property, which gets or sets value represents order on z-plane in element appears you may bind zindex coefficient property of view model: <polyline points="{binding figure}" panel.zindex="{binding coefficient}" .../>

asp.net - Web Services (SOAP) - How to work with xmlnodes contained in an interface -

i've added in service reference project has generated several methods contained in interface. here example: public interface clientservicesoap { [system.servicemodel.operationcontractattribute(action="https://service.service.com/getagentsingroup", replyaction="*")] [system.servicemodel.xmlserializerformatattribute(supportfaults=true)] system.xml.xmlnode getagentsingroup(string username, string password, int groupid); [system.servicemodel.operationcontractattribute(action="https://service.service.com/getagentsingroup", replyaction="*")] system.threading.tasks.task<system.xml.xmlnode> getagentsingroupasync(string username, string password, int groupid); how work these xmlnodes consume them , return information in web application? in example, how agents method?

Self-Signed SSL Certificate Trust from iOS App -

i building app retrieves data server. server can installed elsewhere (i have built server) , after setting correct host in app go. now problem. trying make things secure possible, , 1 of aspects using ssl. using self-signed certificates on server side, can't accepted ios app. @ first got warning certificate not trustworthy pc running server, after found answer [1], got "https" being accepted browser (and fiddler), turns green when calling server url, working fine, pc server running. when try call url external device, again message certificate not trustworthy (which understand because signed certificate myself, here looking way baypass that), , inside app cannot establish connection. so, can set self-signed certificate "trustworthy" external devices? (expecting every customer buy own certificate not option.) or, there apple-approved way accept certificate inside ios app? know can accepted changing in private api of nsurlrequest (if interested can exp

ios - Invalid Bundle structure The binary file "WatchKitSupport/WK" is not permited -

i'm trying validate app itunesstore, app have watchkit extention. archive validate these messages: itunes store operation failed. invalid bundle structure - binary file 'watchkitsupport/wk' not permited. app can't contain standalone executables or libraries, other cfbundleexecutable of supported bundles. you including executable files in app shouldn't there. for more info: http://onebigfunction.com/ios/2015/03/15/invalid-bundle-structure/

php - How can I calculate distance travelled for a user's journey? -

in database, have few thousand rows latitude , longitude stores. in php , how can calculate total distance user has travelled on journey stored in database recorded latitude , longitude points? is there mathematical equation can reference or something? in system performing calculation on queue , caching user's journey won't change after system has recorded efficiency isn't issue. i ideally output total of distance travelled in miles. thanks! update: here code sample of have done far. $distance = 0; $earthradius = 6371; for($i = 0; $i < $journey->data->count(); $i++) { $currentdata = $journey->data->get($i); $previousdata = $journey->data->get($i-1); if($previousdata == null) continue; $dlat = deg2rad($currentdata->latitude - $previousdata->latitude); $dlon = deg2rad($currentdata->longitude - $previousdata->longitude); $a = sin($dlat / 2) * sin($dlat / 2) + cos(deg2rad($currentdata->l

.net - C# parallel and multithreading on single core cpu -

i have application c# , .net 4.5 working on intel core i5 system windows 8.1, when publish application , install on windows 7 sp1 run on system intel pentium 4 single core , single thread .net 4.5.3 application not work completely. portion of code guess cause problem used parallel.foreach . my application using async await too. is true parallel.foreach , async await work on multi thread processor? how can use program on single core? if need replace code should use? the tpl, parallel.foreach utilizes, works threads rather cores, os schedule threads. single core processor run threads associated parallel.foreach code through single core without issue. async/await methods on other hand not create additional threads, rather run on current synchronization context , use time on thread when method active. again, single core cpu should handle async/await without issue. that being said, may degrading performance using parallel.foreach due additional overhead associated th

scala - How to handle response timeout? -

in akka-http routing can return future response implicitly converts toresponsemarshaller . is there way handle timeout of future? or timeout of connection in route level? or 1 way use await() function? right client can wait response forever. complete { val future = { response <- someiofunc() entity <- someotherfunc() } yield entity future.oncomplete({ case success(result) => httpresponse(entity = httpentity(mediatypes.`text/xml`, result)) case failure(result) => httpresponse(entity = utils.getfault("fault")) }) future } adding timeout asynchronous operation means creating new future completed either operation or timeout: import akka.pattern.after val future = ... val futurewithtimeout = future.firstcompletedof( future :: after(1.second, system.scheduler)(future.failed(new timeoutexception)) :: nil ) the second future hold successful result replaces error, depending on want mod

plsql - sql raise_salary procedure -

i'm trying make pl/sql program raise salary of managers table , if salary greater 3000 have set @ 3000 don't seem manage make that. have use o procedure , call anonymous block. in anonymous block, calling procedure every manager. in procedure, raising every manager's pay 500. time block exits, managers going getting quite substantial raise! step 1 decide if want per manager looping in block or in procedure. step 2 if want raise exception if manager earning > 3000, must check see if manager earning > 3000. check null, it. no, check in exception handler doesn't count. salary had null there. in example, i've elected looping in procedure. needs know job type gets raise , amount of raise. create or replace procedure raise_sal( target_job emp.job%type, amount number ) max_sal constant number := 3000; -- passed in sal_null exception; sal_too_big exception; pragma exception_init( sal_null, -20101 ); pragma exception_

java - Android TabHost strange error -

since tabhost not deprecated, , need simple solution switch between 2 controls (maybe 3) decided tabhost perfect needs. mysterious error.... this code have mytabhost = (tabhost) findviewbyid(android.r.id.tabhost); mytabhost.setup(); tabhost.tabspec tmpspec = null; tabcontentfactory tmpcontentfactory = null; tmpspec = mytabhost.newtabspec("main_param_time"); tmpspec.setindicator("sometext"); // error happens here here tmpspec.setcontent(r.id.charts_stickchart); // rest of code here. e.g. addtab etc. the error java.lang.runtimeexception: not create tab content because not find view id 2131427359 my xml file looks this: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <tabhost android:lay

java - Application does not work in an other system -

i wrote javafx application in netbeans using jdk8, uses derby. the built project runs well, fine @ first computer. if run "dist" library working properly. but when took mother's pc (same operation system - windows 7) 32 bit jre, , installed jdk program runs well, cannot communicate database. i can't create new records, can't read database wasn't. do need install apache derby mother's computer? wouldn't think so, since using local derby database. (the filesystem same, database folder can found @ dist folder, should work.) there no error message, not should. (for example not list records database @ main screen) what wrong?

variables - C what is this line of code doing? Is it casting? -

so i'm following online tutorial (on os development if matters) , saw line of c code void. here's simplified version: void function1(struct regs *r) { void (*handler)(struct regs *r); // happened here? // things void *handler } what happened in line? declared variable void *handler but did cast? doesnt seem cast. happened there? void (*handler)(struct regs *r); declares handler pointer function expects argument of type struct regs * , returns type void .

arrays - Why cant I use a loaded movieclip at the same time on two locations? -

i'm loading swf, place in array , use in various locations. everything works should, when add movieclip in 2 different places @ same time (in different classes), displayed on 1 location. i don't error, shows once. this how load swf , add array: img.contentloaderinfo.addeventlistener(event.complete, loaded); url = new urlrequest("my_file.swf"); img.load(url); function loaded(event:event):void{ var mc:movieclip = event.target.content movieclip; testarr.push(mc); } and how display movieclip: var displaymc:movieclip = movieclip(myclass.testarr[0]); addchild(displaymc); var otherymc:movieclip = movieclip(myclass.testarr[0]); addchild(otherymc); should duplicate movieclip in array able display on 2 locations or doing wrong? you can't display 1 movieclip in 2 different places. yes, should duplicate movieclip. try code: var duplicatedimg:loader = new loader(); duplicatedimg.contentloaderinfo.addeventlistener(event.complete, loaded);

asp.net - Passing javascript value to form fields fails with Internet Explorer (11) -

here piece of code (aspx/javascript) works fine in chrome , firefox, breaks in microsoft internet explorer. radio button scripting @ bottom takes values submitted when radio button selected via function @ top. the variable "valuetext" takes contents of "value" property of radio button , passes 2 form fields. why 'form1.anx_1.value' not return radio button value? {...} //called when radio button selected function returnval(qid) { $("#cmdsubmit").removeattr("disabled"); if (qid=='1') {var valuetext = form1.anx_1.value}; if (qid=='2') {var valuetext = form1.dep_1.value}; if (qid=='3') {var valuetext = form1.anx_2.value}; if (qid=='4') {var valuetext = form1.dep_2.value}; if (qid=='5') {var valuetext = form1.anx_3.value}; if (qid=='6') {var valuetext = form1.dep_3.value}; if

Running a python script from PHP with Apache -

i have set apache 2 server on raspberry pi index.php can access computer on network. in same folder ( /var/www ) have python script test.py . the script works fine when running manually. however, want able run script in browser using php. tried this: <?php $command = escapeshellcmd('test.py'); $output = shell_exec($command); echo $output; ?> however nothing happens. tried using full filepath /var/www/test.py , didn't work either. any suggestions on how can working? two things come mind: first, first line in file contain full path python interpreter? i.e: #!/usr/bin/python second, file have appropriate file permissions. can you open www-data user (same user apache process should running as)? sudo -u www-data /var/www/test.py

haskell - "takeWhile" within a list comprehension -

i have following: [bla z|n<-[0..], let z = foo n, z < 42] the thing is, want list comprehension end z < 42 fails, if takewhile. know refactor bunch of filters , maps, more elegant list comprehension. what elegant way combine list comprehensions , takewhile? since list comprehensions not allow this, have hacked bit using monad comprehensions , defining custom monad. outcome of following works: example :: [int] example = tolist [1000 + n | n <- fromlist [0..] , _ <- nonstopguard (n > 1) , let z = 10*n , _ <- stopguard (z < 42) ] -- output: [1002,1003,1004] the above works normal list comprehension, has 2 different kinds of guard. nonstopguard works regular guard, except requiring bizarre syntax. stopguard instead more: become false, stops further choices in previous generators (such <-[0..] ) considered. the small library wrote shown below: {-# language derivef

Azure DiagnosticMonitor API is now obsolete -

we in process of doing overhauls our workerrole on azure. our current implementation uses diagnosticsmonitor automatically put of trace , error information wad-logs table in our storage account , works well. however, implementing diagnostics portion of role in our rewrite, resharper diligently informing me diagnosticmonitor obsolete api. however, cannot find information shows meant replace api. some relevant information (all of these should latest versions via nuget): microsoft.windowsazure.diagnostics :: version 2.5.0.0 microsoft.windowsazure.configuration:: version 3.0.0.0 microsoft.windowsazure.serviceruntime:: version 2.5.0.0 microsoft.windowsazure.storage:: version 4.3.0.0 the code attempting replicate public static void configurediagnostics() { //warning here on diagnosticmonitor var config = diagnosticmonitor.getdefaultinitialconfiguration(); config.configurationchangepollinterval = timespan.f

python - Integrity error while trying to serialize nested object using django rest framework -

model file class address(models.model): address_id = models.autofield(primary_key=true, auto_created=true) address_data = models.charfield(max_length=250) class user(models.model): user_id = models.autofield(primary_key=true) name = models.charfield(max_length=50) address = models.foreignkey(address) serializer file class addressserializer(serializers.modelserializer): class meta: model = address fields = ('address_data') class userserializer(serializers.modelserializer): address = addressserializer() class meta: model = user fields = ('name', 'address') def create(self, validated_data): address_data = validated_data.pop('address') user = user.objects.create(**validated_data) address.objects.create(user=user, **address_data) return user i have above code snippet in model , serializer file. getting integrity error while serializing , savi

PHP & MySQL - Identify table in results from joined tables -

say have following query: $sql = "select * cars left join trucks cars.user_id=$user_id , trucks.user_id=$user_id"; since page cars , trucks have different layouts how know result belongs table ? same different table names. how retrieve table names ? thanks in advance all columns on left belong left table i.e. cars , right truck. so e.g. if have table cars(id..) , truck(id..) then output be id...(from cars) id..(from truck) if want specific columns use like: select `truck`.id,`cars`.id...

How does one declare an array in VBScript? -

i used in excel , works fine. dim varscreen (0 2) string varscreen(0) = "sample 1" varscreen(1) = "sample 2" varscreen(2) = "sample 3" i trying translate array vbscript keep getting error: line: 14 error: expected ')' i have tried various options, removed as string , dim varscreen array still error. what proper syntax? vbscript's (variables and) arrays can't typed, no "as whatever". vbscript's arrays zero-based, no "(x y)" "(z)" z last index (not size) of array. in code: >> dim varscreen(2) >> varscreen(0) = "sample 1" >> varscreen(1) = "sample 2" >> varscreen(2) = "sample 3" >> wscript.echo join(varscreen, "|") >> sample 1|sample 2|sample 3 >>

uistoryboard - Facebook like table cell for comments and Reply(iOS) -

i have app includes feature in user can add comments , reply comment on images/videos (like facebook). user can delete/edit comment/reply posted. want know if there classes available show kind of ui. i have designed above using tableview , added custom cell dynamic cell size(for large size comments). problem when there no reply on comment hide uiview (which contains reply data) , show if there reply on comment. therefore dynamic cell shows lot of whitespace if there no reply on comment. wish avoid it. how can achieve this? thanks.

phpstorm - PHPUnit stderr ignored -

i want run functional/integration tests (not unit tests) phpunit. works well, except in cases gives following error: cannot modify header information - headers sent (output started @ phar://c:/easyphp/binaries/php/php_runningversion/phpunit.phar/phpunit/util/printer.php:137) this happens when trying modify header information, e.g. seassion_start , set_cookie , redirect , etc. there fix this, --stderr run time option or stderr="true" xml configuration, redirects output stderr not starting output. worked great on netbeans. yet, none of these seem work phpstorm. idea why? here's command line (created phpstorm): c:\easyphp\binaries\php\php_runningversion\php.exe c:\users\xxx\appdata\local\temp\ide-phpunit.php --stderr --bootstrap c:\easyphp\data\localweb\tests\bootstrap.php --configuration c:\easyphp\data\localweb\tests\configuration.xml c:\easyphp\data\localweb\tests the config file: <phpunit colors="false" stderr="

html - Box-Shadow not carrying out Transition -

i know may dupe, i'm willing take hit feel confident have researched multiple solutions. i have tried many methods box-shadow transition work, including: switching between hex, rgb, , rgba colors in box-shadow declaration. using selectors more specificity. changing the transition property include ease-in-out @ end of declaration. i cleansed css file of transition properties possibly effect element. all while, triple checking spelling mistakes. the inspector says styles not being overridden. here code: .site-header .genesis-nav-menu .menu-item { -webkit-box-shadow: 3px 3px 14px rgb(0,0,0) inset; -moz-box-shadow: 3px 3px 14px rgb(0,0,0) inset; -o-box-shadow: 3px 3px 14px rgb(0,0,0) inset; box-shadow: 3px 3px 14px rgb(0,0,0) inset; -webkit-transition: box-shadow 3s; -moz-transition: box-shadow 3s; -o-transition: box-shadow 3s; transition: box-shadow 3s; } .site-header .genesis-nav-menu .menu-item a:hover{ -webkit-box-shadow: 3px 3px 14px rgb(0,0,

user interface - Changing GTK label in C using signal_connect -

hello making gui in gtk have menu items, , trying change main label after clicking mouse on specific menu element. widgets[i][0] = gtk_menu_item_new_with_label(arrayofstrings[i]); //arrayofstrings : char** arrayofstrings gtk_menu_shell_append(gtk_menu_shell(indicator_menu), widgets[i][0]); i trying this: void set_main_label(gtkwidget *widget) { app_indicator_set_label(indicator, arrayofstring[2],arrayofstring[2]); } and after call like: g_signal_connect(widgets[i][0], "activate",g_callback(set_main_label), widgets[i][0]); but problem void set_main_label(void) must have void argument. , need pass there string (char*) stored in arrayofstrings. suggest? can change label 1 specific string set in set_main_label function, cannot pass argument function, suggest? . this user_data parameter for. set_main_label() not have void argument list - check documentation : void user_function (gtkmenuitem *widget, gpointer user_data) you

html - PHP Website on Mobile Device -

i have google app engine php website , works fine. when loaded on mobile device loads normal web page. whats best way 'convert' web page better when loaded on mobile device? via css? you looking responsive web design, or pages adapt screen size. common responsive css frameworks bootstrap , foundation .

In Javascript ,how to represent 1.00 as a number in a JSON object? -

all want create json string : '{ "a" : 1.00 }' i have tried var n = 1.00; var x = { : n }; console.log(json.stringify(x)); // gives {"a":1} var n = 1.00; var x = { : n.tofixed(2) }; console.log(json.stringify(x)); // gives {"a":"1.00"} var x = { x : 1.00 }; x = json.stringify(x , function(key,val ){ if( typeof val === "number") return val.tofixed(2); return val; }); console.log(x); // gives {"x":"1.00"} is possible represent '{ "a" : 1.00 }' json string in javascript ? if yes, how can ? a number in json doesn't have specific precision. number represented shortest notation needed reproduce it. the value 1.00 same value 1 , how represented in json. if want represent number in 1.00 format, can't store number, need use string. the string '{"x":1.00}' valid json, has same meaning '{"x":1}' .

applescript - I need to convert an email address to a recipient -

need convert email address contacts recipient in mail. tell application "contacts" set sendto every person's email 1 end tell tell application "mail" set mesg make new outgoing message set recipient of mesg sendto -- need convert here. set subject of mesg "a title" set content of mesg "a body" send mesg end tell you've got several problems in code... when "every person's email 1" list of references, not list of email addresses. actual email address reference "value". sendto list, have loop on list , add each address 1 @ time in mail. there's different kinds of recipients. need use "to recipient". try this: tell application "contacts" set sendtolist value of every person's email 1 end tell set emailsender "me@me.com" set thesubject "the subject of mail" set thecontent "message body" tell application "

Create 3 mutually exclusive samples in r -

i have data set need split 3 mutually exclusive random samples of different sizes. used: testdata<-sample(47959,14388,replace=false,prob=null) to try , create sample (the data set size 47959) don't know how make sample manipulatable data set in r. some data: set.seed(42) x <- sample(20, size=100, replace=true) head(x) ## [1] 19 19 6 17 13 11 random sizes create index of 1:3, , use subset data: i <- sample(1:3, size=length(x), replace=true) head(i) ## [1] 2 1 1 2 3 3 now break 3 groups (many ways this): x.grouped <- split(x, i) str(x.grouped) ## list of 3 ## $ 1: int [1:31] 19 6 15 20 9 5 8 9 18 20 ... ## $ 2: int [1:30] 19 17 14 10 6 10 19 3 10 19 ... ## $ 3: int [1:39] 13 11 15 3 15 19 12 2 8 19 ... the relative sizes of 3 groups vary randomly. controlled sizes indices represents size desire in each group. indices <- c(20, 50, 30) indices.cs <- cumsum(indices) x.unsorted <- sample(x) xs.grouped.sized <- mapply(funct

Is there any way to get the 206px version of a photo via the Facebook Graph API? -

i'm trying version of photo fb uses background image album layouts 1 side 206px , other 1 @ least same, example https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpa1/v/t1.0-9/p206x206/10401476_409218399235620_1454525834273554679_n.jpg?oh=eda59fce63113796b35c46cc4bec162a&oe=55760efd& gda =1433681435_6b4729404e05493108c271a50c753d7f i've scoured both graph , so, having absolutely no luck here. i'm aware can 3 versions of photo using type=album/thumbnail/normal ie https://graph.facebook.com/409218399235620/picture?type=album (you'd think 1 work, never updated redirect new size?). i've tried kinds of variants of knowing graph documentation pretty crap, no avail. i've used explorer example pull ?fields=images, it's never 1 of listed images there. i've tried using widths, replacing parts of url etc. etc. running checks valid access_token. i've pretty resigned myself resizing myself, given time i've spent on this, thought i'd @ le

arrays - Binary Search gives Index Out of Bound Exception in Java -

i trying implement binary search using java programming language. it's obvious array should sorted in order make use of binary search because uses divide , conquer concept. code works fine both cases when when element within array , when it's not. but, when enter number greater greatest number inside array, program crash , give index out of bound exception. public class binary { public static void search(int arr[]) { scanner in = new scanner(system.in); int upper = arr.length; int lower = 0; int middle = 0; int flag = 0; int key; /* * flag = 0 ---> not found yet. * flag = 1 ---> element found. * flag = 2 ---> no such element. */ system.out.println("enter number want find... "); key = in.nextint(); while (flag == 0) { middle = (int) (lower + upper) / 2; if (key == arr[middle]) { flag = 1; } if (key < arr[middle]) { upper = middle

javascript - How set the current position center on the map? -

i tried different approaches found on site , in web don't work me( this code: <h:panelgroup id="gmwrapper" style="background-color: red"> <p:gmap widgetvar="mainmap" center="49.835, 24.0083" zoom="15" id="maingooglemap" type="hybrid" style="width: 600px; height: 400px" model="#{userplaces.model}" styleclass="gmappstyle" onpointclick="handlepointclick(event)" /> <p:commandbutton onclick="somefunc()"></p:commandbutton> <script type="text/javascript"> function somefunc() { if (navigator.geolocation) { alert("start") navigator.geolocation .getcurrentposition(success); alert("successful!") var elem = document .getelementbyid("maingooglemap"); alert("element find")

algorithmic trading - What is the difference between init() and OnInit()? -

i learning mql4. on reference website, creating custom indicator done follows: #property indicator_chart_window int init(){ return(0); } int deinit(){ objectsdeleteall(); return(0); } int start(){ return(0); } but when create new indicator inside metaeditor, syntax, this: int oninit() { //--- indicator buffers mapping //--- return(init_succeeded); } //+------------------------------------------------------------------+ //| custom indicator iteration function | //+------------------------------------------------------------------+ int oncalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { //---

java - Share variables from different function -

my first post here on stackoverflow! started learning java. i'm trying build program prints random letter, should write words begin letter, , has class verify. the problem when generate randomnum in order randomletter array, can't share randomnum variable class needs verified. private void jbuttonplayactionperformed(java.awt.event.actionevent evt) { int randomnum; randomnum = (int)(math.random()*palavras.length); system.out.println(""+randomnum); jlabelrandom.settext(introduce words begins : " + palavras[randomnum]); } private void jbuttonverificaractionperformed(java.awt.event.actionevent evt) { int certas = 0; string[] words = {jtextfield1.gettext(), jtextfield2.gettext(), jtextfield3.gettext(), jtextfield4.gettext(), jtextfield4.gettext()}; (string w

android - fill fragment edttexts with data from activity -

thx in advance time. driving me crazy, want fill edit texts located layout of fragment called button in main activity , want have edit text filled data of asynctask on main activity.i've tried code when open fragment can't close fragment , empty. please please give solution or directions find solution. this code of activity: public class resultadoscopia extends activity implements datos.onfragmentinteractionlistener { imageview foto; button sig; button ant; button adopta; string hld; string postal; string animal; string email; string telf; string edad; string nomanimal; string funciones; string cchld; string neces; string ccanimal; string ccpostal; string nomcont; // progress dialog private progressdialog pdialog; // json parser class jsonparser jsonparser = new jsonparser(); // single product url public string url_product_detials = "http://adoptia.esy.es/androptar.php"; // json node names public static final string tag_hld = "hld"; public stat

insert into mysql file and it's directory using Python -

i combine file_name , directory insert mysql table using python. the code cursor.execute("insert library (book_name, author, written, book_link, images) values (%s, %s, %s, 'library/'%s, 'images/'%s )" , (book_name, author, written, book_link, images)) gives me unwanted single quote ' symbols, this: images/'me ibrary/'my life how avoid wrong syntax?

python - List of all possible ways from root to leaf (without binary tree) -

Image
i'm trying list possible moves root of leafs in tree. have setup can list ['a', ['b', ['c'], ['k']], ['d', ['e', ['f'], ['g']], ['h', ['i'], ['j']]]] here image of list represents: i'm wondering how can transform above list into: "abk", "abc", "adef", "adeg", "adhi", "adhj" i've tried recursion through list can't quite figure out. btw reason i'm trying use list because thats real way think of , doesn't seem of strech list different pathways? here's suggestion! def walktree(lst): # leaf? here's our base case. if len(lst) == 1: return lst # if not, it's node; make sure list formatted correctly. assert(len(lst) == 3) first = lst[0] # here's recursion happens. left = walktree(lst[1]) right = walktree(lst[2]) # finally, combination s

OpenSearchServer stops running: Error (The unique key is missing: content) -

i using opensearchserver v1.5.11 - build bd28c79a9d total of 5000 home pages. after running crawl process (run forever) following error (4608 pages processed). error (the unique key missing: content) the of pages in url browser section unfetched/not parsed , not indexed. what's wrong?

mongodb - Meteor Alternative to Aggregate Stats? -

i'm looking $avg (aggregation) on collection, meteor doesn't support it. solution static , not reactive, or use foreach loop. not performance. think way hold on separated collection "stats". how should work, how calculated , stored , used? have experience , great solutions? interesting question! there packages enable use aggregation pipeline such https://github.com/meteorhacks/meteor-aggregate/ said aren't reactive. perhaps setup cursor.observechanges on relevant collections, or tracker.autorun, result in lot of code running takes longer finish next change coming in, backlog of events. i think better way have separate stats collection runs regularly. need realtime updates, or once per minute? there event queue tools https://github.com/artwells/meteor-queue that. good luck!

json - How to sort a MongoDB document by its subdocument fields -

i'm trying order following document don't way it. need sort following mongodb document field attributes.k order (and order v). { "_id" : objectid("55174192825a674422d29422"), "attributes" : [ { "k" : "order", "v" : "2" }, { "k" : "image", "v" : "550f3232f2bb54ac057883ab" } ] }, { "_id" : objectid("551741a2825a674422d29423"), "attributes" : [ { "k" : "order", "v" : "1" }, { "k" : "

Package Initialization in Java -

i'm building java package , need initialization code called in order package work properly. package being wrapped .jar , , have no control on user calling when import package application. rather having them need call initialization method before can start using package, there way method called under hood? i'd mention static { } approach won't work, need code called 1 time regardless of objects in package being utilized. no, there no such method on package level. to achieve can add static { .... } block each of classes , have static block call common initializer. for example: package a.b; class x { static { a.b.static.init(); } } class y { static { a.b.static.init(); } } class static { static void init() { ... init code goes here ... } }

Mongodb & Robomongo: Can't connect (authentication) -

Image
i have following user: { "_id" : "admin.root", "user" : "root", "db" : "admin", "roles" : [ { "role" : "root", "db" : "admin" } ] } and database: { "_id" : "mydb.mydbdbowner", "user" : "mydbdbowner", "db" : "mydb", "roles" : [ { "role" : "dbowner", "db" : "mydb" } ] } i can't connect via robomongo on localhost. same goes for... database: mydb user name: root database: mydb user name: mydbdbowner i experiencing same issue on mac. removed robomongo client , download latest version website. works :)

pattern matching - re.match with '-' not working in python -

i have following code if(keys==14): print (values) result = re.match("(^\-)", str(values)) print "rr is", result, (values) but match not working sample line. here output got ­ ­-bob rr none ­bob can't reproduce: >>> x='-bob' >>> re.match('(^\-)', x) <_sre.sre_match object; span=(0, 1), match='-'> your values may different, presumably having non-printable characters in addition @ start. try printing repr of make sure that's not case...! edit: , indeed repr reveals values start soft hyphen (encoded in utf-8) may display dash isn't dash. re matching encoded byte strings can inconvenient, let's first decode text: >>> x = '\xc2\xadbob' # or else `values` obtained such >>> y = x.decode('utf8') >>> re.match(ur'([\xad-])', y) <_sre.sre_match object @ 0x1004c0af8> (switched python 2 here why repr of match obj

c++ - Reference class member (was) causing undefined behavior -

i'm attempting make class holds class reference (private member). class example{ private: std::vector<char> chars; }; class example2{ example2(example to_be_initialized) :ref(to_be_initialized) { } private: example& ref; }; hopefully lack of detail won't bug (i know guys see full code, reduced because if isn't problem it's else have figure out. post more/the rest if needed), had code similar this, , weird unicode characters when doing involving ref. once changed ref non-reference, weird undefined behavior went away. i'd know if above legal future reference. know in scenario i'm not saving whole lot of memory referencing class (since it's copying pointers, right?), feel necessary in future. thanks in advance. there major issue code: constructor takes parameter value, means reference refers temporary object. after constructor call, left dangling reference. you need initialize reference valid object. can making cons

JavaFX vs Java Swing -

what javafx? started java gui , going use swing our course. now, looking tutorials assist me on youtube , downloaded gui videos find out javafx ones. so, this? you can read here: http://www.oracle.com/technetwork/java/javase/overview/javafx-samples-2158687.html start downloading ensemble, started. pick javafx next java gui app because find pretty cool. swing around because that's everyone's used , popular while until more people check out javafx. , yes javafx can replace swing.

Possible to write to BIOS from linux kernel mode? -

is possible flash/write bios kernel mode in linux ? i've been doing research on , can't find definitive answer this. i'm not great kernel level stuff , hardware. from i've been able find, know kernel facilities can interrogate bios (see dmidecode ) given bios supports interfaces. i know difference between real , protected mode. switching real mode linux seems impossible correctly (?). know x86 has emulation 8088 programs unsure whether emulation allow flashing bios. wouldn't possible write addresses in kernel mode "flash" bios? update working answer , comments below seems answer yes depending on hardware platform. only, , necessary requirement bios flash chip addressable in io address space. need software support fir flashing chips, whether kernel or user space. example found user space utility flashrom can on seems narrow set of hardware platforms. yes, can if bios flash chip connected io address bus , have necessary drive

forms - PHP How to get an input values type through $_POST -

hi sending form through post php file have made. have been able use $_post["name"] vales of input fields of type text/password,/etc 'type'. in variable $car = $_post["car"]; store value, $carinputtype store inputs type. if in form person chose mazda in checkbox, $carinputtype hold 'checkbox' type. i hope explained think useful many people learn. have been looking around have not found answer this. have tried: $radio = $_post["fname[type]"]; $radio = $_post["fname[type=]"]; a bit of form follows: <form id="ajax-form" onsubmit="return false;"> <div><label for="uname">username <em>*</em></label> <input id="uname" type="text" name="uname" value="" /><p class='note' id = "usernameid"></p> </div> </form> any appreciated. thank reviewing post. you can&

html - Images not loading on local view - mixture -

Image
i want load images stored in respective subdirectories of html file eg in images/ folder index.html file located. when tried show images tag <img src="./images/study.jpg" width="100%" alt="study time"> this works if crate project html not work on local view. am doing silly mistake?

html - Simple Form check box left alignment -

i have rails 4 app simple form. there check box element in app box left of label. <div class="row"> <div class="col-md-3 col-md-offset-1"> <%= f.label :'how share project results?', :class => 'question-project' %> </div> <div class="col-md-7"> <div class= "response-project"> <%= f.input :report, as: :boolean, inline_label: 'a report on project outcomes', label: false, :item_wrapper_class => 'inline' %> <%= f.input :other_outcome, :as => :boolean, :label => false, :inline_label => true %> </div> </div> </div> the css response-project is: .response-project { font-weight: normal; font-family: 'roboto', sans-serif; color: light-grey; font-size: 16px; line-height: 2; } the check box aligned further left of remaining form elements. seems come simple form. know how turn alignm