Posts

Showing posts from August, 2010

lambda - Filter Java Stream to 1 and only 1 element -

i trying use java 8 stream s find elements in linkedlist . want guarantee, however, there 1 , 1 match filter criteria. take code: public static void main(string[] args) { linkedlist<user> users = new linkedlist<>(); users.add(new user(1, "user1")); users.add(new user(2, "user2")); users.add(new user(3, "user3")); user match = users.stream().filter((user) -> user.getid() == 1).findany().get(); system.out.println(match.tostring()); } static class user { @override public string tostring() { return id + " - " + username; } int id; string username; public user() { } public user(int id, string username) { this.id = id; this.username = username; } public void setusername(string username) { this.username = username; } public void setid(int id) { this.id = id; } public string getusername() { retur...

ruby on rails 4 - Devise change email does not update email -

i'm trying allow users change email addresses devise uses unique username. though update gives no errors, no change made email address user in database. here relevant portions of code: form: <%= f.fields_for :user_account, @user.user_account |user_account| %> <p>edit email address account: <%= @user.user_account.email %></p> <div class="field"> <%= user_account.label :new_email %><br /> <%= user_account.text_field :email, autocomplete: "off", value: nil %> </div> <div class="field"> <%= user_account.label :password %> <i>(please confirm password associated account)</i><br /> <%= user_account.password_field :current_password, autocomplete: "off" %> </div> <%= hidden_field_tag 'form', 'email' %> <div class="actions"> <%= user_account.submit "edit" %> </div> contr...

python - How to make a countdown timer that runs in the background, which terminates the program when it runs out? -

i making wants millionare game in python using graphics. want user 45 seconds per question answer it. however, whenever put timer in code waits 45 seconds first, then lets user answer, instead of running in background , letting user answer @ same time. using threading module run multiple threads @ once you use python threading module make 2 things happen @ once, thereby allowing user answer while timer ticks down. some example code utilizing this: from threading import thread time import sleep import sys def timer(): in range(45): sleep(1) #waits 45 seconds sys.exit() #stops program after timer runs out, have print or keep user attempting answer longer def question(): answer = input("foo?") t1 = thread(target=timer) t2 = thread(target=question) t1.start() #calls first function t2.start() #calls second function run @ same time it's not perfect, code should start 2 different threads, 1 asking question , 1 timing out 45 secon...

r - How to create a table from a dataframe -

the following dataframe have col1<-c(1960,1960,1965,1986,1960 ,1969,1960,1993,1983,1924, 1960,1993,1960,1972 ,1960,1969) col2<-c ("a", "c","a","b", "a", "c", "b","a", "b","a", "b", "a", "c","c","a","a" ) mydata<-data.frame(col1,col2) i want create two-way table calculate proportion each category (a, b , c) respectively before 1970 , after 1970 . the desired output should be: year b c before 1970 0.545 0.181 0.272 after 1970 0.4 0.4 0.2 any suggestion appreciated! we can transform dataset create column after 1970 , before 1970 values. can done first creating logical vector ( col1 <= 1970 ), adding 1 true becomes 2 , false 1. use numeric index change values after 1970 , before 1970 . then, frequen...

Handling exceptions within if statements in Python -

is there way deal exceptions within if statements, other putting try , except bracket around whole lot, or test exception on each line in advance? for example, had simplified code: if a[0] == "a": return("foo") elif a[1] == "b": return("bar") elif a[5] == "d": return("bar2") elif a[2] == "c": return("bar3") else: return("baz") if a word_of_six_characters_or_more work fine. if shorter word raises exception on line elif a[5] == "d" . possible test exceptions in advance (e.g. changing elif a[5] == "d" elif len(a) >5 , a[5] =="d" , relies on first part being false , second never executed). question is, there other way of causing exceptions treated false , proceed next elif statement rather throwing exception - or similarly, include try except clauses within elif line? (obviously, possible there no way, , getting con...

sublimetext3 - In Sublime text 3 how do I default a certain file to a specific type -

this question has answer here: sublime text different syntax files under specific subdirectory 1 answer i'm working fastlane.tools , want fastfile open ruby syntax. i'm not sure change this. click on bottom right language selector, or go view > syntax go open current extension as... , pick desired language. this apply files of extension.

Matlab inverse of large matrix -

this equation trying solve: h = (x'*x)^-1*x'*y where x matrix , y vector ((x'x)^-1 inverse of x-transpose times x). have coded in matlab as: h = (x'*x)\x'*y which believe correct. problem x around 10000x10000, , trying calculate inverse crashing matlab on powerful computer can find (16 cores, 24gb ram). there way split up, or library designed doing such large inversions? thank you. i generated random 10,000 10,000 matrix x , random 10,000 1 vector y. i broke computation step step. (code shown below) computed transpose , held in matrix k then computed matrix multiplying k x computed vector b multiplying k vector y lastly, used backslash operator on , b solve i didn't have problem computation. took while, breaking operations smallest groups possible helped prevent computer being overwhelmed. however, composition of matrix using (ie. sparse, decimals, etc.). x = randi(2000, [10000, 10000]); y = randi(2000, 10000, 1); k = x'; ...

jquery - How Can I run my script after validate,before POST in ASP.NET Web Forms? -

i want use webcontrols.validator (ex. requiredfieldvalidator) validation. can submit button twice , more. <asp:textbox id="textbox1" runat="server"></asp:textbox> <asp:requiredfieldvalidator id="reqfld1" runat="server"controltovalidate="textbox1"></asp:requiredfieldvalidator> <asp:button id="button1" runat="server" text="submit" /> $("form").on("submit", function(e){ if (waiting) return false; waiting = true; showmywattingdiv(); ) i tried code, if invalid i'm waiting too; try code below. key use client-side api asp.net validators. here using property page_isvalid available in page whenever have asp.net validators on page. <asp:textbox id="textbox1" runat="server"></asp:textbox> <asp:requiredfieldvalidator id="reqfld1" runat="server"controltovalidate="textbox1...

php - $response->getBody() is empty when testing Slim 3 routes with PHPUnit -

i use following method dispatch slim app's route in phpunit tests: protected function dispatch($path, $method='get', $data=array()) { // prepare mock environment $env = environment::mock(array( 'request_uri' => $path, 'request_method' => $method, )); // prepare request , response objects $uri = uri::createfromenvironment($env); $headers = headers::createfromenvironment($env); $cookies = []; $serverparams = $env->all(); $body = new requestbody(); // create request, , set params $req = new request($method, $uri, $headers, $cookies, $serverparams, $body); if (!empty($data)) $req = $req->withparsedbody($data); $res = new response(); $this->headers = $headers; $this->request = $req; $this->response = call_user_func_array($this->app, array($req, $res)); } for example: public function testgetproducts() { $this->dispatch('/products...

c# - Awaiting a TaskCompletionSource<T> that never returns a Task -

i trying write unit test around async pub/sub system. in unit test, create taskcompletionsource<int> , assign value within subscription callback. within subscription callback, unsubscribe publications. next time publish, want verify callback never got hit. [testmethod] [owner("johnathon sullinger")] [testcategory("domain")] [testcategory("domain - events")] public async task domainevents_subscription_stops_receiving_messages_after_unsubscribing() { // arrange string content = "domain test"; var completiontask = new taskcompletionsource<int>(); domainevents.subscribe<fakedomainevent>( (domainevent, subscription) => { // set completion source awaited task can fetch result. completiontask.trysetresult(1); subscription.unsubscribe(); return completiontask.task; }); // act // publish first message domainevents.publish(new f...

mysql - PHP Add more value to foreach for display group by vendor -

how add more value code display? ex : added 5 products cart different vendors. p1 vendor name test1 p2 , p3 vendor name test2 p4 vendor name test3 p5 vendor name test4 my code : function getvendors() { foreach($_session["products"] $product) { $org[$product["member_display_name"]][] = $product["p_name"]; } return (!empty($org)) ? $org : array(); } foreach (getvendors() $vendor => $prods) { echo "<li>vendor name : {$vendor} </li>"; echo "<li>" . implode("</li><li>",$prods) . "</li>"; } this code given output like: vendor name : test1 p1 vendor name : test2 p2 p3 vendor name : test3 p4 vendor name : test4 p5 this want i want add $product["member_payment"] display : vendor name : test1 p1 payment vendor : 000-111-111 vendor name : test2 p2 p3 payment vendor : 000-111-222 vendor name : test3 p4 payment vendor : 000-111-333 vendor ...

javascript - How to make a slider with jquery using bullets -

hello want know how make slider jquery, i'm quite new try best specific, want this: have slider 3 images "they on same space" , 3 bullets below images, first can't see images because have opacity: 0 if click first bullet see first image, bullet# 2 img# 2, bullet# 3 img# 3, want put <a> tag example <a href="#"class="avanzar1">avanzar</a> advance next image "it on right side" , left side last image saw, question how can that? need keep transition of them , how join bullets? because need use tag <a> <-- button "for me" or bullets, it's difficult , i'm trying it, welcome here html: <!doctype html> <html> <head> <title>slider</title> <meta charset="utf-8" /> <link rel="stylesheet" href="style.css"> <script src="js/jquery-2.1.4.min.js"></script> <script src="js/sli...

Gulp: Run code after asynchronous tasks have completed -

i have gulp task following mission: list of folders. count words in folder. report count each folder , grand total count. so far, have. gulp.task('count', function() { ['folder1','folder2',...].foreach(function(foldername) { gulp.src(['./'+foldername+'/**/*.md']).pipe(countwords(foldername)); }); }); after of folders' words have been counted, want call function reportgrandtotal . have spent hours trying figure out how this. problem gulp.src().pipe() chain runs asynchronously. in many of patterns have tried, reportgrandtotal ends running before of gulp.src().pipe() chains complete. how modify task that, once of gulp.src().pipe() chains have completed, can run reportgrandtotal , grand total? if i'm understanding question, can specify dependency reportgrandtotal, make sure tasks use callback or return stream or promise. gulp.task('reportgrandtotal', ['count'], function(){ // code } ...

xcode4 - Attempt to programmatically re-position UIImageView -

**updated question reflect addition of "init" in uiimageview alloc* * * have "imageview" variable, declared in ".h" class. forced in particular case programmatically move "imageview" 10 pixels , have experienced no luck. in looking @ current uiimageview ("imageview) position, determined x/y/width/height should (78,214,170,120). below code working with, works displays no uiimageview/uiimage: imageview = [[uiimageview alloc]init]; uiimage *image = [uiimage imagewithdata:[nsdata datawithcontentsofurl:[nsurl urlwithstring:img2string]]]; imageview.frame = cgrectmake(78,214,170,120); imageview.image = image; i'd appreciate help. you should initialize image view first imageview = [[uiimageview alloc] init]; like above.

string - Adding characters to str_replace in PHP -

i have php file thread ($tid) , post ($pid) ids defined , i'm looking use str_replace combine them , create desired output (below) &p= added: desired output: $tid&amp;p=$pid the closest i've got doing this: $tid=$t1; $pid=$p1; $tid=str_replace("$tid","$tid"."$pid",$tid); the result is: $tid$pid i may need use function (not sure if so?) in str_replace support &p= being added, trying add in quotes directly doesn't seem work resulting in database errors. edit #1: tried doing following based on comments far: $tid=""; $tid.="$t1"; $tid.="$p1"; $tid=$tid; that results in same previous example above: $tid$pid as add &p= database error: $tid.="&amp;p="; so question how add &p= edit #1 example above correctly? i'm attempting understand question little bit. have couple options alluded in comments above. could, instance (where '1',...

css3 - CSS Select div whose immediate sibling is NOT p -

Image
this question has answer here: select specific element before other element 5 answers i have situation: the transition on entering is, after 1sec delay, fade-in 100% opacity: transition: opacity 1s ease 1s; the transition on leaving is, within 1sec fade out 0% opacity: transition: opacity 1s; the .leaving element removed after 1second. after removed want position:static on .entering so in other words: "when .entering not followed .leaving, apply position:static" , "when .entering followed .leaving should position:absolute" i'm trying this .entering { position: absolute; } .entering:not(+ .leaving) { position: static; } however not working. ideas? let's example in simplified case, background colors. if .entering followed .leaving , it's background color should red. if .entering followed non- .leaving (or f...

Python Subtract integers in List to return a value -

i take large file in python 2.7: 123 456 gthgggth 223 567 fgrthsys 12933 4656832 gjwsoooskkssj ..... and want read in file line line, disregard third element, , subtract second element in each line first element. line 1 above return 333. i have tried far: def deletelast(list): newl = list.pop() return newl f = open(file_name, 'r') line = f.readline() while line: l = line.split() l2 = deletelast(l) l3 = [int(number) number in l2] length = l3[1]-l3[0] print length f.close() but, when try compiler says: valueerror: invalid literal int() base 10: 't' all appreciated. that because list.pop() returning "popped off" item, doesn't return list again. instead of deletelast function have written, better use slice this: l2 = line.split()[0:2] you going run problem later because while loop isn't advancing @ all. consider using loop instead.

Install apache2 on Ubuntu -

i upgrade apache2 v2.2 v2.4, follow instructions on site using command line: # apt-get install apache2 apache2.2-common apache2-mpm-prefork apache2-utils reading package lists... done building dependency tree reading state information... done **apache2 newest version.** apache2-utils newest version. might want run 'apt-get -f install' correct these: following packages have unmet dependencies. apache2-mpm-prefork : depends: apache2.2-bin (= 2.2.22-1ubuntu1.10) not going installed apache2.2-common : depends: apache2.2-bin (= 2.2.22-1ubuntu1.10) not going installed **e: unmet dependencies. try 'apt-get -f install' no packages (or specify solution).** it says installed, run: # service apache2 status apache2: unrecognized service then run command line: #apt-get -f install following packages installed: apache2-mpm-worker apache2.2-bin apache2.2-common suggested packages: apache2-doc apache2-suexec apache2-suexec-custom following new packages installed ap...

android - webview is not present in xml layout file but still getting its reference in class file -

protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); getwindow().requestfeature(window.feature_action_bar); getactionbar().hide(); setcontentview(r.layout.activity_main); webview = (webview) findviewbyid(r.id.webview1); deviceid = secure.getstring(this.getcontentresolver(), secure.android_id); //toast.maketext(this, deviceid, toast.length_long).show(); webview.getsettings().setjavascriptenabled(true); // webview.getsettings().setbuiltinzoomcontrols(true); checkconnection2(); pd = new progressdialog(mainactivity.this); pd.setmessage("loading"); pd.show(); above class file.. and below xml layout file- <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom=...

stack - Could anyone help me with this python singpath program? -

first of all, not class. have been working on these 2 programs long time , cannot make heads or tails of it. want past these problems can move onto other lessons. "create function transforms prefix notation postfix notation, , postfix notation prefix notation. function takes 2 arguments. first string of expression without spaces or syntax errors, , second string contains operators. characters not in second string regarded operands. lengths of operators , operands 1, , operators binary operators." ex: >>> fix_trans('ab33c2c11','abc') '33b211cca' and convert (reverse) polish notation: >>> topolish('(3+5)*(7-2)',d,0) '*+35-72' can provide examples of how far you've gotten this, or methods haven't worked you? also, familiar shunting-yard algorithm ?

html - How to prevent child element from inheriting CSS styles -

i have <div> element <p> element inside: <div style="font-size:10pt; color:red;"> parent div. <p>this child paragraph.</p> parent div ends here. </div> how can prevent paragraph inheriting css properties set <div> ? in case best way on right styles <p> element inheriting: so in css file, should using instead of inline styles: .parent-div { font-size: 10pt; color: red; } .child-paragraph { font-size: 12pt; color: black; }

android - Shrink wallpaper bitmap drawable to reduce RAM usage -

i using device wallpaper layout background. bitmap drawable size large on on devices 7 mb in samsung s3. there way reduce without consuming more ram. worried oom on low memory devices. wallpapermanager wallpapermanager = wallpapermanager.getinstance(mcontext); bitmapdrawable bitmapdrawable = (bitmapdrawable) wallpapermanager.getdrawable(); bitmapdrawable.setgravity(gravity.center_vertical | gravity.clip_vertical); if (android.os.build.version.sdk_int < android.os.build.version_codes.jelly_bean) { layout.setbackgrounddrawable(bitmapdrawable); } else { layout.setbackground(bitmapdrawable); } you can use bitmapfactory.options should convert bitmapdrawable byte[] //convert bitmapdrawable byte[] //winsize height screen user device bitmapfactory.options options = new bitmapfactory.options(); options.injustdecodebounds = true; bitmapfactory.decodebytearray(imagedata, 0, imagedata.length, options); if (opt...

rest - How do I make an Ember-Data has-many collection that is defined by another API endpoint? -

i've got model, post has many comment s. response get /posts/12 pretty ember-data-friendly: { "post": { "id": 12, "title": "i love ramen", "created_at": "2011-08-19t14:22", "updated_at": "2011-08-19t14:22", "body": "..." } } the api post 's comment s, however, get /posts/12/comments , returns { "comments": [ { "id": 673, "author_id": 48, "created_at": "2011-08-21t18:03", "body": "me too!" } ] } what can model or adapter tell post 12 's comment s, use /posts/12/comments ? notice post has no knowledge of comment ids. update in response buuda's answer , here clarifications: the post must able comment s can (a) show comments on postroute , (b) have properties on post like hascomments: function() { return this.get('c...

php - How to create a different store in magento on single domain? -

i searching hard make 2 different stores in magento different functionalities , believe possible in magento 2 different magento installation on single domain. i have went through of following tutorials: multiple magento stores on single domain http://inchoo.net/magento/how-to-set-multiple-websites-with-multiple-store-views-in-magento/ i have read tutorials, think tutorials work on 1 magento installation. i wanted know whether can make 2 store, 1.www.domain.com/store1 2.www.domain.com/store2 with different template design , different functionalities well, think need 2 different installation. also 1st website created , want share categories , products ,but different product prices on 2nd store. are these things possible magento , if yes need hint or little ? also ,how can change nginx configuration same ? sounds need create different website views , stores views. can done in system > manage stores. then need in system >configuration part drop dow...

asp.net - How to solve the following compilation error in C#? -

my .aspx looks following: <div id="valueintroduction" type="text" class="labelarea" runat="server"> <input name="$labeluniversityid" type="text" id="labeluniversityid" style="color:#7d110c;border:0;background-color:#c0d5f2;width:100%" /> </div> .cs file looks like: if (results.read()) { labeluniversityid.value = results["text_content"].tostring(); } exactly trying getting data database , displaying in valueintroduction div. workiing fine. added text box readonly mode. in page if press edit button, value edited. use texbox component: <asp:textbox id="labeluniversityid" runat="server" cssclass="yourcssclass"></asp:textbox> as styling: .yourcssclass { color:#7d110c; border:0; background-color:#c0d5f2; width:100% } then, in code behind can use this: labeluniversityid.text = results[...

click on link with curl php -

i want know how click on link curl in php. pass login page when want create new curl_exec click tag, cant thing. tag make xhr request data , pass form data , still have problem. note:my website want content curl asp. $this->_ch = curl_init(); $this->config(); // normal config curl if (!empty($this->_fields)) { $fields = http_build_query($this->_fields, '', '&'); curl_setopt($this->_ch, curlopt_postfields, $fields); } else { curl_setopt($this->_ch, curlopt_post, false); } if($testparam !="") { curl_setopt($this->_ch, curlopt_postfields, $testparam); } $result = curl_exec($this->_ch); $this->_curlinfo = curl_getinfo($this->_ch); $this->_lastresult = $result; $this->_fields = array(); if (!$this->curlcheckerror()) { $result = null; } ...

ios - Cannot subscript a value of type '[String: AnyObject]' with an index of type 'String' -

Image
this not duplicate of question cannot subscript value of type '[nsobject : anyobject]?' index of type 'string' or cannot subscript value of type '[string : string]?' index of type 'string' the reason because dictionary not optional, problem question. why can't subscript this... accessing dictionaries subscript returns optional. because can't tell dictionary going use subscript exists in keys list. (even if could, wouldn't believe :).

python - Pass list to function by value -

i want pass list function value. default, lists , other complex objects passed function reference. here desision: def add_at_rank(ad, rank): result_ = copy.copy(ad) .. result_ return result_ can written shorter? in other words, wanna not change ad . you can use [:] , list containing lists(or other mutable objects) should go copy.deepcopy() : lis[:] equivalent list(lis) or copy.copy(lis) , , returns shallow copy of list. in [33]: def func(lis): print id(lis) ....: in [34]: lis = [1,2,3] in [35]: id(lis) out[35]: 158354604 in [36]: func(lis[:]) 158065836 when use deepcopy() : in [41]: lis = [range(3), list('abc')] in [42]: id(lis) out[42]: 158066124 in [44]: lis1=lis[:] in [45]: id(lis1) out[45]: 158499244 # different lis, inner lists still same in [46]: [id(x) x in lis1] = =[id(y) y in lis] out[46]: true in [47]: lis2 = copy.deepcopy(lis) in [48]: [id(x) x in lis2] == [id(y) y in lis] out[48]: false

php - how to fetch next value in foreach loop -

i have foreach loop below code : foreach($coupons $k=>$c ){ //... } now, fetch 2 values in every loop . for example : first loop: 0,1 second loop: 2,3 third loop: 4,5 how can ? split array chunks of size 2 : $chunks = array_chunk($coupons, 2); foreach ($chunks $chunk) { if (2 == sizeof($chunk)) { echo $chunk[0] . ',' . $chunk[1]; } else { // if last chunk contains 1 element echo $chunk[0]; } } if want preserve keys - use third parameter true : $chunks = array_chunk($coupons, 2, true); print_r($chunks);

Php CSV export UTF8 encoding causing incorrect excel format -

i tired doing csv export. needed 2 languages (tamil , english) in sheet using normal headers $now = gmdate("d, d m y h:i:s"); header("expires: tue, 03 jul 2001 06:00:00 gmt"); header("cache-control: max-age=0, no-cache, must-revalidate, proxy-revalidate"); header("last-modified: {$now} gmt"); header ( 'content-type: application/vnd.ms-excel') ; header("content-disposition: attachment;filename={$filename}"); header("content-transfer-encoding: binary"); echo $content; this causing problems in tamil characters being displayed. format of excel fine. used utf8 encoding display tamil characters shown below. $now = gmdate("d, d m y h:i:s"); header('pragma: public'); header("expires: tue, 03 jul 2001 06:00:00 gmt"); header('cache-control: must-revalidate, post-check=0, pre-check=0'); header("last-modified: {$now} gmt"); ...

javascript - How to add images in angular JS -

i'm new angular js. i have stumbled problem. using json data , not sure of how supposed add images in code <div ng-controller="myctrl" class="container"> <div class="col-md-8"> <div ng-repeat="item in products" class="product col-md-4"> <h3>{{item.title}}</h3> <img ng-src="{{item.image}}" alt="..." class="img-thumbnail"> <p> <br> <button type="button" ng-click="show = !show" class="btn btn-success">view product</button> <button type="button" ng-click="add_to_cart()" class="btn btn-danger">add cart</button> <br> <span><b style="color: #ff0000">size: </b> {{item.size}} </span> <sp...

angularjs - Add marker with time validity and near real time -

in asp.net web api application angularjs frontend want display marker on map (google maps or leaflet) time validity in near real time. what meaning? each user (client) of app should (near real time) see when user add marker on map. each added marker can have different time validity. if time validity expired, marker should removed map , each user should see that. there 2 options - client side or server side. on client side there "timer" available each marker (e.g. .settimeout() ). if have hundreds of markers different time validity, need same number of timer. not need ressources on client side? thought better on server side? if time validity expired of marker, want remove marker each client. mean, have send request each marker. there best practice that? maybe signalr or that? why not have 1 setinterval markers?, timer fire event @ regular basis markers. think should go webservice option solve this, or maybe combination of both.

K2 for data integration aka ETL -

my company starts adopt k2. ignorant it. k2 can used data integration/orchestration layer, wondering whether use etl data integration data warehouse/data marts. looking potential alternatives ssis. k2 uses smartobject layer data integration layer. but if expecting full featured etl data integration, disappointed. k2 smartobject provide many different channels , mediums integration. transformation , validation of data in smartobject, hard sell. you can build logic in there. bringing back, k2 smartobject build allow workflow , forms pull or push data. not design etl in mind. hope sum you.

Query MongoDB via PHP, compare date and send email -

i want query on users in database. check 'lastlogin' of each user , if longer ago e.g. 7 days, send mail mail address of user. did simple query already, have no idea how continue. array notation confuses me... hope can me out or post code snippet! <?php $m = new mongo(); $collection = $m->selectdb('platte')->selectcollection('users'); $results = $collection->find(array(),array("email"=>1, "lastlogin"=>2)); ?> you looking range query. create mongodate , example using strtotime() , represents date 7 days ago , use in search query searching documents login field less 7 days ago date: in mongo shell, represented query: var d = new date(); d.setdate(d.getdate() - 7); var query = { "lastlogin": { "$lte": d } }; var projection = { "email": 1, "lastlogin": 1 } db.users.find(query, projection); in php, translate to: $m = ...

jquery - JQGrid Column Customization ..Add Column at Run time -

am new j query , trying samples in http://www.trirand.com/blog/jqgrid/jqgrid.html see column names written in js displayed in grid. i have requirement on jqgrid show column search every time. example: have standard set of columns displayed in grid student name, address,phone number. suppose if user search student id need add student id column result. i should show "student name, address,phone number,studentid" if search total i should show "student name, address,phone number,total" to simplify need add 1 column jqgrid after user clicks on search. can in jqgrid. how can implement ? this answer taken older version of oleg's answer here : it not possible add column jqgrid dynamically. have recreate whole grid colmodel having 1 column more. if use separate colnames , size of array have increased too. can use griddestroy example destroy existing grid. can bind column normal can show/hide them @ runtime using jquery . add colu...

html - Make Cursor position in center for ui.helper in jquery-ui draggable method -

i want cursor in center ui.helper of draggable . i doing this $(".soclass").draggable({ cursor: "move", helper: 'clone', revert: "invalid", tolerance: "fit", start: function(event, ui){ $(this).draggable("option", "cursorat", { left: math.floor(ui.helper.width() / 2), top: math.floor(ui.helper.height() / 2) }); } }); using i cursor in center after first drop . how can center align cursor right first drop. jsfiddle you can access offset.click property of draggable instance, pretty setting cursor @ option problem setting option, describe it'll applied next time trigger start event. using property can set on current event. this: start: function(event, ui){ $(this).draggable('instance').offset.click = { left: math.floor(ui.helper.width() / 2), top: ...

Declaration in javascript -

greetnigs. i'm new in javascript , found not familiar me, yet. tell me how it's called , how works? var empty = 0, snake = 1, fruit = 2; var grid = { width: null, height: null, _grid: null, init: function(d, c, r) { }, set: function(val, x, y) { }, get: function(x, y) { } } first declaration equal 3 separated in different lines var prefix? second 1 object 3 properties , has declared 3 functions called: init, set , get, extended later , functions available object? regards

javascript - gulp browser-sync not serving json files -

i have issue not able serve json files sub-folders. below code: var browsersync = require('browser-sync').create(); // static server gulp.task('connect', function() { browsersync.init({ server: { basedir: "app/" } }); }); all static , angularjs files reside inside app folder. when navigate http://localhost:3000 , page loads corresponding json file inside app/data/myfile.json not load. i below error in console: post http://localhost:3000/data/json/myfile.json 404 (not found) the strange thing when try load path in browser, json file loads. at first used way https://www.browsersync.io/docs/options/#option-servestatic fail. const asset_extension_regex = new regexp(`\\b(?!\\?)\\.(${config.assetextensions.join('|')})\\b(?!\\.)`, 'i'); const default_file = 'index.html'; ... server: { basedir: './build', middleware: function(req, res, next)...

Client.exe dump file through WinDbg: -

been trying solve why app crashing on 1 windows 7 computer , running fine when installed on 5 others. program part of camera security system client.exe contacts internal server , brings cameras application viewer. program connects , starts load couple of streaming video windows crashes. recent dump file. antivirus has been removed. dotnet verifyer tools has been run on machine. memory upgraded 4gb 8gb. windows updates current. suggestions appreciated. microsoft (r) windows debugger version 6.3.9600.17336 amd64 copyright (c) microsoft corporation. rights reserved. loading dump file [c:\users\administrator\appdata\local\crashdumps\client.exe.4756.dmp] user mini dump file: registers, stack , portions of memory available ************* symbol path validation summary ************** response time (ms) location deferred srv*c:\symbols*https://msdl.microsoft.com/download/symbols symbol search path is: srv*c:\sy...

How to map object properties in an Orika custom mapper? -

i tried find answer question in orika documentation no luck. i have following classes: public class { private string partnumber1; private string partnumber2; ... } public class b { private integer shelfnumber; private a; ... } public class bdto { private integer selfnumber; private adto somea; ... } public class adto { private string partnumber; ... } .. , following custommapper's map objects of b objects bdo @component public class bmapper extends custommapper<b, bdto> { @override public void mapatob(b b, bdto bdto, mappingcontext context) { super.mapatob(b, bdto, context); //??? here ??? } } @component public class amapper extends custommapper<a, adto> { @override public void mapatob(a a, adto adto, mappingcontext context) { super.mapatob(a, adto, context); adto.setpartnumber(a.getpartnumber1() + a.getpartnumber2()); } } in client code have: b b =...

assembly - Assembly80x86 filling array with user input(names), but no repeating them -

i need fill array names user input, keep out names stored in array(ex, john,jaina,tom,bob). got this, it's not working. data segment numbers db 0 names db 220 dup (?) buffer db 10 dup (?) code segment start: mov ah, 1; int 21h mov numbers, ax mov cx, numbers lea bx, [names] names: onename: lea si, [buffer] mov ah,1;character character int 21h mov [bx], al inc bx mov [si], al inc si cmp al, ',' ;end of name je compare; loop onename compare:;buffer names lea di, [names] check: lea si, [buffer] cmp si, di jne nextname inc si inc di jmp check nextname: cmp di, ',' je check inc di jmp nextname loop names mov ah, 1; int 21h mov numbers, ax you don't initialize counter correctly. dos function 01h gives ascii code in al , ...

garbage collection - How to pass output of one function to another in Spark -

i sending output of 1 function dataframe function. val df1 = fun1 val df11 = df1.collect val df2 = df11.map(x =fun2( x,df3)) above 2 lines wriiten in main function. df1 large if collect on driver gives outof memory or gc issue. r ways send output of 1 function in spark? spark can run data processing you. don't need intermediate collect step. should chain of transformations , add action @ end save resulting data out disk. calling collect() useful debugging small results. for example, this: rdd.map(x => fun1(x)) .map(y => fun2(y)) .saveasobjectfile(); this article might helpful explain more this: http://www.agildata.com/apache-spark-rdd-vs-dataframe-vs-dataset/

amazon web services - How do I register logging driver for docker? -

i'm trying use amazon cloudwatch logs logging driver described in this doc . but following error when launch container error response daemon: cannot start container 1769b857d0ed51cf30b1c160485c9eb05f68ab07a84eaf861893d9d55e6139c4: failed initialize logging driver: failed logging factory: logger: no log driver named 'awslogs' registered how register driver docker ? shall modify docker's systemd script or ? i posted bug on docker's github , got reply awslogs not added until 1.9.0. and according this issue aws cloudwatch support seems broken in latest version of docker.

Python- How does return work in function -

i confused using functions in python. suppose have code def calculate(a): = int(a) return # or yield then write as def _convert(a): = int(a) return # or yield a+1 def calculate(a): _convert(a) # correct or need (return _convert(a)) -- internal return function goes till end? the return statement allows determine value function call takes in expression. if 1 function calls another, the second functions returns value first. thus in second example, in order calculate return value caller must indeed use return statement, , return _convert(a) indeed correct. such answers can determined running them in interactive interpreter, encourage beginners use purpose.

swing - Does Java have the Pythagoras Theorem? -

i use java swing create simple games such pong , air hockey, , find myself using pythagoras theorem calculate distance between 2 points. although it's not pain write (it can reduced single line), wondering if java had included somewhere. i looked through math class, , didn't see there. didn't know else look, if exist, know where? thanks! yes, java has such function in standard library. called math.hypot . can write: math.hypot(x2 - x1, y2 - y1) this method part of java since java 1.5.

javascript - How to get value of a data-id attribute from selected(different id, same name) datalist (html5) option? -

<input type="text" value="" list="department" /> <datalist id="department"> <option data-id="1" value="arthur"></option> <option data-id="2" value="arthur"></option> <option data-id="3" value="king"></option> <option data-id="4" value="gabriel"></option> </datalist> i need access value of 'data-id' selected datalist option on click of "#button" or event. there situation: same value name, different data-id. want correct id. should do? think u! accessing these values can done in 2 ways vanilla javascript, , neither conflicts regular attributes. either use element.dataset[foo] element.getattribute('data-' + foo) (this 1 has more legacy support) where foo name of data attribute , i.e. "id" in case an <input> , <data...

html - Iframe fit to screen -

i trying integrate my blog website via iframe. however, using method have give height , width in pixels. want blog fit screen, though. there way this? edit: answer below suggests change css. do "width" , "height" variables in html? here full html code of page. <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="css/style.css" /> <title>shiloh janowick's blog!</title> <link rel="shortcut icon" href="pics/favicon.ico" type="image/x-icon"> <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="expires" content="0" /> </head> <body> <iframe width="" height="" src="http://shilohgameblog.wordpress.com...

Kotlin Android Project failed to sync Gradle Project -

Image
i created android project newest android studio version (v2 preview 5) , converted kotlin project. gradle not able sync , build project, see screenshot: i didn't build file , deleted entire gradle cache restarting, killing daemons etc. used newest kotlin version 1.0.0-beta-4584 as error message suggest guess reason kotlin plugin, know how solve problem? the kotlin gradle plugin not compatible latest alpha plugin of android ( 2.0.0-alpha6 ) or alpha5 matter. until case, can use 2.0.0-alpha3 instead.

scala - What is the purpose of an empty loop in this volatile var example? -

code: class page(val txt: string, var position: int) val rand = new random() object volatile { val pages = for(i <- 1 5) yield new page("na" * rand.nextint(1000) + " batman!", -1) @volatile var found = false (p <- pages) yield thread { var = 0 while (i < p.txt.length && !found) if (p.txt(i) == '!') { p.position = found = true } else += 1 while(!found) {} log(s"results: ${pages.map(_.position)}") } } what purpose of empty loop while(!found) {} ? the first loop: while (i < p.txt.length && !found) has 2 conditions stopping: when search space exhausted, or when match found. note found variable used in multiple threads: thread {...} presumably spawns new thread. so there several possibilities how threads' loops can play out: the thread finds '!' , sets found . first loop breaks, second doesn't execute. another thr...

Codeigniter: won't load controller page -

i have web page made codeigniter, , works fine, when try add controller gives me a:"404 page not found" - "the page requested not found." why? controller i'm adding 1 tutorial (i'm practising): <?php class blog extends ci_controller { public function index() { echo 'hello world!'; } } ?> i'm using ubuntu, if makes difference. better check out // file name : blog.php class blog extends ci_controller(){ function blog(){ parent::__construct(); } function index(){ echo 'helloworld'; } } your controller filename should equal or same created class controller name. try put constructor before index this.

dojo 1.8 - This time though server, unable to initialise and update ComboBox every time there ia a change in select -

i able able make work after have got help, though not able combobox display selected option. this time wanted improvise jsfiddle connecting server, list. wondering why did not work though made based on previous jsfiddle. when run firebug , firephp enabled. can see managed list not able initate combobox. firebug or firephp did not produce errors. please see jsfiddle . meter_select.on('change', function() { console.debug('selected card = '+ meter_select.value); request.post('listofcards.php',{ //'call listmfg_codes()' data:{cardx : meter_select.value}, handleas:"json" }).then( function(response) { var memostore2 = new memory({data:response});//ok var card_select = registry.byid('node_cardselect');//ok ...