Posts

Showing posts from June, 2014

java - Making web crawler download multiple web pages locally -

i web crawler download browsed url's locally. @ minute download every site comes overwrite local file in each website visited. crawler start @ www.bbc.co.uk, downloads file , when hits overwrites file next url. how can make download them in single files have collection @ end? have code below dont know go here. advice great. url inside brackets (url) string used manipulate browsed webpages. url url = new url(url); bufferedwriter writer; try (bufferedreader reader = new bufferedreader (new inputstreamreader(url.openstream()))) { writer = new bufferedwriter (new filewriter("c:/temp/data.html", true)); string line; while ((line = reader.readline()) != null) { //system.out.println(line); writer.write(line); writer.newl...

android - Invalid Scope When Trying To Create Use GoogleAccountCredential With ARC-Welder on Chrome -

i have android app i'm trying run under chrome arc (via arc-welder). i've created oauth2 ids , changed apk substitute chrome client-id if it's running under arc (build=="chromium"). however, still "invalid_scope" exceptions googleauthutil.gettoken() . the actual "scope" value is: audience:oauth2:client_id:numbers-numbersandletters.apps.googleusercontent.com the actual exception, hot logcat is: com.google.android.gms.auth.googleauthexception: invalid_scope @ com.google.android.gms.auth.googleauthutil.gettoken(unknown source) @ com.google.android.gms.auth.googleauthutil.gettoken(unknown source) @ com.google.api.client.googleapis.extensions.android.gms.auth.googleaccountcredential.gettoken(googleaccountcredential.java:255) ... the code making request is: final string clientid = ischromearc() ? chrome_client_id : web_client_id; googlecredential = googleaccountcredential.usingaudience(this, "server:client_id:" +...

unix - What is a grep command performs? -

im trying understand unix command im not quite expert on this, explain more in detail? grep '^.\{167\}02' what perform? from man page ( man grep ) grep searches named input files ( or standard input if no files named , or if single hyphen-minus (-) given file name) lines containing match given pattern. default, grep prints matching lines. check part in bold: if don't specify files want search in, wait , listen keyboard input , regex match each new line type. if want test it, suggest using easier regex, maybe less characters one: ^.\{3\}02 , see happens: $ grep '^.\{3\}02' 02 002 0002 00002 <-- matches , later printed , highlighted 00002 you don't use grep , type lines see if matches, give files argument, or input using pipe: ls -la | grep '^.\{167\}02'

php - Can I have more actions in a form? -

as said in title need more 1 action in form... form log in script , it's this: <form method="post" action="action.php" name="loginform" id="loginform"> <br><br> username:<br> <input type="text" name="username" id="username" /><br><br> password:<br><input type="password" name="password" id="password" /><br /><br> <input type="submit" name="login" id="login" value="login" class="page"/> <br> <br> <a href="register.php" class="page">sign up</a> </form> the action.php page this: <?php include('index.php'); include('insert.php'); include('contact.php'); include('about.php'); ?> it seems work way want after hit...

get list of unused numbers from an unsorted array in java -

i need smallest unused number unsorted array. not sort array because test program, in actual program, taking values array of objects. so while trying smallest unused number, managed list of unused numbers. perfect first random numbers wrote in program, second time, output wrong. this code tried class smallestunusednumbertest { public static void main(string args[]) { int[] testarray = {1, 5, 7, 11, 4, 8}; int largest = 1; int i; for(i = 0; < testarray.length; i++) { if(testarray[i] > largest) { largest = testarray[i]; } } for(i = 1; < largest; i++) { for(int j = 0; j < testarray.length; j++) { if(i == testarray[j]) { i++; } } system.out.println(i); } } } and output is 2 3 5 6 9 10 i 5, there in array. have used for loop largest number array. then, not able figure out c...

casting - New warning in Xcode 6.3 & Swift 1.2: Cast from '[SKNode]' to unrelated type 'String' always fails -

after updating xcode 6.3 / swift 1.2 have run error can't resolve: "cast '[sknode]' unrelated type 'string' fails". below gamescene code begins parsing p-list. import spritekit class gamescene: skscene, skphysicscontactdelegate, nsxmlparserdelegate { var currenttmxfile:string? override func didmovetoview(view: skview) { /* parse p-list */ let path = nsbundle.mainbundle().pathforresource("gamedata", oftype: "plist") let dict = nsdictionary(contentsoffile: path!)! let playerdict:anyobject = dict.objectforkey("playersettings")! let gamedict:anyobject = dict.objectforkey("gamesettings")! let levelarray:anyobject = dict.objectforkey("levelsettings")! if let levelnsarray:nsarray = levelarray as? nsarray { var leveldict:anyobject = levelnsarray[level] numberoflevels = levelnsarray.count if let tmxfi...

unit testing - Specflow BeforeScenario been called four times -

i have solution contains set of tests can run using nuints. trying integrate specflow it: [testfixture] [binding] public class testbase { protected iwindsorcontainer container {get; set; } protected imongocollectionmanager collectionmanager { get; set; } protected idatabasemanager databasemanager { get; set; } [testfixturesetup] [beforescenario,clscompliant(false)] public void setup() { container = testfixture.container; collectionmanager = container.resolve<imongocollectionmanager>(); databasemanager = container.resolve<idatabasemanager>(); } [testfixtureteardown] public void teardown() { container.release(collectionmanager); container.release(databasemanager); } } everytime run feature file has 1 scenario executes before tests 4 times, before goes given of scenario when run using simple nuint works correctly , gets called once. can 1 me figure out why please? thanks, bijo ...

caching - Calculating Effective CPI when using write-through/write-back architecture -

so i'm trying understand homework problem given instructor , i'm lost - understand concept of write-through/write-back, etc. can't figure out actual calculations needed effective cpi, give me hand? (the problem follows: the following table provides statistics of cache particular program. known base cpi (without cache misses) 1. known memory bus bandwidth (the bandwidth transfer data between cache , memory) 4 bytes per cycle, , takes 1 cycle send address before data transfer. memory spends 10 cycles store data bus or fetch data bus. clock rate used memory , bus quarter of cpu clock rate. data reads per 1000 instructions: 100 data writes per 1000 instructions: 150 instruction cache miss rate: 0.4% data cache miss rate: 3% block size in bytes: 32 the effective cpi base cpu plus cpi contribution cache misses. the cache miss cpi sum of of instruction cache cpi , data cache cpi. the cache miss cost cost of reading or ...

c# - NHibernate Linq-to-Sql - How to do a bitwise complement (~) -

i trying use simple bitwise operations in linq sql query using nhibernate linq provider: query.where(x => ((x.allow & ~x.deny) & permissions) == permissions).toarray() this throws nhibernate.hql.ast.antlr.querysyntaxexception : recognition error occurred. because of & ~x.deny when remove & ~x.deny part, query runs without throwing exception. what proper way execute bitwise complement (~) in linq sql query?

c++ - Deduce weak_ptr argument from shared_ptr -

the following gives me compiler error: could not deduce template argument 'const std::weak_ptr<_ty> &' 'std::shared_ptr' #include <memory> class foo { public: template<typename r> void bar(std::weak_ptr<r> const & p) { p; } }; int main(void) { auto foo = foo(); auto integer = std::make_shared<int>(); foo.bar(integer); } i tried, template<typename r> void bar(std::weak_ptr<r::element_type> const & p) { } , seems syntatically incorrect. following works wondered if it's possible conversion in p, without creating temporary? template<typename r> void bar(r const & p) { auto w = std::weak_ptr<r::element_type>(p); } to clear i'd explicitly state function should take shared or weak_ptr, don't r const & p solution. for completeness works of course: template<typename r> void bar(std::shared_ptr<r> const & ...

java - Gradle project - can build but not run it -

Image
my android project consist of 3 build.gradle files: projects build.gradle : // top-level build file can add configuration options common sub-projects/modules. buildscript { repositories { // mavenlocal() jcenter() } dependencies { // classpath 'com.android.tools.build:gradle:1.1.0' classpath 'com.android.tools.build:gradle:1.1.3' } } allprojects { repositories { jcenter() } } myapp build.gradle apply plugin: 'com.android.library' android { dexoptions { predexlibraries = false } compilesdkversion 17 buildtoolsversion "21.1.1" defaultconfig { minsdkversion 8 targetsdkversion 17 } buildtypes { release { minifyenabled false proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:supp...

java - Smoothing signal from microphone - Hearthbeat -

i'm working on project using oximeter.i want smooth out can use calculating hearthbeat. i'm gathering raw data microphone , put them in new array, lets say, sdata[] . signal crazy , jumps on plot expected, tried smoothing using moving average. main code looks this. writeaudiodatatofile(); (int = 0; < sdata.length; a++) { tempavg += math.abs(sdata[a]); if (a % numberofsamplesaveraged == 0) { //average x samples if (myindex > sample_size - 1) { myindex = 0; } tempavg = tempavg / numberofsamplesaveraged; if (tempavg > 500) { newdataarray[myindex] = 500; }else{ newdataarray[myindex] = tempavg; } //this suppose clear high peaks. log.d("isrecording - average " + numberofsamplesaveraged + " numbers.", "newdataarray[" + myindex + "] = " + newdataarray[myindex]); tempavg = 0; myindex++; ...

PHP: PDO(MySQL) SSL Connection -

i trying establish ssl connection mysql server using following code (on debian gnu/linux 7 (wheezy) php 5.4.4): $db = new pdo('mysql:host=mysql.myorganization.net;dbname=mydb', 'username', 'password', array( pdo::mysql_attr_ssl_ca => 'mysqlcertificates/cachain.pem' )); var_dump($db->query("show status 'ssl_cipher';")->fetchall()); but getting error: sqlstate[hy000] [2026] ssl connection error: asn: bad other signature confirmation i can establish ssl connection using mysql command: mysql -u username -p -h mysql.myorganizataion.net --ssl-ca mysqlcertificates/cachain.pem i built php 5.4.4 source , (without running make install) ran sapi/cli/php ~/projects/test.php and following output array(1) { [0]=> array(4) { ["variable_name"]=> string(10) "ssl_cipher" [0]=> string(10) "ssl_cipher" ["value"]=> string(18) "dh...

sql server - Can someone please help me understand the case function? -

i working in sql data base. have make 2 columns. first column length of employee name(i have that) second column title of courtesy , last name of employee. my problem how add case function have ms displayed miss, mr. mister , dr doctor. not understand. appreciated. here code have far: select 'your full name ' + cast(len(firstname) + len(lastname) varchar(12)) + ' character(s).' [length of employee name] , titleofcourtesy + lastname title dbo.employees you can this: select ... previous things here ... case titleofcourtesy when 'mr' 'mister ' when 'ms' 'miss ' when 'dr' 'doctor ' else '' end + lastname title

sails.js Sessions - rememberme functionality -

i have been trying implement rememberme functionality using sails . want session persist until browser closed. however, if rememberme checkbox ticked when user logins in want session persist 30 days. used remember me passport strategy here: https://github.com/jaredhanson/passport-remember-me ends sitting on top of sails session , 1 called first ends superseding other. you can set cookie age before calling login function. i did in login controller -> passport.callback. passport.callback(req, res, function (err, user, challenges, statuses) { ... if (req.param('remember', false) == true) { req.session.cookie.maxage = 1000 * 60 * 60 * 24 * 30; } req.login(user, function (err) { ... } } this doesn't feel right and, if sending other cookies when logging in, affect lifetime well. but works , went since finding documentation sails-related stuff digging oil. also, noticed passport not destroy...

c# - Perspective transform with WPF -

wpf allows specify linear affine transform on graphical objects. can translation, rotation, scaling, skewing, or combination of that. can specify 2x3 matrix. what want perspective transform in 2d space, requires 3x3 matrix, , known photoshop or gimp, can drag 4 corners of image independently. i tried use 3d features of wpf, set viewport3d , orthographiccamera , placed (2d) objects onto xy-plane. but i'm wondering if there no easier way accomplish perspective transform in wpf? i'm asking because i'd perspective transform on text: in 2d can use textblock , in 3d gets more compliacted, i'd have create brush out of geometry out of formattedtext . as can read here there 3rd party libraries implement silverlight's planeprojection wpf. otherwise forced code yourself. (perhaps microsoft add planeprojection in future version of .net)

java - Synchronized writing and reading in file with not join object variable of file -

i'm trying implement threads concurrency in java. consists of trying write in file last time. there 2 threads: a - creating file , checking if right line in file , b - searching file , trying rewrite file “good” line. “winner” thread must have string in file. thread checks if file has line, file has 1 line. threads have file path. public class implements runnable { private file file; private thread t; public a(string patch,string filename) { t = new thread(this); createfile(patch, filename); //t.setdaemon(true); t.start(); } @override public void run() { bufferedreader reader; while (!thread.currentthread().isinterrupted()) { try { reader = new bufferedreader(new inputstreamreader(new fileinputstream(file))); if (reader.readline().charat(0) == 'b') { system.out.println("a try took file: " + file.getname()); write(); } else { system.out.prin...

java - DBSCAN libraries to extract density-reachable points -

Image
i'm working dbscan libraries extract clusters set of data. far i've tested dbscan using apache common math , weka libraries. (my question not libraries available implementations of dbscan) so far i've understood in dbscan there 3 types of points (as according wikipedia): core points, (density-)reachable points , outliers. issue need extract clusters , it's frontier points or density-reachable points. do know dbscan library allows me extract density-reachable points per cluster? in elki implementation, can use options -algorithm clustering.gdbscan.generalizeddbscan -gdbscan.core-model to cluster "model" containing core points of cluster only. cluster members still border points - density reachable, not core. however, needs more memory, not enabled default. in image, inner convex hull core points only. green cluster, there 2 core points. noise points, there no nested cluster, obviously. note dbscan clusters can non-convex. why green cl...

swift - How to keep sound off while transitioning between SKScenes -

i created game in sprite kit , give user ability mute sound pressing button before can tap , start game. however, when game on , gameoverscene appears, music still stays muted. when new gamescene called music start playing again. know how solve issue. code have music. var backgroundmusicplayer: avaudioplayer! func playbackgroundmusic(filename: string) { let url = nsbundle.mainbundle().urlforresource( filename, withextension: nil) if (url == nil) { println("could not find file: \(filename)") return } var error: nserror? = nil backgroundmusicplayer = avaudioplayer(contentsofurl: url, error: &error) if backgroundmusicplayer == nil { println("could not create audio player: \(error!)") return } backgroundmusicplayer.numberofloops = -1 backgroundmusicplayer.preparetoplay() backgroundmusicplayer.play() } override func didmovetoview(view: skview) { mutesound.name = "mutesound" mutesound.position.x = view.center.x ...

Change CSS of Bootstrap-Columns created by AngularJS -

i try display employees angularjs , bootstrap, unable override/change css of created bootstrap-columns (adding shadow around every employee). i think has css-specifics can not figure out what. index.html <body data-ng-cloak=""> <div class="webpage"> <!-- here banner navigation --> <div ng-view class="content"></div> </div> </body> angularjs partial: <link href="styles/booking.css" rel="stylesheet"/> <div> <div class="row search"> <div class="col-md-2"> <!--sidebar content--> search name: <input ng-model="query"> </div> </div> <div class="row"> <div class="col-md-4 employee" ng-repeat="employee in employees | filter:{name:query}" ng-click="onclickemployee($index)"> ...

Why are mutables allowed in F#? When are they essential? -

coming c#, trying head around language. from understand 1 of main benefits of f# ditch concept of state, should (in many cases) make things more robust. if case (and correct me if it's not), why allow break principle mutables? me feels don't belong in language. understand don't have use them, gives tools go off track , think in oop manner. can provide example of mutable value essential? current compilers declarative (stateless) code not smart. results in lots of memory allocations , copy operations, rather expensive. mutating property of object allows re-use object in new state, faster. imagine make game 10000 units moving around @ 60 ticks second. can in f#, including collisions mutable quad- or octree, on single cpu core. now imagine units , quadtree immutable. compiler have no better idea allocate , construct 600000 units per second , create 60 new trees per second . , excludes changes in other management structures. in real-world use case complex...

Powershell Invoke-RestMethod return -

i running powershell 2.0. new powershell , using run php script on daily basis don't have continually call url in browser myself. seem have working pretty can't seem json return invoke-restmethod. here code using: $limit = 200; ($i=1; $i -le $limit; $i++) { write-host $i started of $limit $site = "http://example.com/updates" $info = measure-command{ $data = @{call_type = 'powershell'} $resp = (invoke-restmethod -method post -uri $site -body $data -timeoutsec 500).results } write-host resp - on $resp.date, $resp.num downloaded write-host $i took $info.totalseconds s write-host --------------------------------------- } the php script passing json string like: {date: '2014-09-30', num: 127569} any great. you don't need .results . invoke-restmethod converts json [psobject] automatically. if want raw json use invoke-webrequest , since reference $res...

Netsuite Inventory Item Custom Forms keep changing -

we have created custom form inventory items in netsuite. when want go , edit inventory item, automatically goes our default custom form. manually have change form want use each time edit these types of items. is there way have when these specific items opened edit go custom form created on? no need create workflow/script. need set custom form "store form record". customize form , checked option says "store form record". every time create item record select form , fill in necessary information , save it. after saving form automatically saved record , used every time edit , view record. definition of "store form record" check box store custom form each record entered form. ensures records viewed , edited form regardless of viewing or editing record.

clojure - Emacs/CIDER Error -

i'm trying clojure development using emacs , cider , , following this tutorial . i've gotten point need m-x cider-jack-in , supposed start *cider-repl* buffer, instead gives me error error in process filter: symbol's function definition void: clojure-mode-variables i'm running emacs 24.3.1 , cider-20150412.827 (out of melpa ), leiningen 2.3.4 , , error whether specify [cider/cider-repl "0.7.0"] or [cider/cider-repl "0.8.2"] . i'm able run lein run on project i'm trying edit. any ideas i'm doing wrong? you're using outdated version of clojure-mode . update recent version (e.g. latest) , should fine. btw, should use [cider/cider-nrepl "0.9.0-snapshot"] cider melpa.

performance - C# Comparing values in 2 DataTables -

i'm processing 2 datatables: ssfe: contains values want find ffe: larger, smaller or equally large ssfe, not contain every value of ssfe the values need match between these tables integers, both tables sorted small large. idea start searching on first item in ffe, start looping through ssfe, , when find match -> remember current index -> save match -> select next item ffe , continue previous index. also ffe can contain integers, can contain strings, why cast values string , compare these. i made code, takes, time. take minute compare ssfe(1.000 items) ffe(127.000) items. int whereami = 0; bool firstiteration = true; (int = 0; < ffedata.rows.count - 1; i++) { (int j = 0; j < ssfedata.rows.count - 1; j++) { if (firstiteration) { j = whereami; firstiteration = false; } if (ssfedata.rows[j][0] == ffedata.rows[i][0].tostring()) { found++; whereami = j; ...

go - Getting websocket connection information in JSON-RPC method -

i using json-rpc on websocket. and, in rpc method (say, multiply in example below), need know connection called method. part below says "// need websocket connection information here". how do so? package main import ( "code.google.com/p/go.net/websocket" "net/http" "net/rpc" "net/rpc/jsonrpc" ) type args struct { int b int } type arith int func (t *arith) multiply(args *args, reply *int) error { *reply = args.a * args.b // need websocket connection information here return nil } func main() { rpc.register(new(arith)) http.handle("/conn", websocket.handler(serve)) http.listenandserve("localhost:7000", nil) } func serve(ws *websocket.conn) { jsonrpc.serveconn(ws) } this challenging because violates abstraction rpc provides. here's strategy suggestion: google uses context object lots of apis: https://blog.golang.org/context . part of interface...

bluetooth - Unable to establish connection using Windows 7 and C# -

intro i getting follow error: system.argumentexception unhandled hresult=-2147024809 message=the iasyncresult object not returned corresponding asynchronous method on class. parameter name: asyncresult source=system paramname=asyncresult stacktrace: at system.net.sockets.socket.endconnect(iasyncresult asyncresult) @ inthehand.net.bluetooth.msft.socketbluetoothclient.endconnect(iasyncresult asyncresult) @ inthehand.net.sockets.bluetoothclient.endconnect(iasyncresult asyncresult) @ myapp_1.frmmt.connectmethod(iasyncresult balanceasyncresult) in c:\xxx\source\workspaces\mt\mt_1\mtx_1\mty_1\form1.cs:line 194 @ system.net.lazyasyncresult.complete(intptr usertoken) @ system.net.contextawareresult.completecallback(object state) @ system.threading.executioncontext.runinternal(executioncontext executioncontext, contextcallback callback, object state, boolean preservesyncctx) @ system.threading.executioncontext.run(executioncontext executioncontext, conte...

ios - Wait for AVSpeechSynthesiser to finish utterance -

i'm writing app allows users press button when hear web link want follow. the problem loop using adds text list of utterances , not wait utterance complete before continuing, meaning can't tell link want follow. i have class called speech which delegate of avspeechsynthesiser , have tried create own way of determining when utterance has concluded: -(id)init { self = [super init]; if (self) { _synthesiser = [[avspeechsynthesizer alloc]init]; [self setspeaking:no]; } return self; } -(void)outputasspeech:(nsstring *)text { [self setspeaking:yes]; [[self synthesiser]speakutterance:[[avspeechutterance alloc]initwithstring:text]]; } -(bool)isspeaking { return [self speaking]; } -(void)speechsynthesizer:(avspeechsynthesizer *)synthesizer didfinishspeechutterance:(avspeechutterance *)utterance { [self setspeaking:no]; } and in class viewcontroller -(void)readbookmarks { [[self speech]continuespeech]; [[self speech]outputasspeech:@"bookmarks,...

java - JFileChooser save dialog filename is modified or acted upon before approveSelection() is called -

i have filesaver class extends jfilechooser class. constructor defines file filters, sets default file filter , calls setacceptallfilefilterused(false) . when user clicks button, filesaver object created , showsavedialog() called it. filesaver class overrides approveselection() can validate filename entered before calling super.approveselection() . this fine filenames entered, if filename contains question mark ("?") or asterisk ("*") approveselection() not called , new file filter created (and appears set while program treats file filter previous setting) filename description. possible treat these filenames others (such approveselection() called , selected file set accordingly)? also, seems though filename containing forward slash ("/") treated path relative current directory , getselectedfile().getname() returns part of filename after slash (or removing slash @ end of filename) , part before appended directory path. possible approveselection...

oauth 2.0 - How can we add oauth2( serviceaccount) with emailsettings? -

previously using https://apps-apis.google.com/a/feeds/emailsettings/2.0 following approach manage sendas , set. gmailfilterservice = new gmailfilterservice(this.applicationname); gmailfilterservice.setoauthcredentials(oauthparameters, signer); gmailfilterservice.setreadtimeout(lxxx.readtimeout); gmailfilterservice.usessl(); how can use oauth2 service account googlecredential credential = new googlecredential.builder() .settransport(httptransport) .setjsonfactory(jsonfactory) .setserviceaccountid(serviceaccountemail) .setserviceaccountscopes(arrays.aslist(directoryscopes.admin_directory_user , directoryscopes.admin_directory_orgunit)) .setserviceaccountuser(adminemail) .setserviceaccountprivatekeyfromp12file( new java.io.file(serviceaccountpkcs12filepath)) .build(); gmailfilterservice.setoauth2credentials(credential); added jar files: core-1.47.1.jar (new...

sql server 2008 - Rollup multiple values in a Column to seperate columns -

i have below table... id phone address 1 502 100 main 1 602 100 main 2 502 500 s main 3 444 201 n point 3 777 201 n point 4 111 999 south i see... id phone1 phone2 phone3 address 1 502 602 100 main 2 502 500 s main 3 444 777 201 n point 4 111 999 south i can have more 2 phone#'s per id,i thinkin maybe pivot i'm not sure appreciative. the following script give result want. first establishes maximum number of phone numbers id. builds string pivot columns using maximum number of phone numbers (of form '[phone 1], ..., [phone n]' n being maximum number). dynamic sql statement built using pivot columns executed. create table #t( id int, phone int, [address] varchar(256) ); insert #t (id,phone,[address]) values (1,502,'...

java - How to assign/access variables in if statements on the same level -

so, need access variables assigned in if statements in last if statement. beginner in java , appreciated :) here compilation error. exception in thread "main" java.lang.error: unresolved compilation problems: local variable may not have been initialized local variable b may not have been initialized local variable c may not have been initialized local variable d may not have been initialized local variable e may not have been initialized and here code. need assign variable based on how many iterations have passed, , access variables after have been assigned on last iteration. public static void main(string[] args){ string a; string b; string c; string d; string e; scanner s = new scanner(system.in); for( int loop = 1; loop <= 6; loop++ ){ if(loop == 1){ system.out.println("please input grade."); = s.nextline(); system.out.println("you said,"+a); continue; } if(loop == ...

math - What is 6.280369834735099E-16 in just 3 decimal places? (Like x.xxx) -

i need answer in 3 decimal places. how it? is answer 0.628 or should put 16 zero's before 6, in case answer might 0.000 in 3 decimal places. that 6.280369834735099e-16 aka 6.280369834735099*10^-16 aka 0.000000000000000628 therefor 0 aka 0.00 mfg mist

ios - iTunes Connect prerelease build number warning symbol -

Image
i uploaded build test flight watchkit extension , getting warning symbol listed next build number build. does know about, how fix it, if means there issue app when submit review, etc? thanks. it's there because testflight doesn't support watchkit extensions right now. can still submit without issues.

c# - How to create a map from model to Entity, and Entity to model, with AutoMapper? -

i have model class account { public string name {get; set;} public string emailaddress1 {get;set;} } is possible configure automapper somehow loop through each property on class , map correct entity value. i able make converter reflection myself: public entity converttoentity() { var propertydict = typeof(account).getproperties().select(x => new keyvaluepair<string, object>(x.name, x.getvalue(typeof(account)))); entity entity = new entity(); foreach (var prop in propertydict) t[prop.key] = prop.value; return entity; } but how can achieve same kind of functionality automapper's createmap?

hex - Lua: Hexadecimal Word to Binary Conversion -

i'm attempting create lua program monitor periodic status pings of slave device. slave device sends status in 16-bit hexadecimal words, need convert binary string since each bit pertains property of device. can receive input string, , have table containing 16 keys each parameter. having difficult time understanding how convert hexadecimal word string of 16-bits can monitor it. here basic function of i'm starting work on. function slave_status(ip,port,name) status = path:read(ip,port) stable = {} if status stable.ready=bit32.rshift(status:byte(1), 0) stable.paused=bit32.rshift(status:byte(1), 1) stable.emergency=bit32.rshift(status:byte(1), 2) stable.started=bit32.rshift(status:byte(1), 3) stable.busy=bit32.rshift(status:byte(1), 4) stable.reserved1=bit32.rshift(status:byte(1), 5) stable.reserved2=bit32.rshift(status:byte(1), 6) stable.reserved3=bit32.rshift(status:byte(1), 7) stable.r...

Better performance than double SQLite inner join -

i have 3 tables (everything oversimplified question) student --- studentid (primary key) universityid (indexed) cityid (indexed) studentname university --- universityid (primary key) universityname city --- cityid (primary key) cityname i want print out student names, if names same, want order first cityname from, , universityname. so, have simple query one: select s.* student s inner join university u on s.universityid = u.universityid inner join city c on s.cityid = c.cityid order s.studentname asc, c.cityname asc, u.universityname asc is there way improve performance of in way, , how? the indexes on universityid , cityid not needed. the order optimized index on studentname .

windows - Ensuring HTML files open with FireFox -

just how linux files can contain top #!open/with/this/program line @ top, there equivalent line add html files ensure tries open firefox first (assuming firefox located in standard path). i referring windows here. no. html markup language, , knows nothing what's being used @ it. you can, though, have shortcut opens specified html file in firefox.

ios - APNS not working on AdHoc Distribution Profile on Google App Engine -

after push notifications sent , received using general ios development , apns development ios certificates, created ios distribution , apns production certificates adhoc testing. at first, created ios distribution certificate , installed keychain. created apns production certificate, installed keychain, , uploaded .p12 file server. finally, created provisioning profile , signed ios distribution certificate. when created , ipa-file , installed on device, push notifications not received. device asked permissions , got unique device id, server side fine. had faced problem , guide/tutorial followed? i followed article http://gnuromancer.org/2013/04/21/google-app-engine-apns/ the issue google app engine server. apnsservice service = apns.newservice() .withcert(inputstream, "password").withsandboxdestination() .withnoerrordetection().build(); if create adhoc or appstore build, along different certificate , provisioning profile, withsandboxdestination() ...

PhantomJS failing to load Google Maps -

my end goal open local html file javascript embedded, creating map polygons, , take screenshot of using phantomjs. have written simple js file this: var page = require('webpage').create(); page.open('https://www.google.com/maps', function(status) { console.log('state: ' + status); if(status === 'success') { page.render('example.pdf', {format: 'pdf', quality: '100'}); } phantom.exit(); }); this returns error: referenceerror: can't find variable: google i've tried on local html file , on other websites using google maps , keep getting same error. have been successful in taking screenshot of other websites without google maps. searching internet doesn't seem people have had issues this, , have been successful in taking screenshots of pages google maps...so i'm wondering wrong. another note: installed phantomjs gem in rails project , running javascript file through rails console using gem. ...

can any recursive looping happen from overwriting __dir__ in python -

suppose, have custom class not inherit class (which typically hard inherit from), builds wrapper along few other functions modify behavior of second class. class testclass: def __init__(self, *args, **kwargs): self.data = origclass(*args, **kwargs) def __getitem__(self, key): ... x = self.data.__getitem__(key) ... def __setitem__(self, key, value): ... self.data.__setitem__(key, value) ... @staticmethod def _try_attr(var, item): if hasattr(var, item): return var.__getattribute__(item) else: return none def __getattr__(self, item): return testclass._try_attr(self._data, item) def __repr__(self): ... def __str__(self): ... as such, testclass working fine new modifications, , falling on origclass methods using __getattr__ methods not re-implemented. however, in interactive mode (e.g. pycharm's python console) or otherwise, when try see __...

ios - Spritekit: move SKSpritekitNode in arc with SKPhysicsBody -

Image
i'm trying move skspritenode in arc physics in spritekit so: but unsure physic should apply (applyimpulse, applyforce, applytorque). currently using applytorque, code not work, , produces no movement on object: _boy.physicsbody.velocity = cgvectormake(1, 1); cgvector thrustvector = cgvectormake(0,100); [_boy.physicsbody applytorque:(cgfloat)atan2(_boy.physicsbody.velocity.dy, _boy.physicsbody.velocity.dx)]; applytorque not right method this. torque twisting force causes node rotate around center point. there no 1 easy command looking do. fail mention method of movement node. apply force, impulse, etc... going have come hack one. the sample project below looking , point in right direction. going have modify code suit specific project's needs though. tap/click screen once start moving node , tap/click screen second time start 90 degree movement change. #import "gamescene.h" @implementation gamescene { int touchcounter; bool changedir...

javascript - Nodejs Cluster with socket.io loses connections -

i using node.js cluster module in order create multiprocess socket.io server. using this example have created following server-client application: server: var cluster = require('cluster'); // start master process if (cluster.ismaster) { // create slave workers (in example there one) var worker = cluster.fork(); // starts server delegate connection worker var routerserver = net.createserver(function(connection) { worker.send({type: 'new_connection'}, connection); }); routerserver.listen(443, "my-ip-address"); } else { // start server on random port var slavehttp = require("http").server(); slavehttp.listen(0, "localhost"); // connect socket.io server var io = require('socket.io')(slavehttp); io.on('connection', function (socket) { console.log("connected"); }); // on server messsage (new connection) emit server process.on(...

image - Java Icon label -

Image
my question how save icon image variable in java? when values displayed sql database in jtextfields , can write them on pdf file in java. however, retrieve image database appears on jlabel . how image appear on pdf file in java? note details in jtextfields shown in pdf file when created. i want image appear in pdf file. string val8 = id.gettext(); icon val11 = lblimg.geticon(); try{ document doc = new document(); pdfwriter.getinstance(doc, new fileoutputstream("report.pdf")); doc.open(); doc.add(new paragraph("employee information", fontfactory.getfont(fontfactory.times_bold,18, font.bold, basecolor.red))); doc.add(new paragraph( "______________________________________________________________________________")); doc.add(new paragraph("employee id " + val));

java - How do I repackage certificates into pkcs #7 certificate using bouncy castle? -

i have root, intermediate , end entity certificates and, want package in pkcs # 7 format using bouncy castle. how can it? at first, have read latest rfc on pkcs#7/cms. please click on rfc link read. now fulfill objective, use bouncycastle. need generate cmssigneddata data . that, need prepare private key , certificate chain. here, going assume, have those. prepare cmsprocessablebytearray . cmsprocessablebytearray msg = new cmsprocessablebytearray("hello world".getbytes()); now, prepare store list of certificates. store certs = new jcacertstore(certlist); then declare cmssigneddatagenerator , add signerinfo , certificates. cmssigneddatagenerator gen = new cmssigneddatagenerator(); gen.addsignerinfogenerator(new jcasignerinfogeneratorbuilder(......)); gen.addcertificates(certs); then generate cmssigneddata cmssigneddatagenerator , cmsprocessablebytearray. cmssigneddata cmsdata = gen.generate(msg, true); finally write the byte array of cmssignedd...

c# - Error Calling InitializeCache on WindowsAzure Storage Account -

i have following snippet being called on on application start: var drivecache = roleenvironment.getlocalresource("imageslive"); clouddrive.initializecache(drivecache.rootpath, drivecache.maximumsizeinmegabytes); this has been working year or so. have upload new version of site , getting following error: exception of type 'microsoft.windowsazure.clouddrive.interop.interopclouddriveexception' thrown. @ throwiffailed(uint32 hr) @ microsoft.windowsazure.storageclient.clouddrive.initializecache(string cachepath, int32 totalcachesize) unknown error hresult=80070103 @ microsoft.windowsazure.storageclient.clouddrive.initializecache(string cachepath, int32 totalcachesize) @ site.global.application_start(object sender, eventargs e) this works when running within vs emulator presumably update. does have pointers how might go getting more information? cannot see way of getting more information, let alone sudden cause of error is. this has been found side e...

OpenId Connect reauthentication with only a token -

is possible restablish session openid connect authorization server (get cookies set in browser) without passing credentials (for example id token or access token or minimal data doesn't include user credentials) ? thanks there's extension of core openid connect specification called openid connect session management ( http://openid.net/specs/openid-connect-session-1_0.html ) allows type of functionality. when refreshing session rp send authentication request prompt=none parameter , id_token_hint contains current id_token . openid connect rp may issue new id_token , return rp in authentication response. see last 2 paragraphs of section http://openid.net/specs/openid-connect-session-1_0.html#rpiframe

javascript - How to convert a nested object into an array of objects? -

inputjson = { "mn": { "mt1": 1, "mtop": 2, "ot1": 3 }, "ln": { "mt1": 4, "mtop": 5, "ot1": 6 } } outputarrayofjson=[ { rs: "mt1", mn: 1, ln: 4 }, { rs: "mtop", mn: 2, ln: 5 }, { rs: "ot1", mn: 3, ln: 6 } ] rs hardcode key. i don't know why having hard time doing operation. it conversion of javascript objects inputjson = { "mn": { "mt1": 1, "mtop": 2, "ot1": 3 }, "ln": { "mt1": 4, "mtop": 5, "ot1": 6 } } d = {}; for(var key1 in inputjson){ for(var key2 in inputjson[key1]) { if(!(key2 in d)){ d[key2]={}; } d[key2][key1] = inputjson[key1][key2]; } } v = []; for(var k in d){ var o = {}; o.rs=k; for(var k2 in d[k]){ o[k2] = d[k...

php - Implementing a REST API w/ Google App Engine -

i have created rest api w/ slim framework (php microframework), few php files in ftp server, , sql table. i want implement simple configuration google api engine, , there's resources , confusing pages in google tutorials can't seem find i'm looking for... can steer me right direction please ? again, few php files (w/ slim) , sql database, that's it. thank much. if begin php tutorial google app engine, can find here 1 . try deploy existing app there, aware php runtime still in beta. app execute in restricted "sandbox" environment 2 . hope helps.

php - How to insert or update if a condition is true, but not at every row? -

when search word in searching box, if word not in database want add him giving suggestions, , if word in database want update number of searches of word can make top of popular words. it's google. search box works don't know how insert word 1 time not every time rows fetched. $cuvant=$_get['cuvant']; //the word introduce in searching box $sql="select * cautare";// cautare table keep words $resursa=mysql_query($sql); //the resource while($row = mysql_fetch_array($resursa)) { $nr=$row['nr_cautari'];//number of serching of each word if ($row['cuvant']!=$cuvant && $cuvant!=''){//if word not in database want insert him $nr=1; $sql2="insert cautare values('".$cuvant."',".$nr.")"; $resursa2=mysql_query($sql2); }else if($row['cuvant']==$cuvant && $cuvant!=''){ //if word in database want uptdate number_of...

c# - My player disappears when launching my 2D Unity game -

i trying create 2d platformer game in unity 5 following these tutorials: https://www.3dbuzz.com/training/view/creating-2d-games-in-unity-45 i running problem when hit play button in unity character not appear inside game. made sure on right layer , has of required scrips associated him , still no dice... here copy of source code: https://mega.co.nz/#!4yfavlxa!8uzienrqi3f1--4hsalppfw_icbckg7ugzvuwafmsyy in end issue main camera not far enough on z axis , unity rendering player behind camera! i fixed setting camera's z coordinate -100 instead on -10.

swing - Java: Draw a circular spiral using drawArc -

Image
i'm working on java programming exercise have draw circular spiral using drawarc method result looks similar this: i've been working on while , have far: import java.awt.graphics; import javax.swing.jpanel; import javax.swing.jframe; public class circspiral extends jpanel { public void paintcomponent(graphics g) { int x = 100; int y = 120; int width = 40; int height = 60; int startangle = 20; int arcangle = 80; (int = 0; < 5; i++) { g.drawarc(x, y, width, height, startangle, arcangle); g.drawarc(x + 10, y + 10, width, height, startangle + 10, arcangle); x = x + 5; y = y + 5; startangle = startangle - 10; arcangle = arcangle + 10; } } public static void main(string[] args) { circspiral panel = new circspiral(); jframe application = new jframe(); application.setdefaultcloseoperation(jframe.exit_on_close); application.add(panel); ...