Posts

Showing posts from September, 2014

java - Are there dangers to throwing a runtime exception forcibly into a thread with Thread.stop(Throwable)? -

i writing large, multithreaded application, many differing roles threads (e.g. event processing, metrics, networking). currently, if there inconsistency cannot handled, manifest exception. since there's no way recover of them, i've been rethrowing runtime exception of type applicationdeathexception . any classes need handle shutdown call catch block exception, , rethrow in order propagate stack). i considering killing off other threads in same manner calling thread#stop(throwable) upon them. fine sudden termination, , can catch exception should there need shutdown logic. have exception propagate stack, performing shutdown logic whereever needed, , killing thread in end. there hidden dangers i'm missing approach? thread.stop has been deprecated since unsafe (see javadoc). instead have each thread monitor boolean flag of sort (see java: how stop thread? , countless other threads on so). in situations typically implement sort of thread pool manager respon

javascript - toggling image classes for inactive/active states -

i'm still coming against resistance here js- have row of thumbnails. first starts active class,the others have inactive classes. on click, want thumb clicked switch active , previous go inactive. want hover effect inactive classes. right now, can add active class, cant figure out how toggle prev active class jquery(document).ready(function($) { $(".groomsmen_thumbs, .bridesmaid_thumbs").click(function(){ if ( $(this).find(".toplevel").hasclass("inactivethumb") ) { $('img', this).toggleclass("activethumb inactivethumb"); } }), $('.groomsmen_thumbs, .bridesmaid_thumbs') .on("mouseenter", function() { $(this).find(".inactivethumb.toplevel").animate({"opacity": "1"}, "fast"); }) .on("mouseleave", function() { $(this).find(".inactivethumb.toplevel").animate({"opacity": "0"}, "fast"); }) }); links this <li><a hr

bash - How to test existence of a program in crontab? -

i made bash script test if utility named 'myutility' exists: #!/bin/bash #if hash myutility >/dev/null 2>&1; if hash myutility 2>/dev/null; echo "branch true" exit 0 else echo "branch false" exit 1 fi on command line, $ ./test.sh branch true -- seems work. if add crontab: $ crontab -l ## test * * * * * /users/meng/bin/test.sh > "/users/meng/log.txt" i got $ more /users/meng/log.txt branch false so, somehow when script run crontab, hash myutility >/dev/null 2>&1 part not work. idea? knowing when, , why, cronjobs fail can difficult. solution use wrapper script archive successful cron job runs time , send email admin staff when fails. both successful , failed runs leave trace file disk can read understand job did , when. @ failure trace sent admin staff, not need login server initial idea should done if anything. notice when things fail best read notification email bottom to

python - How to modify an inherited list in the __init__ method of a subclass? -

is possible change in init function of class? lets have class called "deck" which, when initialized, creates list of 52 card objects. now want make class called "even" inherits "deck" class , creates deck of card objects eliminates cards number 2 (so spades, hearts, etc) inherited "deck". i have been having lot of trouble because when try modify inherited list, regardless of try, python return error, 'nonetype' being main root of problem. here code "even" class init: def __init__(self): x = deck.__init__(self) card in x: if card.rank() == 2: x.pop(card) return x it worth noting card class has method rank() return rank of card int. regardless of things have tried, there wrong it. "'nonetype' object not iterable" or "subscripable" , when check type() of x nonetype. have done lot of searching around nothing making sense me nonetype or should fix it. if r

css - Minifying only a part of .LESS file -

when working .less preprocessor files, there gui tools such winless, etc. or in grunt, minify section of outputted css file? for eg. in final .css, want main code remain neatly formatted reset code or normalize include minified. e.g. https://github.com/tryghost/casper/blob/master/assets/css/screen.css in file, either can minify , have min.css users use, want know if there automated option minify part of it, e.g. normalize reset section.

php - PDO Login Script Always Re-Directing To Header Page -

Image
<?php include "config.php"; class users extends config { public function login($username, $password) { try { $this->db->begintransaction(); $stmt = $this->db->prepare("select `username`, `password` `users` `username` = ? , `password` = ? limit 1"); $stmt->execute(array($username, $password)); if($stmt->rowcount == 1) { while($row = $stmt->fetch(pdo::fetch_assoc)) { header("location: index.php?p=loggedin"); exit(); } } else { header("location: index.php?p=false"); exit(); } $this->db->commit(); } catch(pdoexception $ex) { $this->db->rollback(); echo $ex->getmessage(); } } }

Time period in Excel 2010 -

a simple question, quick googling did not prove fruitful. basically, have column called "uniqueid", unique identifier people in dataset. uniqueids have multiple records, because there 1 record per year person stayed @ university. i'd create "time period" variable, first year, t= 1, second year t=2, third year t=3 etc. each unique id. the following faster if spreadsheet sorted unique id; =if(a2=a1,b1+1,1) (assumes above formula in column b , data begins on row 2) and, of course, copied down rows described above. you find in spreadsheet containing many rows countif slow since looking through ever-increasing range sizes.

java - Adding Jpanel containing JButton disturbs the structure of frame -

Image
class frame extends jframe{ public frame() { jframe jf= new jframe("student admission"); jf.setlayout(new gridlayout(5,1)); jpanel jpn= new jpanel(); jpanel enr= new jpanel(); enr.setlayout(new flowlayout(flowlayout.left)); jlabel enrno= new jlabel("enrollment number",jlabel.left); jtextfield enrnoinput=new jtextfield(3); enr.add(enrno); enr.add(enrnoinput); jf.add(enr); jlabel name= new jlabel("student's name",jlabel.left); jtextfield nameinput=new jtextfield(60); jpn.add(name); jpn.add(nameinput); jf.add(jpn); jpanel jpfn= new jpanel(); jlabel fname= new jlabel("fathers's name",jlabel.left); jtextfield fnameinput=new jtextfield(60); jpfn.add(fname); jpfn.add(fnameinput); jf.add(jpfn); jpanel hscp= new jpanel(); hscp.setlayout(new flowlayout(flowlayout.left)); jlabel hscper= new jlabel("hsc percentage",jlabel.left); j

ios - Inherit from tableViewController -

i have myvc inherited tableviewcontroller. now inherit myvc in detailvc. i want have tableview in myvc , cell in detailvc. (i have difficult cell construction) have full implementation of myvc in detailvc(with myvc's navigation buttons). how can have table 1 cell in detailvc? create model containing cell components name,occupation etc. store data populating table cells in array. in - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath method self.timesheetmodel = [self.timesheetlistarray objectatindex:indexpath.row]; in - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { self.detailvc = [[detailvc alloc]init]; //create property model in detailvc assign it. self.detailvc.model = [self.timesheetlistarray objectatindex:indexpath.row]; //pass model . data in detailvc of selected cell. [self.navigationcontroller pushviewcontroller:self.detailvc animated:yes];

php - Warning Invalid argument supplied for foreach() -

i getting error message , don't have clue it. warning: invalid argument supplied foreach() in /home/a9083956/public_html/zundappgroesbeek/beheer/testretrievesql.html on line 31 this code working with. warning 31st line, foreach() line. ive changed = => make checkbox work, delete code won't work still. <html> <head> <title>retrieve , delete data database </title> </head> <body> <?php // connect database server mysql_connect("mysql7.000webhost.com", "a9083956_test", "sesam") or die (mysql_error ()); // select database mysql_select_db("a9083956_test") or die(mysql_error()); // sql query $strsql = "select * forum_question"; // execute query (the recordset $rs contains result) $rs = mysql_query($strsql); // loop recordset $rs // each row made array ($row) using mysql_fetch_array while($row = mysql_fetch_array($rs)) {

javascript - Twitter bootstrap:Popop are not showing up on first click but show up on second click -

here code. please me $(document).ready(function(){ $(document).delegate(".view","click",function(){ var id = $(this).attr("id"); alert(id); $("#"+id).popover({ html : true, content: function() { return $("#"+id+"tt").html(); }, title: function() { return $('#popovertitle').html(); } }); alert("thisa"); }); }); try replacing function .delegate() .on(), function has been superseded in last versions of jquery. jquery 1.4.3+ $( elements ).delegate( selector, events, data, handler ); jquery 1.7+ $( elements ).on( events, selector, data, handler ); the code be: $(document).ready(function(){ $(document).on("click",".view",function(){ var id = $(this).attr("id"); alert(id); $("#"+id).popover({ html : true, content: function() {

angularjs - angular changing the url location without reloading the page -

i have partials loaded url templates/test.html example. templateurl relative. want use same templates in different locations within website. so , want use same relative url http://somedomain.com/templates/test.html if on actual url of http://somedaomian.com/some1/some2 i have tried use $loaction service, unable set $loaction home url when need to. e.g in controller : var new_base_url = homeurl(); function homeurl() { /* here unable home url */ $location.path('/'); // returns current url }; if want absolute url, $location.absurl() return (all url segments). if want host name, $location.host() return host name. if want protocol, $location.protocol() return that. if want path, $location.path() return that. if want hash, $location.hash() return that. you should able use these methods parse out pieces of url after. var path = $location.path(); var hash = $location.hash(); var basepath = path.replace(hash, '');

php - Torrent scrapper -

i'm using scrap torrents , show seeds of them, use script found on internet , uses socket connect tracker , data, run on localhost xampp server when not server works, not catch seeds of stream , script generates error message script msg: error: not open http connection. connection error: yes script: code 1 (udptracker.php): <?php /* torrent udp scraper v1.2 2010 johannes zinnau johannes@johnimedia.de licensed under creative commons attribution-sharealike 3.0 unported license http://creativecommons.org/licenses/by-sa/3.0/ nice if send me changes on class, can include them if improve it. thanks! usage: try{ $timeout = 2; $scraper = new udptscraper($timeout); $ret = $scraper->scrape('udp://tracker.tld:port',array('0000000000000000000000000000000000000000')); print_r($ret); }catch(scraperexception $e){

Some confusion on backup whole data in redis -

document say: whenever redis needs dump dataset disk, happens: redis forks. have child , parent process. child starts write dataset temporary rdb file . when child done writing new rdb file , replaces old one . because want backup whole data, type shutdown command in redis-cli expecting shutdown , save data dump.rdb .after shutdown completely, go db location , see happen dimpr.rdb 423.9mb , temp-21331.rdb 180.5mb.temp file still exist , smaller dimpr.rdb .apparently, redis not use temp file replaces dump.rdb . i wondering whether dump.rdb whole db file @ time?and safe delete temp file. what file mod timestamp of temp-21331.rdb say? sounds leftover crash. can delete it. the documentation correct. when rewriting, info written temp file (compressed), , when complete, dump.rdb file replaced temp-file. there should no leftovers during normal usage. is important: need enough free disk space operation succeed. safe guideline is: 140% times redis memory limit (

cassandra - Deleting a row after certain time -

deleting row after time: i inserting notification in table. if unread there , if read should deleted after 1week. how achieve that? i using ttl seems expire column not row. i want delete row. create second cf (called eg. recorded, same key semantics notifications table) insert (w/ ttl) seen messages into. @ same time delete same message notifications table. to load inbox need read both cf. seen messages automatically removed after 1 week , unseen messages stick around ever.

git - Gerrit branch access modification through command line -

i change access rule deactivated branches on gerrit "allow" "deny".. have command line options available ? you can edit access rights through git protocol using refs/meta/config pseudo-branch. see docs . you checkout branch, modify project.config , push gerrit server. that's how can automate this.

java - Navigation drawer and Action bar tabs contents overlapping in android -

i have done navigation drawer , action bar tabs using fragments contents of navigationdrawer overlapping on actionbartabs content.how overcome problem , work google play store app. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); actionbar actionbar = getactionbar(); actionbar.setnavigationmode(actionbar.navigation_mode_tabs); // create new tabs , and set titles of tabs actionbar.tab mfindtab = actionbar.newtab().settext(getstring(r.string.ui_tabname_find)); actionbar.tab mchattab = actionbar.newtab().settext(getstring(r.string.ui_tabname_chat)); actionbar.tab mmeettab = actionbar.newtab().settext(getstring(r.string.ui_tabname_meet)); actionbar.tab mpartytab = actionbar.newtab().settext(getstring(r.string.ui_tabname_party)); // create fragments fragment mfindfragment = new

PHP Displaying data from MySQL database -

i wanted display page content php , mysql. don't know how select , display data php. $name = $_get['title']; $query = "select * pages name = $name"; $result = mysql_query("$query"); but don't know how display data. want string value content in sql table row name = $name , display it. if can, please me you may try , include in code: $name = mysqli_real_escape_string($_get['title']); $query = "select * pages name = $name"; $result = mysqli_query($link, $query); while ($row = mysqli_fetch_array($result)){ echo $row['content']; } mysqli_free_result($result); here have assumed $link handle connect database. n.b.: may consider passing $_get values through mysqli_real_escape_string() avoid sql injections may prove fatal database , tables. need consider usage of mysqli_* functions because mysql_* functions deprecated , discontinued.

php - file upload not working for doc, excel file -

i using below code file upload not work in case of doc , excel file switch(strtolower($imagetype)) { case 'image/png': case 'image/gif': case 'application/pdf': case 'image/jpeg': case 'video/avi': case 'video/mp4': case 'image/pjpeg': case 'application/msword': case 'application/vnd.ms-excel': break; default: die('unsupported file!'); //output error , exit } this code work case of image when upload doc file. show me unsupported file you missing additional mime types. mime types correct older .doc , .xls files, not newer ones. for .xlsx files use: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for .docx files use: application/vnd.openxmlformats-officedocument.wordprocessingml.document this migh

c++ - How to search a string for a character, and remove said character -

i'm trying code word game, , in word game, need able know letters have available me. have string available letters, @ start, "abcdefghijklmnopqrstuvwxyzaeiou", entire alphabet set of vowels. need able search string character (i might want use letter 'c'), , assuming character in string, remove character string. i'm not entirely sure how this, i'm writing in pseudocode. string alphabet = "abcdefghijklmnopqrstuvwxyzaeiou" char input; cout << "please input character."; cin >> input; if (input in string) { remove letter string } else { cout << "that letter not available you." } i think can use string::find find character, don't know how i'd able remove letter string. if there's better way go this, please let me know. how search string character, , remove said character just use std::remove , , erase-remove idiom : #include <string> #include <al

hooks to run different setup and clean for each test case in mocha -

i developing mocha automation framework. in there 2 hooks beforeeach() , aftereach() executed each test case. have defined test setup , cleanup in these hooks. have different setup , cleanup each test case, cant able use beforeeach() , aftereach(). describe() { beforeeach(setup) //test setup it(test1) it(test2) it(test3) aftereach(cleanup)//test cleanup } in above code, each test follows different setup , cleanup. there other hooks or methods satisfies condition, i.e. hooks allows different setup , cleanup individual test case? if setup , cleanup different each test, should this: function test1() { # setup test1setup(); # execute code under test # cleanup test1cleanup(); } do see (or have encountered) issues that?

javascript - Canvas WrapText function with fillText -

i creating multiple choice quiz, however, questions many characters , won't display on 1 line. understand have use wraptext function in order paragraph it, unsure how implement within code. questions set strings in variable (questions), answers being strings in variable (options). textpos1, defines coordinates want question start, textpos2 - textpos4 defining coordinates separate answers start. these coordinates in these positions align background image. jsfiddle here full code doesn't seem bg image on there... http://jsfiddle.net/danielparry8/6u9rn/ var canvas = document.getelementbyid("mycanvas"); var context = canvas.getcontext("2d"); var quizbg = new image(); var question = new string; var option1 = new string; var option2 = new string; var option3 = new string; var mx=0; var my=0; var correctanswer = 0

c# - Remove weekends Silverlight DatePicker -

i have little question silverlight's datepicker. i wonder if knows how remove every week end silverlight's datepicker? thank answers. its going lot of coding, simple way specifying weekend dates, <calendar name="calworkingdays" selectionmode="singledate"> <calendar.blackoutdates> <calendardaterange start="8/6/14" end="8/7/14"/> <calendardaterange start="8/20/14" end="8/20/14"/> <calendardaterange start="8/28/14" end="8/30/14"/> </calendar.blackoutdates> </calendar> if doing using mvvm, have service method blackoutdates , bind mentioned here. datepicker-with-holiday-blackouts-and-tooltips

run jasper report using rest request in C# asp.net -

i have been trying days jasper reports integrated .net website. have tried several ways including soap , rest service custom library suggested in post( http://freeze.ro/?q=node/7 ). know close new , still trying understand how works. people suggest using rest method , found example on here still getting error bad request. code rest request. webclient httpclient = new webclient(); httpclient.credentials = new networkcredential("username", "password"); httpclient.headers.add("content-type", "application/x-www-form-urlencoded"); // build resourcedescriptor string requestxml; requestxml = "<resourcedescriptor name=\"invoice\" wstype=\"reportunit\" uristring=\"/reports/nosreports/invoice\""; requestxml += " isnew=\"false\">"; requestxml += " <parameter name=\"invoiceid\">1016242</p

user interface - In a MATLAB GUI, extract coordinates by clicking inside a plot and display it -

Image
i'm pretty new matlab, have looked everywhere solution problem : let's use gui example : how can i, clicking somewhere inside plot, display x coordinate in text box ? here's code tried in gui code, couldn't work : function axes1_buttondownfcn(hobject, eventdata, handles) [x y] = get(gca,'currentpoint'); set(handles.edit1,'string', num2str(x)); guidata(hobject, handles); edit: oh, misread question. pushed original answer bottom of post. might still useful. here go: function axes1_buttondownfcn(hobject, eventdata, handles) [x y] = eventdata; set(handles.edit1,'string', num2str(x)); guidata(hobject, handles); note, i've seen instances eventdata doesn't work. if try use , it's empty, let me know , i'll try walk through doing using custom datacursormode tooltip callback function, more complex, doable. original: datacursormode on for additional information see this page. i've done lot of wor

How do I fix error "use of undeclared identifier n" in C? -

i'm sure there tons of syntax/other errors, i'm trying figure out 2 it's picking on. i'm new don't know how fix undeclared identifiers. note #include <cs50.h> cs50's library. #include <cs50.h> #include <stdio.h> int main (void) { int add, fee, disc; printf("for rate tax , security deposit, type y. 10 percent off, type n:"); string name = getstring(); if (name == y) { printf("pretax amount: "); scanf("%d", &fee); printf("okay. add 10 percent tax %d.\n ", fee); add = (1.1 * fee); printf("plus tax amount = %d\n", add); printf("security deposit = 1000 dollars\n"); printf("total = (%d + 1000)", add); } else if (name == n) { printf("pretax amount: "); scanf("%d%d", &fee, &disc); printf("okay. minus 10 percent discount %d , add tax.\n ", fee);

networking - Python Multiplayer Games -

i have been trying find tutorial making multiplayer games python, have struggled find 1 covers more multiplayer on same wifi connection. if possible, , guys one, or how it, (module, library..), please share me? thanks it indeed possible. might try twisted , popular event-driven networking engine written in python. also check out this page examples of games written in pygame have multiplayer functionality (source code included)

Accessing flash attributes in Spring Web flow -

i use, redirectattributes.addflashattribute("msg","level complete") to access message on redirected jsp. how can use redirect attribute when redirecting webflow ? when flash attribute used send data 1 controller webflow have bind redirected flash attribute (from controller) response jsp page of webflow. purpose can maintain backend formaction class bind value scope of webflow. in flow xml can can call custom method on entry of view state. custom method of formaction class public void setupreferencedata(requestcontext context) throws exception { httpservletrequest request = (httpservletrequest) context.getexternalcontext().getnativerequest(); map<string, ?> inputflashmap = requestcontextutils.getinputflashmap(request); if (inputflashmap != null) { string flash = (string) inputflashmap.get("flash"); context.getrequestscope().put("flash1", flash); } } this

AngularJS directive file upload with progress bar from AngularJS O'Reilly book -

i'm starting angularjs , following book o'reilly, angularjs. in there example of using file upload file upload blueimp. i can upload files, want show progress bar , can not access element contains during "progress" event. in declaration of directive have "element" access container element , once there, show div progress bar, progress event have no access "element" (one passed 2 arguments, e & data) during file upload can not show bar. have looked @ many examples used differently i'm doing so, not serve me. is possible pass "element" function runs on progress event? ecm_directives.directive('fileupload', function(){ return { restrict: 'a', scope: { done: '&', progress: '&', }, link: function(scope, element, attrs) { var optionsobj = { datatype: 'json' }; if (scope.done) { optionsobj.done = function(e, data) { scope.$ap

c++ - How call method from Qt GUI in background worker thread using QThread -

i'm trying add gui in qt code recieving data vrpn server. , need continuously send data server application , call action(method) in interface when receive information. but have problem endless cycle while (running) . found solution use qthread recieving data server, can't figure out how use method qt class in worker when recieve data server. i tried make worker way, i'm not sure, how call method class when recieve data server (or if it's @ possible/or exist better way): #include "worker.h" #include <iostream> #include "vrpn_analog.h" void vrpn_callback vrpn_analog_callback(void* user_data, vrpn_analogcb analog) { (int = 0; < analog.num_channel; i++) { if (analog.channel[i] > 0) { there want call method nextimage(), have in qt class mainwindow } } } // --- constructor --- worker::worker() { } // --- deconstructor --- worker::~worker() { } // --- process -

php - Pause the Flow-player once a JavaScript function is called. -

Image
i using flowplayer display videos in project. using following code: <a href="<?php echo base_url()?>secure/<?php echo $videos->videolink?>" class="fplayer" id="flowplayer"> </a> <script> $(document).ready(function() { $('div[id^="overlay_form"]').css({ left: ($(window).width() - $('div[id^="overlay_form"]').width()) / 2, top: ($(window).width() - $('div[id^="overlay_form"]').width()) / 7, position:'fixed' }); }); </script> <script> $f("flowplayer", "<?php echo base_url()?>js/flowplayer-3.2.18.swf", { clip: { autoplay : "true", autobuffering : "true", onstart: function() { //msgs.innerhtml += "common clip event listener called\n"; return true; }, onpause: function() {

c++ - How to use CGAL::triangulate_polyhedron -

i trying use undocumented function cgal::triangulate_polyhedron. receiving lots of error it. here simple code: #include <cgal/exact_predicates_exact_constructions_kernel_with_sqrt.h> #include <cgal/point_generators_3.h> #include <cgal/algorithm.h> #include <cgal/polyhedron_3.h> #include <cgal/convex_hull_3.h> #include <cgal/triangulate_polyhedron.h> #include <vector> typedef cgal::exact_predicates_exact_constructions_kernel_with_sqrt k; typedef cgal::polyhedron_3<k> polyhedron_3; typedef k::segment_3 segment_3; // define point creator typedef k::point_3 point_3; typedef cgal::creator_uniform_3<double, point_3> pointcreator; int main() { cgal::random_points_in_sphere_3<point_3, pointcreator> gen(100.0); // generate 250 points randomly on sphere of radius 100.0 // , copy them vector std::vector<point_3> points; cgal::cpp11::copy_n(gen, 250, std::back_inserter(points)); // define polyhedr

html - how to stay image constant on hover -

here code using on page html <a href="#" class="bac" data-role="none" style="color:#fff;"> <strong>an&uacute;nciese gratis</strong> </a> css .bac{ background:url("http://wstation.inmomundo.com/static02/costarica/sprites_botones1.png"); background-repeat:no-repeat; display: block; font:15px/18px arial; height: 22px; padding: 6px 18px 4px 4px; text-decoration: none; margin-right:-4px; } .bac:hover{ background-attachment:scroll; background-position:0px -35px; background-image:url("http://wstation.inmomundo.com/static02/costarica/sprites_botones1.png"); background-repeat:no-repeat; height:22px; padding:6px 18px 4px 4px; } here demo http://jsfiddle.net/lc4ky/1/ (open in google chrome browser) when open in google chrome, on hover image going off second showing hover effect.the image going off first time on each refresh. want should stable.is there solution this? i not sur

javascript/jQuery How do I reuse objects in an array for a particle system -

i'm in process of building entity system canvas game. started simple particle emitter/updater altering accommodate multi-particle/entity generator. whilst ok javascript/jquery running limits of experience concerns arrays , gratefully accept on following: when need new particle/entity current system calls function push object array contains variables entity updates. then update function runs loop on array, checking on type variable update particle (position/colour/etc...). [array.splice] particle, based on condition. when needed further particles/entities push new particles. what achieve here is: in makeparticle function, check on particle array "dead" particles , if available resuse them, or push new particle if not have created particlealive var flag purpose. var particles = []; var playing = false; function mousepressed(event) { playing = !playing; } if(playing) { makeparticle(1, 200, 200, 10, "blueflame"); makeparticle(1, 300, 200, 10, "r

stylus string interpolation styntax for :before pseudo selector using a for loop -

i'm trying make #others li .text1:before{ content: "text1"; }... by doing #others li label in text1 text2 text3 .{label}:before content {label} but syntax isn't right seems... gives error expected "indent", got "outdent" the error content {label} bit, because without class selectors ( .text1:before ) prints ok and content '{label}' prints out {label} is. stylus don't have interpolation in strings or idents values, use addition string, convert ident string: #others li label in text1 text2 text3 .{label}:before content ''+label

php - get first and last value form a mysql results array -

how go getting first , last value sql query . want highest , lowest vaue of variable $integer1, have ordered them in ascending order in sql query, need pull them out of array first , last items. tried didn't work: $first = reset($result); $last = end($result); also, in sql query select string1, string2 , integer1 i want order integer1 , print out first , last (both strings) first echo $string 1. " " . /4string2; last echo $string 1. " " . /4string2; asuming want min , max value of field in sql. instead of fetching rows table , take first , last row in php, in sql ! select min(your_field), max(your_field) your_table conditions group field1,field2

Windows Phone 8 append to JSON file -

i'm working on windows phone 8 app. i'm having issue appending json file. works fine if keep app open once close , come in starts writing beginning of file. relevant code: private async void btnsave_click(object sender, routedeventargs e) { // create entry , intialize values textbox... gasinfoentries _entry = null; _entry = new gasinfoentries(); _entry.gallons = txtboxgas.text; _entry.price = txtboxprice.text; _gaslist.add(_entry); //txtblockpricepergallon.text = (double.parse(txtboxgas.text) / double.parse(txtboxprice.text)).tostring(); // serialize our product class string string jsoncontents = jsonconvert.serializeobject(_gaslist); // app data folder , create or open file storing json in. storagefolder localfolder = applicationdata.current.localfolder; storagefile textfile = await localfolder.createfileasync("gasinfo.json", creationcollisionoption.openifexists); //if await operator error

sql - Mysql retrieving range between 2 max values -

i'm trying retrieve range of values between last row in table , row 40 rows above it: 2568, 2567, 2566, etc. query i'm using not getting done: select * posts front_weight between 'max(front_weight)-40' , 'max(front_weight)' from wording assume front_weight unique? if can use: select * posts order front_weight desc limit 40

javaScript object doesn't keep key order giving from php -

i have array use json_encode on looks in php array ( [4] => array ( [numberof] => 60 [date] => 4 ) [3] => array ( [numberof] => 3 [date] => 3 ) [2] => array ( [numberof] => 6 [date] => 2 ) [1] => array ( [numberof] => 5 [date] => 1 ) [12] => array ( [numberof] => 1 [date] => 12 ) [11] => array ( [numberof] => 0 [date] => 11 ) ) however, when accessing via javascript the order following { "1":{"numberof":5,"date":"1"}, "2":{"numberof":6,"date":"2&

I don't understand the concept of Ruby operators. What is the difference between '<' and 'xyz' method? -

class computation def initialize(&block) @action = block end def result @result ||= @action.call end def xyz(other) end def <(other) result < other.result end end = computation.new { 1 + 1 } b = computation.new { 4*5 } p < b #=> true p xyz b #=> `<main>': undefined method `xyz' main:objec i don't understand why '<' method works , 'xyz' method returns error ? in ruby < > + - etc operators, can call operators without dot, , off course can redefine operators (what doing here). in case of xyz string, , when called without dot ruby treats differently. a.xyz b evaluates a.xyz(b) a xyz b evaluates a(xyz(b)) , since global scope object , throw undefined method 'xyz' main:object

python - Local variable referenced before assignement -

this question has answer here: unboundlocalerror in python [duplicate] 8 answers i going crazy. simple callback function doesn't recognize variable assigned right before in it's parent scope. local variable 'elapsed' referenced before assignment error`. why? total = os.path.getsize(filename) elapsed = 0 def progress_print(chunk): elapsed += len(chunk) # elapsed apparently unassigned?? percent = float(elapsed) / float(total) * 100 print ' copied %s%%\033[a' % int(percent) ftp.upload(filename, temp_path, callback=progress_print) you're trying assign global. python makes explicitly that. def progress_print(chunk): global elapsed elapsed += len(chunk) in general pretty sign need refactor code until don't need globals more. note assignment , access different beasts - former requires explicitly

asp.net - MobilePin createuserwizard doesn't work? -

i new asp.net , first time using membership controls in project. here in project while creating new user need mobile number of user, how can enable mobilepin of createuserwizard. because saw mobilepin field in aspnet_membership table thinking can add values mobilepin field front-end while creating new user. can me? i did code doesn't work <asp:label id="mobile" runat="server" associatedcontrolid="mobilepin">mobile no:</asp:label> <asp:textbox id="mobilepin" runat="server" cssclass="textentry"></asp:textbox> <asp:requiredfieldvalidator id="requiredfieldvalidator1" runat="server" controltovalidate="mobilepin" cssclass="failurenotification" errormessage="mobile required." tooltip="mobile required." validationgroup="registeruservalidationgroup">*</asp:requiredfieldvalidator> how make mobilepin in asp.net me

C# Math.Round double .5 -

i have try math.round class. let see math.round(2.5) //2.0 math.round(-2.5) //-2.0 math.round(2.5,midpointrounding.toeven) // 2.0 math.round(2.5,midpointrounding.awayfromzero) //3.0 my simple question if change number -77777777.5 why result -77777778.0 not -77777777.0 math.round(-77777777.5) // -77777778.0 math.round(-77777777.5,midpointrounding.awayfromzero) // -77777778.0 math.round(-77777777.5,midpointrounding.toeven) // -77777778.0 thanks idea , suggestion. the default midpointrounding mode toeven . in mode, explained documentation (where a input value), the integer nearest a. if fractional component of halfway between 2 integers, 1 of , other odd, number returned. -77777777.5 has 2 nearest integers -77777777 , -77777778 latter 1 1 returned. in awayfromzero mode, -77777778 further 0 -77777777 .

c++ - Is it possible to run code on a "reserved" cpu core? -

simplified background: my app runs lot of tasks. of them cpu intensive. 1 task (which single thread running in loop, listening packets network), "realtime" task. make more interesting, thread native code called using pinvoke . the problem: when lot of traffic showing, tasks working hard, , cores maxing out. when happens, "realtime" thread (which runs on 100% cpu core), starts drop packets, because doesn't enough cpu time. the question: it possible somehow "reserve" 1 core "realtime" thread, , limit other threads (tasks) other cores? of course, there other processes running, consuming cpu time well, let's assume consume little , constant resources. this real problem can solved "throw more cpu on it"... not option... edit - answering many useful comments: we use winpcap capture packets, can many (many). the "realtime" thread not "realtime" (i think "realtime" processes - in .

Convert HTML Megamenu to Yii CMenu zii Widget -

i started working yii, , having trouble converting html megamenu yii. html this: <div class="nav-wrapper"> <div class="container"> <ul class="some_class"> <li class="active"><a href="#">parent 1</a> <div class="megamenu"> <div class="row"> <a href="#" class="overview">child 1</a> </div> <div class="row"> <div class="col1"> <ul> <li><a href="#">child 3</a></li> <li><a href="#">child 4</a></li> </ul> </div>