Posts

Showing posts from July, 2011

javascript - Remove invalid characters from email -

i want users mistakenly entering invalid characters in email input (pre server-side validation/cleanup) note: not validating emails in frontend, cleaning up // coffeescript $(element).find('input[type="email"]').on 'change keyup', (event) -> = $(this) v = i.val() i.val(v.replace( [what goes here?] , '')) i want remove space , illegal characters. what's regex pattern? something like. saying, strip things not want. honest, not know acceptable email chars. .replace(/[^a-za-z0-9_-@.]/g,'')

triggers - SQL - Default Value of other columns/fields -

i have access db contains following column/fields: [id], [itemcode], [imagecode]. the filecode "computed" expression of: [itemcode] & "img" & [id] & ".jpg" so if [id] , [itemcode] "4" , "item008a" (respectively) [imagecode] be: "item008aimg4.jpg". however, migrating sql, , while rebuilding table, found can't column's default value or computed formula. i've read triggers best resolve, have written triggers affect other tables , not (if possible?). is there more direct? if not, trigger like? any appreciated. thanks. you can add computed column alter table tablea add imagecode cast(itemcode varchar(10)) + 'img' + cast( id varchar(10)) + '.jpg'

html - Disable -ms-overflow-style "auto-hide" without disabling the bar completely -

in ie11, website bodies scrollbar keeps disappearing , re-appearing whenever cursor goes page , out. read ie-exclusive '-ms-overflow-style' css style problem. set following 2 css properties onto body element: body { -ms-overflow-style: none !important; overflow-y: auto; } i still want scrollbar appear when there overflowing content vary depending on browsers window height. don't want disappear , reappear in ie "auto-hide" feature. basically, want behave same ff , chrome. problem is, seems once set '-ms-overflow-style' 'none', ie11 ignores 'overflow-y' also. frustrating. if grammar bad, sorry, i'm tired. thanks in advance! you can use: -ms-overflow-style: scrollbar instead of none . source: http://msdn.microsoft.com/en-us/library/windows/apps/hh441298.aspx

java - HtmlPage.save() doesn't preserve arabic characters -

using htmlunit 2.15 , trying call myhtmlpage.save(file) on page has both english , arabic content doesn't save page in correct format. ??? (question marks) displayed in place of arabic characters. code snippet: file filetosave = new file("d:\\abc.txt"); final htmlpage startpage = webclient.getpage(baseurl); startpage.save(filetosave); opening saved page in browsers (chrome & ie8 both) or editor (notepadd++) shows ?? arabic characters. how htmlpage.save() save correct arabic characters? in advance.

android - Deleted items of arraylist appear on listview when device mode changes from Landscape to portrait mode OR portrait to Landscape mode -

hello friends, deleting items of arrylist listview item of arrylist become deleted problem occurs when change device mode (landscape portrait mode ) or ( portrait landscape mode ) deleted item becomes visible on listview.please me short these problem.thanks in advance thanks lot dear friends yours valuable comment.... change in manifest file , work fine me..again friends..below line have added in manifest file along activity android:configchanges="orientation|keyboard|keyboardhidden|screensize|screenlayout|uimode or use these android:configchanges="orientation|screensize|screenlayout"

android - How to get number of pending matches with Google Play -

what best way number of pending matches google player game services? i thinking of loading current matches, filtered ones a) turn pending or b) have invitation pending. the way see this, using loadmatchesbystatus , seems major overkill, async load all match data , care number of matches (i don't need of match data ). are aware of in api provide me way find number of pending games, without loading of game data? thanks! currently there no way load 'count' of matches without loading rest of match metadata. i assume using kind of notification badge/alert. if concerned performance keep track of counter locally. example increment whenever turn notification, decrement when take turn, etc.

asp.net - Grid view and class library -

i using class library , asp.net form. in class library created class retrieving database value based on specific fileid.i have no idea how connect class gridview.tried using gridview.databind(obj).not working. appreciate thanks in asp.net form dim retobj new mailbox retobj.mailboxname = mailb.text insmairet = new clsmailboxcollect insmairet.retrievemail(retobj) gridview1.databind(retobj) the simplest way use sqldatasource , gridview . you can use follows: <asp:sqldatasource id="sqldatasource1" runat="server" datasourcemode="datareader" connectionstring="<%$ connectionstrings:mynorthwind%>" selectcommand="select firstname, lastname, title employees"> </asp:sqldatasource> <asp:gridview id="gridview1" runat="server" datasourceid="sqldatasource1"> </asp:gridview> click here ...

javascript - backbone routes, creating a faux route? -

i not sure if have used technical term, or describe wanting backbone routes. in application user logs dashboard , can see activity related them, clicking on activity link create modal them edit activity. on landing in dashboard url http://app.dev/#dashboard on clicking link want modal overlay dashboard, url change http://app.dev/#activity/edit/:id without losing activity view should site behind model, app navigations edit route , re-renders everything, there way preserve view change url? you need create subview render edit view (or create overlay popup). either way, cannot using <a href> tag, need via javascript. backbone.js has way navigate through routes using: router.navigate(fragment, options) - see backbone navigate using {trigger:true} can call router function (which happens now) , re-render view using router function (as if user landed on page). default, , if pass {trigger:false} , backbone change url, not trigger router function, transparent use...

c++ - pass shared_ptr as a argument to a function which accepts object of a class type -

i wondering , possible pass shared_ptr argument function accepts pointer of class type example class class_a_type { bla bl private: istuff *mstuff; } class istuff { public: ireporter(){}; virtual ~ireporter(){}; virtual void reportresults( class_a_result_type *presult) = 0; }; void class_a_type::sendresultback( bool status, std::string statusstring ) { boost::shared_ptr< class_a_result_type >aresultbptr( new class_a_result_type ( mstuff, getpropertyname() ) ); bool lbool = false; std::string lstr = "running"; aresultbptr->setstatus( lbool, lstr ); mystuff->reportresults( aresultbptr );// error how pass shared _ptr ?? } you should call get function on shared_ptr . mystuff->reportresults( aresultbptr.get() );

Formatting and displaying locals in Stata -

i came across little puzzle stata's locals, display, , quotes.. consider example: generate var1 = 54321 in 1 local test: di %10.0gc var1[1] why call: di "`test'" returning 54,321 whereas call: di `test' shows 54 321 what causing such behaviour? complete sequence (1) . di 54,321 54 321 (2) . di "54,231" 54,321 display interprets (1) instruction display 2 arguments, 1 one. same result last line (first) local macro test evaluated , (second) display saw result of evaluation. the difference when quotation marks supplied thereby insist argument literal string. same result first display command same reasons given. in short, use of local macros here quite incidental differences in results. display never sees local macro such; sees contents after evaluation. so, seeing pivots entirely on nuances in presented display . note further while can use display format in defining contents of local macro, ends sto...

python - How to run two django apps on same dev machine -

i'm trying run 2 separate django apps need communicate each other using restfull api. in real life there 2 separate machines during development i'm running 2 instances on different ports. trying anyway ... one app running on 127.0.0.1:8000 , , other on 127.0.0.1:9000 . i've tried running both on localhost or 0.0.0.0 , other combinations keep getting these weird errors. 407 client error: proxy authorization required or 500 server error: inkapi error which far find apache error, or 403 forbidden what correct way test 2 apps on same machine ? there's no true one. try using nginx (althought works apache well, using appropiate syntax - should care general idea). define 2 fake domains domain1.dev , domain2.dev, , build appropiate entries: server { listen 80; server_name domain1.dev; location / { proxy_pass http://127.0.0.1:8000/ } } server { listen 80; server_name domain2.dev; location / { proxy_pass htt...

javascript - Reflux stores not listening to actions -

edit: i feel silly now. the problem wasn't requiring store anywhere in code, never being created. my refluxjs store not calling callback when call action it's listening to. here relevant code: actions: module.exports = require("reflux").createactions([ "createuser" ]); store: var useractions = require("../actions/user-actions"); module.exports = require("reflux").createstore({ listenables: useractions, oncreateuser: function() { console.log("oncreateuser called", arguments); } }); component fires action: var react = require("react"), useractions = require("../../actions/user-actions"); var login = react.createclass({ getinitialstate: function() { return { name: "" }; }, updatename: function(event) { this.setstate({ name: event.target.value }); }, // action gets called here...

web services - NetSuite SSO only allows map to Admin? Can I switch to a different role? -

i have managed mapsso / ssologin working expected, except can not seem use role other admin. there way switch role logged in or mapped when using sso or have admin role? inbound sso can used role, key item first mapping in account must administrator. once have mapping administrator can set additional mappings other users/roles. i'm unsure whether can map twice same user (once admin, once sales person example).

java - How to add import-packages from a specific bundle version in OSGi -

my project has 2 osgi bundles (a , b) need use different versions of javax.activation — requires version 1.1.0, while b requires 1.1.1. by default in aem 5.6.1, there bundle installed exports version 1.1.1, bundle using. in order make use 1.1.0 instaed, used boot delegation javax.activation jre 7 system bundle 1.1.0. setting using sling.properties file in aem 5.6.1. if give version javax.activation greater 1.1.1 in sling.properties file, both , b using system version (even though version of import-packages specified in manifest.mf file); if give version less 1.1.1, both bundles use version provided aem. how can configure bundles use different versions of javax.activation bundle bundle b? if want use 1.1.0 version in bundle a, should specify in a's manifest file: import-package: javax.activation;version="[1.1.0,1.1.0]" for bundle b manifest be: import-package: javax.activation;version="[1.1.1,1.1.1]"

php - Return a variable from a function to a view -

i newbie in laravel 4 , want return, when pressing button, value controller view. my form view: {{ form::submit('save', array('class' => 'btn btn-small btn-info iframe')) }} <?php echo $test; ?> my controller: <?php class testcontroller extends basecontroller { /** * start scrapping script. */ public function posttest() { $scrap = 'it works!'; return view::make ( 'admin/test/index' )->with('test', $test); } } my routes: route::post('test', 'testcontroller@posttest'); however, get: undefined variable: test(view: c:\xampp\htdocs\laravel_project\lara\app\views\admin\test\index.blade.php) any recommendations doing wrong? i appreciate answer! update i changed controller that: public function getindex() { // show page return view::make ( 'admin/test/index' ); } public function...

c# - How to achieve object scoped singletons in the Unity Container? -

assume have following class structure: public class outer { [dependency] public func<inner> innerfactory { get; set; } } public class inner { } in autofac can done in following way (and describes behaviour looking for; ignore fact stupid contrived example): [testmethod] public void autofacmakesthiseasy() { var builder = new containerbuilder(); builder.registertype<outer>().propertiesautowired(); builder.registertype<inner>().instanceperowned<outer>(); var container = builder.build(); var outer1 = container.resolve<owned<outer>>().value; var inner1 = outer1.innerfactory(); var inner2 = outer1.innerfactory(); var outer2 = container.resolve<owned<outer>>().value; var inner3 = outer2.innerfactory(); var inner4 = outer2.innerfactory(); assert.arenotsame(outer1, outer2, "outer1 == outer2"); assert.aresame(inner1, inner2, "inner1 != inner2"); assert...

javascript - Remove Item from Firebase -

i'm trying understand how remove item firebase. i've set function ( createprovider ) create item , can't figure out how go removing item. html <form role="form" name="createproviderform"> <input type="text" ng-model="title"> <button type="submit" ng-click="createprovider()">submit</button> </form> <div ng-repeat="provider in providers"> <h3>{{ provider.title }}</h3> <button type="button" ng-click="removeprovider()">remove</button> </div> </div> js var rootref = new firebase(fburl); var providersref = rootref.child('providers'); $scope.newprovider = {}; $scope.providers = []; providersref.on('child_added', function(snapshot) { $timeout(function() { var snapshotval = snapshot.val(); console.log(snapshotval); $scope.providers.push({ title: snapshotva...

java - How to run SQL script using hibernate -

i have requirement load , run sql-script (reportdata_pr.sql) create procedures on start-up , run procedures. we using spring 4.0.2.release , hibernate 4.3.5.final development. is possible run script file using hibernate. if yes how that. if not there other work around achieve goal. thanks you can run script using nativequery: e.g. entitymanager manager = getentitymanager(); query q = manager.createnativequery("begin"+sqlscript+"end;"); q.executeupdate(); see if helps

objective c - no visible @interface for NSMutable Array declares selector 'addStock' -

i cannot figure out why addstock method not working nsmutablearray object "giuport" . have connected class files. how make interface visible / correct error comes each of times try using addstock method? the following snippet main.m file rendering error is: nsmutablearray *giuport = [[nsmutablearray alloc]init]; [giuport addstock:apple]; [giuport addstock:lvs]; [giuport addstock:verizon]; the class .h file in declare nsmutablearray, etc: @interface bnrportfolio : nsobject { nsmutablearray *_stocks; } @property (nonatomic, copy) nsarray *stocks; @property (nonatomic) float valueofport; //instance methods -(void)addstock:(bnrstockholding *)s; -(float)valueofport; @end the class .m file in implement nsmutablearray, etc: @implementation bnrportfolio // array set stuff -(void)setstocks:(nsarray *)s { _stocks = [s mutablecopy]; } -(nsarray *)stocks { return [_stocks copy]; } // instance methods -(void)addstock:(bnrstockholding *)s ...

swing - Java Graphics and Bordering Problems in JScrollPane -

Image
i have found customscrollbaruiexample , , trying change own (with attribution , of course, legal). have run problem. what trying achieve put border around not jscrollpane itself, moveable block if understand meen. i have put modified source code below, , have highlighted problem. package com.finn.chess; import java.awt.*; import java.awt.image.bufferedimage; import javax.swing.*; import javax.swing.plaf.metal.metalscrollbarui; /** @see https://stackoverflow.com/a/12270067/230513 */ public class customscrollbaruiexample { public static void main(string[] args) { jscrollpane before = makeexamplepane(); jscrollpane after = makeexamplepane(); after.setverticalscrollbarpolicy(jscrollpane.vertical_scrollbar_always); jscrollbar sb = after.getverticalscrollbar(); sb.setui(new myscrollbarui()); jframe f = new jframe(); f.setdefaultcloseoperation(jframe.exit_on_close); f.setlayout(new gridlayout(0,1)); f.add(before); f.add(after); f.pack(...

What are the output comment and hide comment in jsp? -

hiii came across these terms output comment , hide comment in jsp. know differences between them. in advance. output comment: a comment sent client in viewable page source(it appear in output). <!-- output comment --> hidden comment: a comments documents jsp page not sent client(it not appear in output ). <%-- hidden comment --%>

unit testing - How to write nunit test for ASP.NET Identity in Web Forms? -

i've written (single-tier) asp.net web forms (please note not mvc application) application uses identity model authentication. vs solution consists of web forms project , unit test project. i've added nunit packages unit test project via nuget. i've been trying find example unit tests login function i've failed so. please point me in correct direction giving me sample/tutorial or providing me guidance on doing so? p.s. - i'm not familiar writing unit tests. update 1 meant i'm not familiar writing them in context (using nunit , identity on single tier web forms application). familiar concept , have written few in past java. sorry misunderstanding. update 2 i've managed write test method test log in functionality. following method i'm attempting test: public bool loginasuser(string username, string password) { bool issuccessful = false; // validate user password var manager = context.getowincontext().getusermanager<applicat...

close pop-up - chrome extensions -

im trying create quite simple chrome extention, close pop-up after pop-up loaded, , title. reason the title keeps returnen blank. this came with. { "name": "reportcloser", "version": "0.1", "permissions": [ "tabs","<all_urls>" ], "browser_action": { "default_icon": "icon.png" }, "content_scripts": [ { "matches": [ "http://*/*", "https://*/*" ], "run_at": "document_end" , "js": ["script.js"] // pay attention line } ], "manifest_version":2 } script.js var x = document.title; var title = "customtitle"; if(x==title){ close(); } else{ } i tried move run_at: document_end before content script, problem still there. any...

Calculate percentage and total after create categories mysql -

i've query select trage, case trage when '<18' sum(case when age <18 1 else 0 end) when '18-24' sum(case when age >= 18 , age <= 24 1 else 0 end) when '25-34' sum(case when age >= 25 , age <= 34 1 else 0 end) when '35-44' sum(case when age >= 35 , age <= 44 1 else 0 end) when '45-54' sum(case when age >= 45 , age <= 54 1 else 0 end) when '>=55' sum(case when age >= 55 1 else 0 end) end total ( select t_personne.pers_date_naissance, t_personne.pers_date_inscription, timestampdiff(year, t_personne.pers_date_naissance, t_personne.pers_date_inscription) - case when month(t_personne.pers_date_naissance) > month(t_personne.pers_date_inscription) or (month(t_personne.pers_date_naissance) = month(t_personne.pers_date_inscription) , day(t_personne.pers_date_na...

Getting the correct query in Mongodb -

i'm trying simple query subfield out of collection. far keep getting entire field should correct print out subfield i'm looking for? i'm trying list titles (only) of movies rank of less 9.2 , @ least 5 votes, print titles in alphabetical order. this query far incorrect , returns whole object. how can return rank , votes of jungle book? thank in advance. db.collections.find({"title": {$exists:true}}, {"_id":0, "rank":{$lt : 9.2}}) { "_id" : objectid("10"), "rank" : 6, "votes" : 8.8, "title" : "jungle book" } { "_id" : objectid("11"), "rank" : 8, "votes" : 8.7, "title" : "spawn" } you need have filter/query in first parameter. second parameter set of booleans properties should return. db.ratings.find({title: {$exists:true}, rank:{$lt : 9.2}, votes: {$gte : 5 } }, {_id:0, title:1}).sort({title:1}) t...

caching - Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource -

i have upgraded tomcat version 7.0.52 8.0.14. i getting lots of static image files: org.apache.catalina.webresources.cache.getresource unable add resource @ [/base/1325/wa6144-150x112.jpg] cache because there insufficient free space available after evicting expired cache entries - consider increasing maximum size of cache i haven't specified particular resource settings, , didn't 7.0.52. i have found mention of happening @ startup in bug report supposedly fixed. me happening not @ startup when resource requested. anybody else having issue? trying @ least disable cache, cannot find example of how specify not use cache. attributes have gone context in tomcat version 8. have tried adding resource cannot config right. <resource name="file" cachingallowed="false" classname="org.apache.catalina.webresources.fileresourceset" /> thanks. in $catalina_base/conf/context.xml add block below before ...

javascript - Ember error - "Call stack size exceeded range error" when loading a route -

i building app in ember uses rails backend. i error whenever try navigating consultants show route, ember throws "call stack size exceeded range error". have built out other parts of app using same kind of methods below, reason navigating show route throw kind of error. i'm not sure problem or what's going on. thanks. this error logged in chrome console. error while loading route: consultant.show maximum call stack size exceeded rangeerror: maximum call stack size exceeded @ apply (http://localhost:3000/assets/ember.js?body=1:7980:27) @ superwrapper [as rendertemplate] (http://localhost:3000/assets/ember.js?body=1:7567:15) @ embermaven.consultantshowroute.ember.route.extend.rendertemplate (http://localhost:3000/assets/emberadmin/routes/consultants_route.js?body=1:24:10) @ apply (http://localhost:3000/assets/ember.js?body=1:7980:27) @ superwrapper [as rendertemplate] (http://localhost:3000/assets/ember.js?body=1:7567:15) @ embermaven.consultantshowroute.emb...

api - Rails - How to validate the state of associated models as a state of the parent model -

i'm building api using rails backend of ember webapp. have model named 'palette' has many colors associated it. due way ember app built, deleting colors , replacing them new objects whenever palette updated. challenge if new state of colors no longer valid, have deleted old colors , cannot return original state. solution have far create transaction in our update method of palette controller throw exception if of new color creations fails or palette fails. while solution works, feels bit clunky. there more elegant solution available? class palettescontroller < basecontroller def update activerecord::base.transaction begin palette = palette.find params[:id] palette.destroy_colors params[:palette][:colors].each |color| color.create! palette: palette, name: color[:name], cmyk: color[:cmyk], color_type: color[:color_type] end return render jso...

flex - ASDoc generation error -

Image
i following instructions here exporting asdocs . image below tutorial , have set same. when run configuration error below loading configuration file /applications/adobe flash builder 4.6/sdks/4.6.0 (air 14)/frameworks/flex-config.xml /users/steam/documents/development/air/mediawindowtest/src/mediawindow.mxml: error: unable locate specified base class 'spark.components.windowedapplication' component class 'mediawindow'. so can't find base class spark.components.windowedapplication can find "flex-config.xml" in sdk folder. confusing. flex sdk copy of 4.6 on overlaid air sdk. works fine build project – confused. do need add variable point flex sdk using (and why doesn't pick project)? you need add additional arguments follows: -source-path src -doc-sources src -main-title "asdoc documentation" -external-library-path+=c:\repository_mvn3\com\adobe\as3corelib\0.93\as3corelib-0.93.swc -external-library-path+=c:\repos...

c# - asp.net mvc controller calculating incorrect values -

this bugging me right now. have following controller action method: public partialviewresult scrollemployeecompyear(int employeeid, string direction, int latestyearcurrentlydisplayed) { list<employeecompensationyear> fouryearslist = new list<employeecompensationyear>(); employee employee = _db.employees.find(employeeid); employeecompensationyear compyear; if (direction == "right") { int latestyeardisplayedminusthree = latestyearcurrentlydisplayed - 3; (int = 0; < 4; i++) { if ((compyear = employee.compensationyear.find(m => m.year == --latestyeardisplayedminusthree)) != null) { fouryearslist.add(compyear); } else { break; } } fouryearslist.reverse(); } else if (direction == "left") { (int = 0; < 4; i++) { if ((compyear = employee.compensa...

How to use javascript for html form validation to valid number only? -

how validate input form using javascript stretch user don't insert value input form element. object: 1, want user input number value if have character or special character show errors 2, , if user let input element value empty alert user below javascript code <script type="text/javascript"> $(document).ready(function(){ $('.quantity, .unitprice').on('keyup', function(e){ var errors = array[]; var quantity = document.getelementsbyclassname('.quantity').val(); var unitprice = document.getelementsbyclassname('.unitprice').val(); if(quantity== ""){ errors = "quantity empty"; } if(unitprice== ""){ errors = "unitprice empty"; }eles{ if(errors){ forearch(errors errors){ alert(errors); } }else{ calculate(); ...

javascript - How to hide page numbers when records are less -

i using datatables pagination.when there more 5 records want show next,previous buttons , show number of pages drop down. for using this if($("#example").find("tr:not(.ui-widget-header)").length<=10){ console.log('hi'); $('#example_length').addclass('hide'); $('#example_paginate').addclass('hide'); } } enter link description here lets there 5 records there no need show next or previous buttons neither number of records per page. so hiding , works well.but problem if there 12 records on 1st page shows 10 records , next,previuos buttons visible , when click next button shows 2 records , here buttons disappear. now user can not see 1-10 records there no button that so how overcome issue. how can disable buttons if total number of records less 10 here fiddle in datatables api there page function returns current page number. change if statement check...

nginx - MPEG-DASH picky in fragmented mp4 sampleOffsets and sampleSizes? -

hey stackoverflow fellows. encountered problem mpeg-dash players not wanting play dash content. basically, have mp4 source in i'm feeding in 2 channels, 1 through rtmp , other in rtsp. connect both channels , create mpeg-dash content out of it. output dash both same, same manifest content, same number of fragments. when playing industry's dash player (i.e. gpac osmo4, digital primates, castlabs dashas), dash content generated rtmp source working perfectly, however, dash content generated rtsp source problematic (i.e. lot of video freezes, a/v out of sync, etc...). when comparing dash fragments generated rtmp against rtsp, difference samplingoffsets , samplingsizes in trun box. have same samplecounts. same fragments used in mss , mss player played both okay regardless of difference in samplingoffsets , samplingsize. does know if mpeg dash has requirement regards size of each samples in trun , offsets? or cause problem? i welcome opinions, advice. shoot it... bas...

How to force minimum charge in Woocommerce, yet not restrict checkout? -

i'm wondering how force minimum charge in woocommerce, e-commerce system wordpress. if minimum $100, , items in cart total $23, person can checkout, paying $100. needs reflect not in checkout, order invoice , other relevant fields. i'm okay php, i'm not familiar woocommerce system. logic-wise, predict can mod total calculator... if $total >= 100 { proceed regularly } else { $total = 100 }. or maybe dynamically add item cart based on difference between minimum charge , current cart total. i'm concerned may mess things not putting in enough consideration how entire site may need modding because total amount shows in many places. note: not talking not letting people checkout if don't meet minimum order amount. there plugins or can use javascript disable checkout button. i answering own question: to force minimum charge, have tap couple of woocommerce parts. first ability add additional line (like surcharge) total. second subtotal amount. in them...

javascript - Pebble.js ajax request with post data. No data in request -

i started fiddeling pebble.js prototype. have make connection server , send user data pebble (login information) server handshake , send data server pebble. using pebble.js because easy prototyping. now using ajax library ( http://developer.getpebble.com/docs/pebblejs/#ajax ) setup connection. have following code: ajax( { url: url, method: 'post', type: 'json', data: { auth : 'test' } }, function(data) { // success! console.log(json.stringify(data)); }, function(error) { // failure! console.log('no response'); } ); in php on server complete header information apache_request_headers(); , send pebble echo json_encode(apache_request_headers()); this results in output of console.log(json.stringify(data)) {"host":"192.168.0.113","content-type":"application/json","accept":"*/*","connection":"keep-alive","cookie":"v2ci_session=55mmp...

c# - First combobox item missing after combobox filled with datatable -

i have combobox on form , datatable . combobox filled row values fro datatable . before add combobox item called (new) first option of combobox in case user add new item. but when combobox filled, (new) not show reason. string query = "select id,name,text apsissms order id desc"; oledbdataadapter da = new oledbdataadapter(query, conn); conn.open(); da.fill(dtsmsmessages); combosmsmessages.items.add(new comboboxitem() { text = "(new)", value = "-1" }); if (dtsmsmessages.rows != null && dtsmsmessages.rows.count > 0) { combosmsmessages.items.clear(); (int = 0; < dtsmsmessages.rows.count; i++) { comboboxitem item = new comboboxitem() { text = dtsmsmessages.rows[i]["name"].tostring(), value = dtsmsmessages.rows[i]["id"].tostring() }; combosmsmessages.items.add(item); } } combosmsmessages.selectedindex = 0; combosmsmessages.items....

c# - Wiring up fluentvalidation with Nancy and Ninject -

i using nancy ninject ioc. fine. need add fluentvalidation. how go wiring nancy use fluentvalidation via ninject? i see there's nuget package ninject.fluent.validation can't find documentation or example on how use it. the demo project on nancyfx website uses tinyioc it's not useful me. update : have tried do: var createrequest = this.bindandvalidate<createrequest>(); if (!modelvalidationresult.isvalid) { return response.asjson(modelvalidationresult, httpstatuscode.badrequest); } the model valid (even if there should errors reported createconsumerrequestvalidator ). this have added in ninject bootstrapper: bind<imodelvalidatorfactory>().to<fluentvalidationvalidatorfactory>().insingletonscope(); assemblyscanner.findvalidatorsinassemblycontaining<createrequestvalidator>() .foreach(match => bind(match.interfacetype).to(match.validatortype)); the imodelvalidatorfactory wired automatically nancy v0.12 (see here c...

css3 - CSS `will-change` - how to use it, how it works -

i found css will-change w3.org docs , mdn docs property (which works in chrome , partiali supported firefox , opera) i'm not sure how works. know more mysterious thing? i have read allows browser prepare calculation on element in future. don't want misunderstand it. have few questions. should add property element class or hover state? .my-class{ will-change: 'opacity, transform' } .my-class:hover{ opacity: 0.5 } .my-class:active{ transform: rotate(5deg); } or .my-class{ ... } .my-class:hover{ will-change: 'opacity' opacity: 0.5 } .my-class:active{ will-change: 'transform' transform: rotate(5deg); } how can increase browser performance? theoretically, when css loaded, browser "knows" happen each element, doesn't it? if can add example illustrating how use efficiently, grateful :) i won't copy paste entire article here here's tl;dr version: specifying want change allow...

mysql - How to Encrypt data after validation in Ruby on Rails? -

i using devise authentication, register. want save emailid in mysql in encrypted format. use gem 'aescrypt'. my controller: def create @dashboard_user = dashboarduser.new(dashboard_user_params) @dashboard_user.created_by=current_dashboard_user.username @dashboard_user.company_id=current_dashboard_user.company_id active_ind = "" email = @dashboard_user.email if params["active"] == nil active_ind = "0" else active_ind = "1" end @dashboard_user.active = active_ind @dashboard_user.email= aescrypt.encrypt(email, "password") respond_to |format| if @dashboard_user.save format.html { flash[:notice] = 'user created.' , redirect_to action: "index"} else @dashboard_user.email = email format.html { render :new } end end end when try save user, throws email invalid. removed validation email in model. though ...

c - Error in accessing struct in some other file using extern -

i'm new c. reading extern .i used built-in data dypes , worked fine.when used structs, gave following error. doing wrong? bar.c struct myx { int x; } x; foo.c extern struct myx x; int main() { x.x=80; return 0; } gcc -o barfoo foo.c bar.c error: invalid use of undefined type 'struct myx' x.x=80; ^ because gcc -o barfoo foo.c bar.c (which should gcc -wall -wextra -g foo.c bar.c -o barfoo ; should enable warnings , debugging info when compiling code) compiling 2 compilation units ( foo.c , bar.c ) linking object files together. every compilation unit (or translation unit ) "self-sufficient" regarding c declarations; should declare every -non-predefined- type (e.g. struct ) using in translation unit, in common header file. so should have struct myx { int x; }; and extern struct myx x; in both foo.c & bar.c . avoid copy-pasting, want put in myheader.h , use #include "myheader.h" @ start of bot...

Moving folders with the same name to new directory Linux, Ubuntu -

i have folder 100,000 sub-folders. because of size cannot open folder. looking shell script me move or split folders. current = folder research : 100,000 sub-folders. (sorted a, b, c, d) needed = new folder folders starting name a-science. should moved new folder ascience. folders starting b-science.. should move new folder bscience i found script below. don't know how make work. find /home/spenx/src -name "a1a2*txt" | xargs -n 1 dirname | xargs -i list mv list /home/spenx/dst/ find ~ -type d -name "*99966*" -print i had @ command supplied see did. here's each command (correct me if i'm wrong) | = pipes output of command left of pipe input of command on right find /home/spenx/src -name "a1a2*txt" = finds files within given directory match between "" , pipes output xargs -n 1 dirname = takes in piped files outputted find command , gets directory name of each file , pipes output xargs - list mv list /home/spenx...

windows - Terms matching in two files.txt, batch script -

first of, read /help , thread 1 : comparing 2 files in batch script but chinese me. i'm experienced in c/c++ programming (linux/unix) , i'm getting stuck batch script on ma dear windows. here problem : have 2 files (file1.txt (or logok.txt in below source code) , file2.txt) looks like file1.txt : dir1;dir2;dir3;dir4;... file2.txt : dir7;dir3;dir4;dir1;... (files aren't ordered name asc or whatever have ';' separator) what want .bat compare file1.txt file2.txt , when match (here dir 1, 3 , 4) echo [folderx] >> file3.txt so i'll file3.txt : dir1;dir2;dir3 here first part (wich works well, actually) of script check if directories empty or not, if can : (there debugs lines too) @echo off setlocal disabledelayedexpansion if exist logko.txt del /s logko.txt if exist logok.txt del /s logok.txt set "folder=." if not defined folder set "folder=%cd%" /d %%a in ("%folder%\*") ( set "size=0" /...

mouseevent - JAVA - Get mouse location when mouse is clicked -

i need absolute location of mouse after click on screen. i've searched on web solution have found uses method: mouseinfo.getpointerinfo().getlocation() which gets position independently click. otherwise, have use eventlistener check out when mouse clicked, problem listeners related component, while need absolute location. how can solve this? this os dependent feature. far understand question, don't have gui or don't want add listener gui components. jvm receive clicks components related it. here have write native code hook events want on own, or should use library jnativehook same thing , don't need write code linux, mac os x , windows.

css - PX-REM mixin only working with font-sizing -

so using mixin generate px value fallbacks when using rem unit: @function fix8_unit_to_px($val) { @if unitless($val) { @if $val == 0 { @return $val } @else { @return $val * 10+px }; } @else { @return $val}; } @function fix8_unit_to_rem($val) { @if unitless($val) { @if $val == 0 { @return $val } @else { @return $val+rem }; } @else { @return $val}; } @mixin rem($prop, $val...) { $n: length($val); $i: 1; $px-list: (); $rem-list: (); @while $i <= $n { $px-list: append($px-list, fix8_unit_to_px(nth($val, $i))); $rem-list: append($rem-list, fix8_unit_to_rem(nth($val, $i))); $i: $i + 1; } @if $px-list == $rem-list { /* 8 */ #{$prop}: $px-list; /* 9 */ } @else { #{$prop}: $px-list; /* 9 */ #{$prop}: $rem-list; /* 9 */ } } this works if use on font-sizing i.e. @include rem(font-si...

vb.net - How to work out the X and Y coordinates of a moved pendulum -

Image
i trying make pendulum simulation in vb.net, move string of pendulum using: e.graphics.drawline(pens.black, 270, 0, 270, lengthofstring) and changing end coordinates rotate line around point (270, 0). end making isosceles triangle. know 2 equal lengths (lengthofstring). how work out lower (not (270, 0) x , y coordinate of rotated line. i have tried work out with: pythagoras (to work out lower line's length) trig, after splitting triangle in half if starting angle let φ , known then: sinφ = x / lengthofstring cosφ = y / lengthofstring the end points: (270 - x, 0 + y), (270 + x, 0 + y)

c# - Changing the color of a custom control -

i trying set background color of custom button. build button html overriding render method. expose attributes through customer overridden attribute methods , set capabilities. allows change parts of custom button after compiling. i want change color of buttons div or table (i dont care which). how can this? the button has table - how can programmatically grab table given know name ;buttontable.findcontrol not working, 'not set instance of object' error. panel buttonpnl = new panel(); //declare , init here in case need changing background color @ code compile , not run time system.web.ui.webcontrols.image logoimg; system.web.ui.webcontrols.image errorimg; textbox maintexttb; label subtextlbl; protected override void createchildcontrols() { controls.clear(); //init controls //buttonpnl.width = unit.pixel(200); //buttonpnl.height = unit.pixel(150); buttonpnl.id = "buttonpnl"; logoimg...

Removing sections from a string in Swift -

all, if have string : le7 3jj, 2, bellyache road, sheepshead how can remove characters , first comma, comes out : 2, bellyache road, sheepshead do ranges in swift ? want write extension of string : extension string { func removestringtofirstcomma(input:string) -> string { return } } you can this: let str = "le7 3jj, 2, bellyache road, sheepshead" if let firstcomma = str.rangeofstring(",") { let res = str.substringfromindex(advance(firstcomma.startindex, 2)) println(res) } first, find location of first comma in string. if there, advance index 2 skip on comma , adjacent space character , , take substring starts @ index. to adapt snippet function, return original string else branch of conditional (not shown above).

ElasticSearch matching no more than query terms -

for search "w1 w2 w3" want retrieve documents contain of query terms no more. documents containing "w1", "w2", "w3", "w1 w2", "w1 w3", "w2 w3" or "w1 w2 w3" ok, not document containing "w1 w2 w3 w4". did programming elasticsearch => idea please? use query string query: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html { "query_string": { "query": "(w1 or w2 or w3 or (w1 , w2) or (w1 , w3) or (w2 , w3) or (w1 , w2 , w3))" } } or { "query_string": { "query": "(w1 or w2 or w3) , not w4)" } } or using bool query: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html { "bool": { "should": { "match": "w1 w2 w3" }, ...

ios - MapView doesn't work anymore if I add a GestureRecognizer -

i'm trying add pin @ map when user longpress (with uilongpressgesturerecognizer), doesn't work. however, bigger problem is: map isn't displayed anymore. why map has disappeared? you find project-file here ---------------------------viewcontroller.swift-------------------------------- { import uikit import mapkit class viewcontroller: uiviewcontroller, mkmapviewdelegate { @iboutlet var themapview: mkmapview! @iboutlet var thetextfield: uitextfield! @iboutlet var thelabel: uilabel! @ibaction func thebutton(sender: uibutton) { thelabel.text = "swift-app schreibt \(thetextfield.text)" thetextfield.resignfirstresponder() } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. // position var latitude:cllocationdegrees = 48.399193 var longitude:cllocationdegrees = 9.993341 // zoomfaktor var latdelta:cllocationdegrees = 0.01 var longdelta:cllocationdegrees = 0.01 ...

ruby on rails - How do I call my namespaced class from the lib directory -

i have class that's 3 levels deep in lib directory i'm trying call uninitialized constant error. class , directory structure looks this: file name: lib/my_module/my_second_module/my_third_module/my_class.rb module my_module module my_second_module module my_third_module class my_class def self.something something... end end end end end i'm trying call class using rails console returns 'uninitialized constant my_module'. run command , error: mymodule::mysecondmodule::mythirdmodule::myclass.something also i've include following in config/application.rb config.autoload_paths += dir["#{config.root}/lib/my_module/**/"] try ::mymodule::mysecondmodule::mythirdmodule::myclass.something

python - function to list earthquakes -

my function designed take data website , collect latitude, longitude, depth, , magnitude of earthquake. second function 'colorcode' supposed take depth of earthquake , return color value it. stuck. tried make data float use if statement , compare int still says cannot converted float. thoughts? (excuse me if post code in improper format) import urllib #parseearthquake: int --> list-of-float def parseearthquakedata(numberofearthquakes): urlonweb = urllib.urlopen("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv") lines = urlonweb.readlines() numberoflines = len(lines) numberoftimes = 0 index = 1 myaccumalator = [] numberoftimes in range(numberofearthquakes): while index < (numberofearthquakes + 1): line = lines[index] data = line.split(",") latitude = float(data[1]) longitude = float(data[2]) depth = float(data[3]) ma...

audio - AVAudioRecorder not recording in iOS -

i have made app(dictation) having audio functionalities such recording, overwriting & playing audio files. have used avaudiosession recording & playback , have locally saved audio files(.m4a) , send them server. make recording works in background, have added uibackgroundmodes in plist file , worked fine. recording after pause failed on conditions. steps reproduce : 1) start audio recording on 00:00 minute , pause recording on 02:00 minutes. total file size approximately 0.45 mb , has been stored in app documents(sandbox). 2) after pause, have made device sleep mode tapping power button , come app same screen. continued recording pause , recording continues file did not writing local file , file size remains @ 0.45 mb. if remove uibackgroundmodes plist, above steps worked fine recording audio in background wouldn't working since app not have uibackgroundmodes audio. how continue audio recording after pause & device sleep mode? much appreciate support. tha...

selenium - Getting Could not load Extension from error when launching Chrome using Webdriver -

i trying launch chrome using below code. webdriver driver; system.setproperty("webdriver.chrome.driver", "properties/chromedriver.exe"); driver = new chromedriver(); driver.get("www.google.com"); when program runs, chrome opened , getting below error after that could not load extension c:\users\username\appdata\local\temp\scoped_dir4560_5259\internal. invalid value permission[1]. please change below line in code : driver.get(" http://www.google.com "); use http url per above. also please download latest chrome driver below : http://chromedriver.storage.googleapis.com/index.html?path=2.10/ replace above downloaded file properties folder , run