Posts

Showing posts from April, 2010

json - Evaluate custom javascript method (CircularJSON) with Jade -

i want parse object client-side javascript through jade. work: script var object = json.parse(#{json.stringify(object)}); but object circular , need this script var object = circularjson.parse(#{circularjson.stringify(object)}); but throws error cannot call method 'stringify' of undefined which guess because jade doesn't recognise circularjson method. way make it? it require d , passed in locals response.render("index.jade", {circularjson : require('circular-json')}); or defined function in scope of jade - var circularjson = function(e,t){function l(e,t,o){var u=[],...//whole function script var player = circularjson.parse('!{circularjson.stringify(player)}');

c# - Can LocalDb and SQL Enterprise 2012 run side by side? -

i've installed sql enterprise 2012 , localdb appears inoperable. can access localdb command line , see instance referencing indeed running, when run project code first migrations enabled uses instance (localdb)\v11.0, error stating connection string may incorrect. didn't change connection string @ all, connection string set default while creating new project in visual studio 2012. has had same issue? there fix running both side side? here's exact error getting: an error occurred while getting provider information database. can caused entity framework using incorrect connection string. check inner exceptions details , ensure connection string correct. and exception: system.data.providerincompatibleexception: error occurred while getting provider information database. can caused entity framework using incorrect connection string. check inner exceptions details , ensure connection string correct. ---> system.data.providerincompatibleexception: provider did not...

javascript - jquery mobile slide out dialog box has previous leftover in it -

i have simple jquery mobile slide out dialog box, first time slide out works fine, comment box shows up, user can enter comments, submit, "thank you" follow. but when user closes dialog box , slide out dialog box second time, "thank you" still there, want fresh comment box generated instead. even when user enter in comment box without submit, , go back, next slide out dialog box still shows entered text! any appreciated. this html: <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css"> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script> </head> <body> <div data-role=...

Why does the first panel of ExtJS 4.2.1 accordion layout never close? -

i have extjs 4.2.1 accordion layout 3 panels. when app first launched, first panel open , 2nd/3rd closed. i can open , close 2nd , 3rd, can never close first panel. ext.define('myaccordion', { extend: 'ext.container.container', alias: 'widget.myaccordion', padding: 0, margin: 0, width: 200, layout: { type: 'accordion', align: 'stretch', animate: true, hidecollapsetool: true }, items: [{ xtype: 'panel', title: 'test volumes', layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'label', text: 'volume one' },{ xtype: 'label', text: 'volume two' },{ xtype: 'label', text: 'volume three' }] }, { xtype: 'panel...

android - Restore image to ImageView on Orientation Changed -

i writing simple app set image imageview through intent calling camera. when change orientation image disappears. i've tried questions q1 , q2 . previous questions suggest either use onsaveinstancestate or retaining object during configuration change . but in android docs i've read: you might encounter situation in restarting application , restoring significant amounts of data can costly , create poor user experience so, if bitmap consider “significant amount of data” need use setretaininstance , in docs says: while can store object, should never pass object tied activity, such drawable, adapter, view or other object that's associated context what approach should use able restore image on orientation change? what i've done far private imageview mphotoimgage; private bitmap mcameradata; oncreate { mphotoimgage = (imageview) findviewbyid(r.id.photoresultimage); if (savedinstancestate != null){ mphotoimgage.setimagebitmap((...

Breeze and Web API (gui and no gui) -

i'm building new spa, , i'm having problems dealing appear conflicting concerns. wonder if breeze experts can me out? so, on surface, spa basic crud. however, there's catch: want of functionality available web api. that sounds fit, given breeze works on top of web api, keep feeling i'm pounding square peg round hole. can give me tow? example of issue: suppose have screen creating/adding widgets. there validations there business rules (if widget weighs on 5 lbs, call web service sends email) so, breeze, that's pretty easy. hook efcontext provider, , hook beforesaveentity(ies) events , go town. great, but they want createwidget web api. it's not going acceptable client have build breeze compatible jobject bundle simulate save. the api seem want conventional dto/domain service sort of thing. like: string createwidget(widgetdto) breeze's client side library fantastic, , want able use gui app. i'm having hard time figurin...

c# - How do I write REST service to support multiple Get Endpoints in .net MVC Web API? -

so familiar how write default get, post, put, delete //get api/customer public string get(){} //get api/customer/id public string get(int id){} //post api/customer public void post([frombody]string value){} //put api/customer/id public void put(int id, [frombody]string value){} //delete api/customer/id public void delete(int id){} but how write add endpoint w/o having create whole new controller? want grab customer's metadata? need make changes routeconfig? if how that? , how use new route in javascript? //get api/customer/getmetadata public string getmetadata(){ } you use attribute route . attribute added in webapi 20 , can use @ method level define new route or more routes , way use [route("url/route1/route1")] : using 1 of examples above like: //get api/customer/getmetadata [route("api/customer/getmetadata")] public string get2(){ //your code goes here } if declaring several routes in class can use routeprefix attri...

Where do I correctly put this break statement in Python? -

i need put break statement, instructions of code say: break should go inside if statement, right after "congratulations!" message. from random import randint board = [] x in range(5): board.append(["o"] * 5) def print_board(board): row in board: print " ".join(row) print "let's play battleship!" print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col guess_row = int(raw_input("guess row:")) guess_col = int(raw_input("guess col:")) if guess_row == ship_row , guess_col == ship_col: break print "congratulations! sunk battleship!" #i want put break satement here, how? else: if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "oops, that's not...

python - Django: name 'SignupFormExtra' is not defined -

i have django-userena installed , trying override default sign form custom 1 can have fields, being new django, happen stuck. after following guide documentation userena have app called accounts. in app created 'forms.py' , put following info: from django import forms django.utils.translation import ugettext_lazy _ userena.forms import signupform class signupformextra(signupform): """ form demonstrate how add fields signup form, in case adding first , last name. """ first_name = forms.charfield(label=_(u'first name'), max_length=30, required=true) last_name = forms.charfield(label=_(u'last name'), max_length=30, required=true) industry = forms.charfield(label=_(u'industry'), max_length=50, requir...

php - How can I format currency by using JQuery -

this question has answer here: convert currency format 5 answers i trying format currency using code below: $('#currency').keyup(function(e){ var val = $(this).val(); val = val.replace(/[^0-9]/g,''); if(val.length >= 2) val = '$' + val.substring(0,2) + ',' + val.substring(2); if(val.length >= 6) val = val.substring(0,7) + val.substring(7); if(val.length > 7) val = val.substring(0,7); $(this).val(val); }); but work volume such "$10,000" or that, how can include thousands, hundreds, , millions in 1 code? here nice function in vanilla js handles things: var format = function(num){ var str = num.tostring().replace("$", ""), parts = false, output = [], = 1, formatted = null; if(str.indexof(".") > 0) { parts = str.split("....

Subtype polymorphism in scala -

what difference between following 2 declarations of sum functions? def sum[a](xs:list[a]) = ..... def sum[a <: list[a]](xs:a) = .... edit: elaborate more.... lets want write method head on list. i can write head follow: def head[a](xs:list[a]) = xs(0) or else can write def head[a <: list[a]] (xs:a) = xs(0) which 1 prefer , when? note: 1 difference figured out implicit conversions not applied second one the first 1 takes list[a] parameter, second 1 a subtype of list[a] . consider following example: scala> trait foo[a <: foo[a]] defined trait foo scala> class bar extends foo[bar] defined class bar the recursive type parameter on foo can useful, when want define method in trait takes or returns type of subclass: trait foo[a <: foo[a]] { def f: } class bar extends foo[bar] { def f: bar = new bar } class baz extends foo[baz] { def f: baz = new baz } i don't know how specific example should work, because don't...

java - Signing android app with cert valid only for few years -

i have signing certificate valid 2015. can used cert sign android app google has recommended use certificate valid upto 25 years. planning release app on google app store. will problems cert? thanks in advance. from http://developer.android.com/tools/publishing/app-signing.html if plan publish application(s) on google play, key use sign application(s) must have validity period ending after 22 october 2033. google play enforces requirement ensure users can seamlessly upgrade applications when new versions available. you have problems, because google play deny apk.

mysql - HQL with join of 3 tables and where condition -

we had report generating hql join between 2 tables worked correctly. changes db design, need same thing 3 tables now. not getting desired results. earlier, users had single role in system , role part of user table. in case following hql worked <![cdata[select new com.test.reportsmodel.agentreport(u, count( t.transactionid ), sum(case when t.status = 'created' 1 when t.status = 'paid' 1 when t.status = 'delivered' 1 else 0 end )) user u left join u.transactionsforagent t (t.invoicedate between :startdate , :enddate) u.role = 'externalagent' group u.userid]]> now db design has changed allows users have multiple roles in system. hence useraccess table has been created has userid , role in it. take care of change above hql has been updated <![cdata[select new com.test.reportsmodel.agentreport(u, ...

asp.net mvc - Adding filename in url -

i want customize route in asp.net mvc. @url.action("viewdoc", "home", new { filename = "abc.pdf" }) and routes.maproute( name: "", url: "{controller}/{action}/{filename}", defaults: new { controller = "home", action = "viewdoc", filename = urlparameter.optional } i get http://localhost/home/viewdoc?filename=abc.pdf how below? http://localhost/home/viewdoc/abc.pdf the code have pasted correct ordering in route setup wrong. move routes.maproute method above default route , should work expected.

javascript - How to save canvas compressed -

so have upload script save canvas image looks this. js: function save_as() { var canvas = document.getelementbyid("originalcanvas"); var dataurl = canvas.todataurl(); var filename = document.getelementbyid('sa_filename').value; if(filename.length < 3) { cerror('filenameshort'); } else if(filetype == 'none') { cerror('filetypenotselected'); } else { // call upload.php , post data $.ajax({ type: "post", url: "file-upload/uploadas.php", data: {image: dataurl, filetype: filetype, filename: filename} }).done(function( respond ) { console.log("saved filename: "+respond); }); } } php: <?php if (isset($_post["image"]) && !empty($_post["image"])) { if (isset($_post["filetype"]) && !empty($_post["filetype"])) { if (isset($_post["filename"]) && !empty($_post["fi...

javascript - false returned when comparing 2 identically looking strings -

i use node.js script scraping , noticed 1 of strings scraped don't pass regex.regex isn't important here, string acts strange, here's example: var scrapeddata = '1111 test1' var mydata = '1111 test1' scrapeddata === mydata false now, if manually remove space between 1111 , test1 inside scrapeddata, , enter space, ok. var scrapeddata = '1111 test1' // manually deleted , added space var mydata = '1111 test1' scrapeddata === mydata true so guess scrapeddata contains hidden character breaks regex, might have encoding(utf-8 used) ? replaced single space character ' ' ? maybe helps: try using escape see actual char. example: escape('1111 test1') should return "1111%20test1" if char space.

Better performance for Java Canvas Buffered images -

i using java canvas , have draw method, called 20 times second. iterates through array of images , draws scaledinstance of them depending on window size: g.drawimage(img.getscaledinstance( (short)math.round(rect.width * yvector), (short)math.round(rect.height * yvector), image.scale_smooth), (short)math.round(rect.x * xvector), (short)math.round(rect.y * yvector), null); performance bad. using buffer strategy , how images, bufferedimage, declared: try { image = imageio.read(new file("resources/drawable/" + src)); img = (bufferedimage)image.getimage(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } the performance issues came getscaledinstance . scaled image 20 times/second, not performant. our application has fixed positions , sizes, runs stable, high fps rate.

Unattended installation of Azure SDK via PowerShell -

i'm having problems create unattended installation of cmdlets of azure (it's msi file, windowsazure-powershell.0.8.3.msi, current version). how can know parameters installation needs , how should write it? in way? $msifile= '<path>\windowsazure-powershell.0.8.3.msi' $arguments= ' /qn /l*v .\options.txt' start-process ` -file $msifile ` -arg $arguments ` -passthru | wait-process so how can perform that? thanks in advance. don't worry commandline switches. can using wmi , powershell $product= [wmiclass]"\\.\root\cimv2:win32_product" $product.install("c:\temp\windowsazure-powershell.0.8.3.msi")

android - EditText steals focus from other EditTexts inside ListView -

Image
i have stand-alone edittext , listview . each item in listview has 2 edittext fields. when touch inside listview edittext , stand-alone edittext steals focus. makes impossible edit of listview edittext fields. name steals focus other textview elements inside listview here activity's xml, containing stand-alone edittext , listview <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margintop="16dip" android:orientation = "vertical" > <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginbottom="16dip" > <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layou...

build - Boot.img too large -

i have compiled kernel source htc evo 4g. zimage. so, when build whole tree, use zimage kernel instead of prebuilt kernel. however when build whole android tree, following error: out/target/product/supersonic/boot.img total size 5988352 error: out/target/product/supersonic/boot.img large (5988352 > [5406720 - 270336]) make: * [out/target/product/supersonic/boot.img] error 1 make: * deleting file `out/target/product/supersonic/boot.img' searching in web, didn't find solution. i found size of partitions defined in file device/htc/supersonic/boardconfig.mk , don't know how change them. board_bootimage_partition_size := 0x00280000 board_recoveryimage_partition_size := 0x00500000 board_systemimage_partition_size := 0x15e00000 # limited enforce room grow board_userdataimage_partition_size := 0x1aba0000 board_flash_block_size := 131072 i don't know how solve issue. in case boot partition limited to: 0x00528000 - 0x00042000 5mb. thats sma...

django - Mongoengine query to return matching elements from an array of the same document in a collection -

what mongoengine query return locations names starts "b" below document of collection? { "_id" : objectid("5388ae8df30090186310ed77"), "city" : "pune", "locations" : [ "kalyani nagar", "vishrantwadi", "camp", "bhawani peth", "kasarwadi", "deccan gymkhana", "dhankawadi", "wanowrie", "sinhagad road-vadgaon budruk", "kothrud", "pune cantonment", "bibvewadi", "shivaji nagar", "pimple nilakh-pimpri chinchwad", "thergaon", "dapodi", "wakad", "katraj", "pashan gaon" ] } collection.objects(locations__istartswith = "b",city__iexact = "pune...

jquery - Installing superslides plugin -

i need installing this plug-in . download included lot of files bit confused ones use. ones have used have made no effect @ all. don't know whether it's files or haven't linked files correctly (i have of files in same folder that's not problem). i've used superslides.css, query.superslides.js , query.superslides.min.js. this html used: <script type="text/javascript" src="jquery.superslides.js"></script> <script type="text/javascript" src="jquery.superslides.min.js"></script> <link type="text/css" rel="stylesheet" href="superslides.css"> <body> <div id="slides"> <div class="slides-container"> <img src="http://flickholdr.com/1000/800" alt=""> <img src="http://flickholdr.com/1000/800" alt=""> </div> </div> </body> can superslides ex...

RegEx match table cell -

regex question again i'm using pcre syntax , i'm trying find solution matching cells in simplified table (like in trac) let have: ||cell||cell||cell|| ||cell||cell||cell ||cell||||cell|| ||other table cell|| ok, need make 2 tables out of above, (second line misses ending, third has colspan=2 @ second cell) the idea simple must catch every occurrence of ||cell i'm interested catch occurrences of | , text next occurrence of double | or new line, need avoid ! before pipes, , know distance beginning of line. i spend whole day trying this... maybe i'm stupid... or maybe .net has verid implementation of regex. this grabs content of every cell, you're talking about? (?<=\|\|)[^|\r\n]* see demo explanation (?<= # behind see if there is: \| # '|' \| # '|' ) # end of look-behind [^|\r\n]* # character exc...

php - Laravel/Entrust - Get Roles For Permission -

i'm trying figure out how permissions role laravel , entrust. uses pivot table called permission_role has role_id , permission_id stored in it. what i'm trying role it's id , permissions associated role. think may on complicating it, since have had 0 luck on hoping me out. you may try this: // hope have this: class role extends entrustrole {} then permissions role id 1 : $role = role::with('perms')->find(1); // assumed 1 role id dd($role->perms); // permissions in role

serializable - is there a built-in way to detect if a serialized java object is missing fields? -

i'm making compatible modifications serializable class, namely adding few primitive fields (boolean, long). class client-side representation of data provided server. when load class file, need able detect if loaded class saved earlier version, i.e. missing fields java set default value on load. if case, app still work, when client has network connectivity, i'd fetch new fields server. does java have built-in methods detect if class missing fields loaded? (i realize can solve manually "version" instance member; hoping though java has built-in) you can override readobject() method of serializable interface custom handle deserialization of class. note strongly recommended include serialversionuid whenever implement serializable: private static final long serialversionuid = 1; if don't define it, 1 created hash of class's members... if later add things describe, uid won't match , java won't let reload old data. more info seria...

DIR Command in Windows Command Line -

how use dir command list directories, including subdirectories, contain no files? i've researched @ length , can find how delete specified directories, not list them. can help? there better way other dir command? you modify powerscript answer on linked question display instead of delete this: get-childitem -recurse . | { $_.psiscontainer -and @( $_ | get-childitem ).count -eq 0 } | select-object -property fullname

c# - Data grid view text box event handler -

i stuck annoying problem, glad help. i have datagridview 6 columns (one combo box , others text boxes). want handle textchange(text box) event , selectedindexchange event(combo box), keep error , don't know why. this error: an exception of type 'system.formatexception' occurred in mscorlib.dll not handled in user code additional information: input string not in correct format. this code datagridview1.editingcontrolshowing += (sender, e) => { if (datagridview1.currentcell.columnindex == 0) { combobox cb = (combobox)e.control; cb.selectedindexchanged += (sender2, e2) => { this.client.roaming[datagridview1.currentcell.rowindex].country = cb.text; //dictionaries.gettypedict()[country.name + datagridview1.currentcell.rowindex.tostring()].invoke(convert.tostring(cb.text)); ...

Precompile ASP.NET Web Pages razor (*.cshtml) files -

for mvc project, there <mvcbuildviews>true</mvcbuildviews> property can set in csproj file, see e.g. here . however, has no effect in web pages kind of project. there similar switch use? note: typical web pages project of type "web site", i.e. no csproj. solution, however, uses web pages inside normal web application project have csproj, compiles fine, runs fine, don't have compile-time checking of *.cshtml files i'd add. i think should take @ razorgenerator implementing soultion want. not sure if work web site project

android - Picasso url does not load -

i have dynamic url show avatars users. http://www.dapptapp.com/contents/avatar/200/200/27.png the image show in browser picasso not show image. the current code used: getpicasso().load("http://www.dapptapp.com/contents/avatar/200/200/27.png").into(civavatar); is has headers of image or something. can't seem pinpoint error. if use other regular image web there no problem. postman response on url: connection →keep-alive content-encoding → content-encoding type of encoding used on data. gzip content-length →36908 content-type →image/png date →tue, 03 jun 2014 14:44:22 gmt keep-alive →timeout=1, max=100 server →apache vary →accept-encoding,user-agent i run problem too. if ok-http lib not provided, picasso using urlconnectiondownloader load url. seems times load url param boolean localcacheonly=true, , header setting httpurlconnection. connection.setusecaches(true) connection.setrequestproperty("cache-control", "only-if-cached,...

php - Check if public object property is set with variable as pointer -

ola! so got $_post looking like: array ( [name] => foobar [sobject] => tbl_character [id] => 102 ) and "smartobject" like: smartobject object ( [_settings] => array ( [table] => tbl_character [ignores] => array ( [0] => leaderid [1] => typeid [2] => senderid [3] => recieverid [4] => imageid [5] => fileid [6] => professionid [7] => id ) [prefix] => tbl_ ) [id] => 102 [worldid] => [accountid] => 110 [zoneid] => [raceid] => 1 [imageid] => [name] => asd ... blabla more data ) what want loop through $_post , check if keys match public set property on smartobject so: foreach($_post $key => $value) { if(i...

sql - MySQL SubQuery doesn't seem to work -

i have database table named "married" consist of numerous fields, 2 fields in particular make-up table primary-key. 2 field names are; "number", "date". there many records in duplicate share same "number" have different "dates" associated. i need delete record (row) within each pair, "number" common between two, has older "date" associated. there goes wrong in query. delete number married number in(select number married) , date <any( select date married) you want delete recent date each number. in mysql, limited in use of table deletions occurring in rest of query. fortunately, can around using join . think want: delete m married m join (select number, max(date) maxd married group number ) tokeep on m.number = tokeep.number , m.date < tokeep.maxd;

Export command line output to a file in Python -

here's code execute jar file in python: import os os.system("java -jar xyz.jar") i can see output on terminal, want store in file. how can that? with subprocess.call can pipe outputs (stdout, stderr or both) directly file: import subprocess subprocess.call("java -jar xyz.jar", shell=true, stdout=open('outfile.txt', 'wt'), stderr=subprocess.stdout) note added shell=true parameter, required if application requires shell-specific variables (such java located). also note in above call, output streams handled follows: stderr stream piped stdout, and stdout piped outfile more details on stream configurations available in subprocess manual page .

c - Placing a new node into the next available position in a binary tree heap? -

let's have data structure minimum heap: struct node{ int height; struct node *parent; struct node *left; struct node *right; }; what want add new node next available position (keeping min heap property not matter @ point.) have far in case of empty tree (the root instantiated earlier null earlier in code). having trouble figuring out logic in case root exists. need add elements in 1 one. understand how using heap array, need using heap binary tree. void insert(int number) { struct node *nodetoinsert; nodetoinsert=(struct node*)malloc(sizeof(struct node)); nodetoinsert->value = number; if(root == null) { root = nodetoinsert; root->left = null; root->right = null; } } if understand correctly, want know how descend complete binary tree insert next node. need know how many nodes in bottom level. bits of number tell how turn (left or right) move down tree next available position. happliy, c...

javascript - Why isn't this jQuery script replacing the video declaration with the GIF declaration on an HTML page -

i'm writing jquery script detect when user visiting website on ios device, , when are, switch background of website video gif, since .mp4 , .webm files aren't supported on ios version of safari. script uses modernizr.js , uisearch.js supporting files. script directly included in html, not separate file. here is: $(document).ready(function() { if((navigator.useragent.match(/iphone/i)) || (navigator.useragent.match(/ipod/i)) || (navigator.useragent.match(/ipad/i))) { ('.video-background').remove(); ('body').prepend('<img src="./index_files/test_cut_gif.gif" id="backgroundimage" class="video-background">'); } }); the html attempting change looks this: <body div="main" class="html front not-logged-in no-sidebars page-node page-node- page-node-16 node-type-panel role-1 lightbox-processed"> <div class="video-background"> <video ...

xcode - iOS unit testing on a Mac running Mountain Lion (OS X 10.8.5) -

i have ios project comes older xcode (4.6.3) , did not include test target default, projects in latest xcode versions seem include. have xcode 5.1.1. on mac running os x 10.8.5. i've reading this apple's document regarding unit testing in xcode, looks need os x mavericks, @ least installing , configuring os x server, don't you? i'd appreciate guidelines follow add test target project , how integrate testing process in workflow if not have os x maveriks. thanks in advance edit: there anyway of run tests in normal running of app? mean, need test cases involve update of data @ hours, , update of parameters , gui after data update... how this? thanks you need mavricks if wish use xcode service, apple's continuous integration server. not need mavricks run unit tests, miss out on pretty in-xcode reports. without mavericks, can run unit tests manually pressing cmd+u or going product->test . you can setup own continuous integration service , run...

rest - Using HTTP POST to query a Database -

can use rest http post query database, designing rest api service . confusion whether use get or post . want pass parameter query thinking use post . reading on net found get should used if there read access , post should used when create on server side if want render information based on identifier should through get . basically crud treated rest assigning dedicated http methods follows: create => post read => update => put delete => delete if using post getting read information there's no harm violating rest principle

.net - Calling a secured WebService from jQuery safely -

i have webservice has several calls available members of site. want build pure html/jquery mobile app can call service make requests , download information. my initial plan put users' username , password in auth header i'm worried exposing them traffic sniffers. can create session key after initial authentication call in token may vulnerable session stealing. my current plan is: implement login call, return token expire after designated time the js calls in token (thereby reducing number of times password sent). the user makes calls the token compared against user's ip address. the user logs out, ends session , removes key reduce risk another thought encrypt password send it. possible/sensible public/private key encryption in js based on .net rsacryptoserviceprovider implementation? what best approach handle authentication, ideally without purchasing ssl certificate (the data not particularly sensitive). ? apart obvious reasons why ssl highly r...

java - Thymeleaf th:if expression not evaluating true -

i trying evaluate expression 2 strings, evaluating true well, when used within th:if not working expected. the below code trying <div th:with="cntx=${#httpservletrequest.getrequesturi()}"> <li th:each="obj : ${list}" th:with="path=${obj.path}" th:if="${path == cntx}"> <span th:text="${obj.title}"></span> </li> </div> the context above code, i have list of objects contain link has displayed in 1 of objects. trying string equality th:if, expression here ${path == cntx} failing reason , not showing on final rendered page. i checked path , uri values equal i.e /test path , /test cntx, evaluating true if print out using th:text. quite strange behaviour. my guess if evaluated before th:with . try : <th:block th:each="obj : ${list}" th:with="path=${obj.path}"> <li th:if="${path == cntx}">...</li> </th...

mysql - How to match a word from string and retrieve data in SQL Query and PHP? -

i have mysql table this brand -------- honda sozuki oddi . . . now there dynamic array in php : $brand = ["sozuki","honda"] the question how retrieve data matches word in above array. tried : $qry = 'select * brand brand '% $brand[0] %' , '% $brand[1] %'; it works fine if have no specific length of array, can dynamic array. solution appreciated thanks try $qry = "select * brand brand "; $i=1; $count = count($brand); foreach($brand $v) { $a = ($i < $count ? 'and' : ''); $qry .= " '% $v %' $a "; $i++; } echo $qry;

Facebook Post likes -

i've question in regards fb graph api. assuming search likes related facebook post,i have this: 541729512538864_792100727501740/likes/ but if find whether user(me) has liked specific post(not page)?i've tried doing way. 541729512538864_792100727501740/likes/<my user id> but not return results.so would actual graph path be?i gladly appreciate help,thank :d! with graph api not possible imho. you'll need use fql instead: select post_id, like_info.user_likes stream post_id="541729512538864_792100727501740" will return { "data": [ { "post_id": "541729512538864_792100727501740", "like_info": { "user_likes": false } } ] } in case. bound user of access token you're using running query with. see https://developers.facebook.com/docs/reference/fql/stream/ reference.

google chrome - When will the tabId change -

i working on chrome extension capturing of web data. found change address bar can lead tabid change. has full idea when there change tabid? by no means authoritative answer: it has pre-rendering, , specific case may have instant search. type in address bar, chrome apparently pre-fetches , pre-renders pages faster navigation. if not trigger via address bar, chrome still can tab swapping performance reasons. consider description of chrome.tabs.onreplaced : fired when tab replaced tab due prerendering or instant. or, this remark in chrome.webnavigation api docs: not navigating tabs correspond actual tabs in chrome's ui, e.g., tab being pre-rendered. such tabs not accessible via tabs api nor can request information them via webnavigation.getframe or webnavigation.getallframes . once such tab swapped in, ontabreplaced event fired , become accessible via these apis. to summarize: for performance reasons chrome can spawn separate, invisible tab, , ...

javascript - undefined function when triggering a onmouseover of a div with jQuery -

i getting undefined function error. have defined function on onmouseover not working. my code html <div class="col2" onmouseover="show_info('<?php echo $sub_menu['page_id']; ?>');" onmouseout="hide_info();"> <a href="#"> <img src="css/images/img1.png" /> <h3><?php echo $sub_menu['page_title']; ?></h3> </a> </div> script <script> function show_info(id) { alert('hiiii'); var data = "page_id ="+id; $.ajax({ url:"get_page_info.php", type:"post",data=data,cache:false, success: function(html) { document.getelementbyid('hide').style.display='none'; document.getelementbyid('show').innerhtml=html; } }); } function hide_info() { document...

ios - No Background when Rendering an UIView to a PDF -

in ipad app use following method render uiview pdf. + (nsdata*)createpdffromuiview:(uiview*)aview { nsmutabledata *pdfdata = [nsmutabledata data]; uigraphicsbeginpdfcontexttodata(pdfdata, aview.bounds, nil); uigraphicsbeginpdfpage(); cgcontextref pdfcontext = uigraphicsgetcurrentcontext(); [aview.layer renderincontext:pdfcontext]; uigraphicsendpdfcontext(); return pdfdata; } this works quite fine. problem rendered correctly (all subviews) views background white. have change if want view's background rendered correctly? if view has valid bg, rendered pdf: @implementation viewcontroller - (void)viewdidload { [super viewdidload]; //bg self.view.backgroundcolor = [uicolor redcolor]; //make pdf nsdata *pdf = [viewcontroller createpdffromuiview:self.view]; [pdf writetofile:@"/users/dominik/t.pdf" atomically:no]; } + (nsdata*)createpdffromuiview:(uiview*)aview { //question source code (see a...

User interactive animation in matlab -

i trying make user interactive animation in matlab. square translates , rotates across screen , user has click on it. if click on it, receive points , animation repeat. if click on whitespace (eg. anywhere except within square) animation exit , lose displayed. have animation finished using 2 functions. 1 create animation , registers mouse click. far can recognize mouse click , animation stop if user clicks on whitespace animation not repeat if user clicks within polygon. unsure how modify code animation repeat until user clicks white space. have pasted code below. appreciated. animation function: function movingpolygon global guserhitpolygon; global gcurrentxvertices; global gcurrentyvertices; guserhitpolygon = true; nsides =4; %polar points r=1; theta = pi/nsides * (1:2:2*nsides-1); %cartesisn points x0 = r * cos(theta); y0 = r * sin(theta); nframes = 100; xx = linspace(0,10, nframes); yy = xx; rr = linspace(0, 2*pi, nframes); h = figure; set(h,'windowbuttondown...

javascript - Is there any way to load a local JS file dynamically? -

for development purposes, i'd able load locally-stored scripts browser instead of having copy-paste console. creating new <script> element isn't working, gives not allowed load local resource: file://.... error (in chrome). also, creating userscript won't work--i'd have re-install every time make edit. is there alternative way load local script via bookmarklet/etc? in chrome, can create extension holds of local files need load. make files accessible via chrome-extension://... instead of file://... make file named manifest.json in new folder , fill with: { "name": "file holder", "manifest_version": 2, "version": "1.0", "web_accessible_resources": ["test.js", "other.js", "yetanother.js"] } then, put scripts want load in new directory, , make sure included in web_accessbile_reources manifest list. load extension going chrome://extensions ,...

Mock command line arguments for Python script with `optparse`? -

a python script want use (called snakefood ) run commandline , takes commandline arguments, eg: sfood /path/to/my/project the parsing of commandline arguments happens in file called gendeps.py using optparse . however, want use snakefood module script. there way can somehow mock passing of commandline arguments snakefood or way of rewriting gendeps.py doesn't depend on optparse anymore? you can assign new list sys.argv : import sys sys.argv = ['programname', '-iq', '-q', directory] gendeps.gendeps() optparse uses sys.argv[1:] input when no explicit arguments have been passed in.

groovy replace double quotes with single and single with double -

i have string "['type':'multipolygon', 'coordinates':[[73.31, 37.46], [74.92, 37.24]]]" how can replace single quotes double quotes , double single? result should this: '["type":"multipolygon", "coordinates":[[73.31, 37.46], [74.92, 37.24]]]' from link given @yate, can find method: tr(string sourceset, string replacementset) and apply string as: def yourstring = ... def changedstring = yourstring.tr(/"'/,/'"/) that job.

Enable a mercurial extension in .hgrc only if it's present -

i have lot of things in .hgrc file keep in repository , share between computers. i have lot of extensions enabled in [extensions] section, don't want use of them on of computers. unfortunately, whenever try use mercurial shared .hgrc file on computer don't have every single 1 of specified extensions installed, message of form: *** failed import extension evolve $hg_extensions/mutable-history/hgext/evolve.py: [errno 2] no such file or directory: '/home/botond/programs/mercurial/extensions/mutable-history/hgext/evolve.py' every time run hg command! is there way avoid this? example, there way specify in .hgrc file, "load extension if can find it, otherwise don't load , quiet it"? (then, if try use extension, i'd error.) additional search terms: how conditionally enable mercurial extensions activate mercurial extension based on condition enable mercurial extension if exists use projrc extension enable , extensions i...

how do you specify a timeout for an Intern test that returns a promise -

in intern can specify timeout using this.async(), example var d = this.async(1000); xhr(..., d.callback(...)); return d; however, how can specify timeout if test returns promise? example: return asyncfunc().then(function(res){ assert.strictequals(res, 2); }); set this.timeout timeout value. see writing tests intern more details.

python - Pandas get date from datetime stamp -

i'm working pandas data frame 'date_time' column has values datetime stamps: 2014-02-21 17:16:42 i can call column using df['date_time'], , want search rows particular date. i've been trying along lines of df[(df['date_time']=='2014-02-21')] but don't know how search date datetime value. also, i'm not sure if it's relevant, when check type(df.date_time[0]) returns string, instead of datetime type object. thanks lot. it more efficient not use strings here (assuming these datetime64 - should be!), these have calculated before comparing... , string stuff slow. in [11]: s = pd.series(pd.to_datetime(['2014-02-21 17:16:42', '2014-02-22 17:16:42'])) in [12]: s out[12]: 0 2014-02-21 17:16:42 1 2014-02-22 17:16:42 dtype: datetime64[ns] you can either simple ordering check: in [13]: (pd.timestamp('2014-02-21') < s) & (s < pd.timestamp('2014-02-22')) out[13]: 0 true ...

Having trouble in c# fraction calculator -

Image
i have assignment due tomorrow has add , subtract fractions whole numbers, , i'm getting bit confused these numbers, , math isn't helping either. it's performing math correctly, keeps putting 1 whole variable when should 0 , can't figure out life of me why. here's fraction.cs: class fraction { int num, den, whole, newnum; public fraction(int numerator, int denominator, int whole = 0) { this.num = numerator; this.den = denominator; this.whole = whole; } public fraction add(fraction other) { int temp1 = num, temp2 = den; if (math.abs(this.whole) > 0) { newnum = temp2 * whole; newnum = +temp1; temp1 = newnum; } if (math.abs(other.whole) > 0) { other.newnum = other.den * other.whole; other.newnum = +other.num; other.num = other.newnum; } temp1 = temp1 * other.den + temp2...

javascript - Generated Google Chart Page not working -

i'm using codeigniter generate page google chart data mysql database. page isn't displayed (no chart @ all). don't know part of generated code wrong. generated code this: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setonloadcallback(drawchart); // create our data table out of json data loaded server. var data = new google.visualization.datatable(); data.addcolumn('number', 'time'); data.addcolumn('number', 'va'); data.addcolumn('number', 'vb'); data.addcolumn('number', 'vc'); //var d = new date(); data.addrow([1400230864720,9192114,9194641,9190145]); data.addrow([1400230864740,9191693,9194641,9189443]); ...