Posts

Showing posts from September, 2013

thorax.js - Javascript files are not getting loaded in rails production environment -

my application running on rails-4.1.2 , thorax.js front-end javascript framework. when added new thorax.js route , pages application, application dashboard page not getting loaded . , have no errors in production log. any appreciated.

java - Who is better in performance filechannel or RandomAccessFile for reading and writing? -

i came across filechannel , big fan of randomaccessfile . wondering why pick filechannel on randomaccessfile reading file , writing content another. is there specific performance reason? dont want use locking of filechannel purpose believe 1 of reasons why filechannel can used. don't want use bufferreader or suggested in other stackoverflow response. filechannel api says: region of file may mapped directly memory; large files more efficient invoking usual read or write methods.

rest - Elasticsearch security measures? -

i have set elk stack on single server , tested on small setup hands-down on elk. want use elk system logs analysis. now, have been reading es has no security. read this: "do not have es publicly accessible. that's equivalent of making wordpress mysql database accessible world. es rest accessible db means can delete of data access endpoint." i noob in this. means if put logs in es accessible (which scary) ?? please guide me security measures must taken? please suggest links can ensure security. how keep es cluster private? security real subject in elk stack . the initial position of elasticsearch : don't care security , self , acl hosts ..... with success of elk , demands security : elasticsearch realizing that's security real subject . they developping : http://www.elasticsearch.com/products/shield/ you can see : soon not released yet . so see 2 solutions : secure kibana : kibana hosted in webserver (apache , nginx) can add secur...

python - ipython notebook pandas max allowable columns -

i have simple csv file ten columns! when set following option in notebook , print csv file (which in pandas dataframe) doesn't print columns left right, prints first two, next 2 underneath , on. i used option, why isn't working? pd.option_context("display.max_rows",1,"display.max_columns",100) even doesn't seem work: pandas.set_option('display.max_columns', none) i assume want display data in notebook following options work fine me (ipython 2.3): import pandas pd ipython.display import display data = pd.read_csv('yourdata.txt') either directly set option pd.options.display.max_columns = none display(data) or, use set_option method showed works fine well pd.set_option('display.max_columns', none) display(data) if don't want set options whole script use context manager with pd.option_context('display.max_columns', none): display(data) if doesn't help, might give minimal exa...

mysql - convert column into rows based on another column -

Image
i have below table convert second column rows based on first column.please see below screenshots. base table: output table: since don't know total rows of columns needed apply dynamic sql. can't figure . can please me appreciated. thanks arfater

netcdf - Writing a netcdf4 file is 6-times slower than writing a netcdf3_classic file and the file is 8-times as big? -

i using netcdf4 library in python , came across issue stated in title. @ first blaming groups this, turns out difference between netcdf4 , netcdf3_classic formats (edit: , appears related our linux installation of netcdf libraries). in program below, creating simple time series netcdf file of same data in 2 different ways: 1) netcdf3_classic file, 2) netcdf4 flat file (creating groups in netcdf4 file doesn't make of difference). find simple timing , ls command is: 1) netcdf3 1.3483 seconds 1922704 bytes 2) netcdf4 flat 8.5920 seconds 15178689 bytes it's same routine creates 1) , 2), difference format argument in netcdf4.dataset method. bug or feature? thanks, martin edit: have found must have our local installation of netcdf library on linux computer. when use program version below (trimmed down essentials) on windows laptop, similar file sizes, , netcdf4 2-times fast netcdf3! when run same program on our linux system, can reproduce old resul...

php - Pass sanitized input as column name in where clause -

i have function accepts $filter argument , pulls data sql table based on filters in argument. @ first tried overloading function 1 function took single $filter variable , took array multiple filters. then, started wondering how sanitize filter tag. that may have been confusing here examples. example, user types in search box display users name john . so, $filter_tag set 'name' , $filter set 'john'. pdo query this: $query = "select `name` `users` "; $query .= $filter_tag." = ?"; the issue $filter_tag not sanitized. if sanitize , variable escaped, query not work. maybe making more complicated needs , there simple solution. please comment if not understand asking. you create whitelist of valid tags: if (in_array($filter_tag, ['name', ...], true)) { $query .= $filter_tag . = '?'; } alternately remove invalid characters, prefer whitelist approach, because there many valid column names :) lastly, instead ...

android - why my video doesnot fit the size of the texture as i change the size of the texture -

iam trying animate video rendered using texture view, animation works fine , when scale texture different size media player not scale fit size of texture,the video playing full screen in background , can see part of video when scale texture code works fine on android devices running android 4.0 not work on devices later versions of android . heres code animation kindly tell me problem .. public class mainactivity extends activity implements textureview.surfacetexturelistener{ animationset animset; textureview mytexture; mediaplayer mmediaplayer; surface s; int height; static final string logfilename = "log"; int width; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mytexture = new textureview(this); mytexture.setsurfacetexturelistener(this); setcontentview(mytexture); } @override public void onsurfacetextureavailable(surfacetexture arg0, int arg1, int arg2) { string mediastoragedir = environmen...

Get correct string position C# -

i have string: string str = "wishing {all great} day {ahead}. \n lot \n } \n {your} help!}" i read string line line. @ present have 4 lines me: 1. wishing {all great} day {ahead}. 2. lot 3. } 4. {your} help!} the intention check whether "}" closing brace of string , should not appear single character in of other lines. my approach this: in above string, want position of "}" in main string. , check whether there characters after position check whether closing brace. but iam unable correct position of "}" may appear in other lines well. is there better way go this? within single string, sounds should iterate on characters in string , keep count of how many opening , how many closing braces you've seen. this: int open = 0; (int = 0; < text.length; i++) { switch (text[i]) { case '{': open++; break; case '}': if (open > 0) ...

how to do Implementation of Android TvView -

i have started working on android smart tv. have make tvview, know leanback library gives lot of stuff work android smart tv. last day have tried work tvview perform streaming of channels. have included android-support-leanback17 . still getting error no class definition found. appreciated . want know library support tvview. in advance this logcat 11-27 09:25:10.684: e/androidruntime(16203): fatal exception: main 11-27 09:25:10.684: e/androidruntime(16203): java.lang.noclassdeffounderror: android.media.tv.tvview 11-27 09:25:10.684: e/androidruntime(16203): @ com.example.tvtest.mainactivity.oncreate(mainactivity.java:25) 11-27 09:25:10.684: e/androidruntime(16203): @ android.app.activity.performcreate(activity.java:5104) 11-27 09:25:10.684: e/androidruntime(16203): @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1080) 11-27 09:25:10.684: e/androidruntime(16203): @ android.app.activitythread.performlaunchactivity(activitythread.java:...

javascript - How to get the key of ajax response array in order to build up header of datatable? -

i have $.post query, retrieving json data ajax response. issue want load data in datatable , header of table need created dynamically. my json data comes in format: [{"id":"11105","name":"gummy drop (iphone, free, row except cn, 72.3mb, w"},{"id":"11107","name":"gummy drop (ipad, free, row except cn, 72.3mb, w\/ "},{"id":"4274","name":"z-redirect non-targeted traffic dragon city mobile"},{"id":"6484","name":"z-redirect non-targeted traffic dragon city mobile"}] as can see, 2 keys id , name . want 2 keys , use header column unable so. here's code: $(document).ready(function() { window.prettyprint() && prettyprint(); $('#load').click(function() { var v = $('#drp_v').val(); var cnt = $('#drp_cnt').val(); var ctg = $('#drp_ctg').val(); ...

How does strpos() function in PHP return int as well as boolean? -

this w3school says strpos() function : returns position of first occurrence of string inside string, or false if string not found. how function defined? possible write such functions returns values of 2 different datatypes in other languages well? many dynamically typed languages allow return whatever want function. typed languages don't. in php function can return anything wants, including booleans, ints, strings, null, arrays, kinds of objects, whatever need. it's same in example javascript , lua, dynamically typed. just make sure check return type of function if can different kinds of things. things int(0) , false, considered equivalent if use == comparison. use === make sure it's right type.

c - python-dev: how to change library architecture -

i trying use python-dev api running few issues. this code trying compile #include <stdio.h> #include <signal.h> #include <unistd.h> #include <python.h> int main(int argc, char *argv[]) { py_setprogramname(argv[0]); /* optional recommended */ py_initialize(); pyrun_simplestring("from time import time,ctime\n" "print 'today is',ctime(time())\n"); py_finalize(); return 0; } with gcc -c test.c `python-config --cflags` first of, have python 2.7.8 installed in (osx 10.9) computer. when run python-config --cflags output: -i/library/frameworks/python.framework/versions/2.6/include/python2.6 -i/library/frameworks/python.framework/versions/2.6/include/python2.6 -fno-strict-aliasing -fno-common -dynamic -arch ppc -arch i386 -g -o2 -dndebug -g -o3 so reason, though have python 2.7.8, python-dev api python 2.6. tried reinstalling python did me no good. secondly, reason python trying use power...

Batch fit image in Linux (e.g. GIMP) -

how can batch fit image under linux? please note explicitly ask batch fitting images independent of actual orientation of image (e.g. fit 800x600 px max, taken account different orientations of images). thanks in advance! you can solve task , many others imagemagick for example ls *.jpg | xargs -i'{}' convert -resize 800x600 -quality 80 {} {}

php - Get SQL Column Value value from Nested Array -

to explain better here code: $mydate=carbon::now()->addhours(8); $newdate=$mydate->todatestring(); $myquery = db::table('attendances')->where('date_only', '=', $newdate)->orderby('logon','asc')->get(); $counter=0; foreach ($myquery $newquery) { $query1[$counter]=$newquery->user_id; $finalquery[$counter]= db::table('employees')->where('id', '=', $query1[$counter])->get(); $counter++; } var_dump($finalquery[2]); the output of code this: array(1) { [0]=> object(stdclass)#160 (6) { ["id"]=> int(23) ["firstname"]=> string(3) "kim" ["lastname"]=> string(7) "samsung" ["position"]=> string(10) "programmer" ["created_at"]=> string(19) "2014-11-25 07:21:31" ["updated_at"]=> string(1...

Android Studio Google Cloud Endpoints Run/Debug Config Error -

i beginner android cloud endpoints. trying create backend module in android studio 1.0 rc2. seems okay while creating backend endpoint module ( https://github.com/googlecloudplatform/gradle-appengine-templates/tree/master/helloendpoints ). gradle builds successfully. when wanted debug locally, found problem. said, "app engine gradle configuration not detected on module, maybe need sync project gradle". i tried rebuild whole project, builds successfully. error remains. this screenshot: https://www.dropbox.com/s/tvuv52ldmr0yzvs/screen%20shot%202014-11-27%20at%204.21.14%20pm.png?dl=0 thank lot. this introduced bug has since been fixed in android studio 1.0.

ruby on rails - Carrierwave gem Secure File Path Cannot read file error -

i tried follow 'secure upload' in carrier wave bit confusing because have customized file path , bit. when try run app, 'cannot read file' error. here's route : match "/uploads/tobereviewed/:user.:username.downcase/:basename.:extension", :controller => "photos", :action => "uploaded", via: :get the sotre_dir of uploader : class submituploader < carrierwave::uploader::base def store_dir "uploads/tobereviewed/#{model.user.username.downcase}" end carrierwave.rb initializer : carrierwave.configure |config| config.permissions = 0600 config.directory_permissions = 0700 config.root = rails.root end photos controller : def uploaded file = submit.first send_file "#{rails.root}/uploads/tobereviewed/#{file.user.username.downcase}/#{file.id}" end the full error log : started "/uploaded" 127.0.0.1 @ 2014-11-27 18:19:09 +0530 processi...

java - Get request header in JSP Struts2 -

Image
i set header in action class. code follow: public string domyaction() { response.setheader("abc","cba"); response.addheader("abcdefg","1234567890"); return "target_page"; } at target_page.jsp, tried display header, value null. <%= request.getheader("abc") %> <-- null <%= request.getheader("abcdefg") %> <-- null <%= response.containsheader("abc") %> <-- true <s:property value="%{#request.abc}" /> <-- empty <s:text name="%{request.abc}" /> <-- empty <s:text name="%{#header.abc}" /> <-- empty <s:text name="%{#header['abc']}" /> <-- empty and in developer tools, there headers. in struts-config.xml, <action name="target_name" class="com.my.class"> <result name="target_page">/my/j...

html - title for td using fmt:message -

i want add 1 title 1 button inside 1 td of html table using fmt:message key="..." how can :i put in way gives me error data=data+"<td><button title="<fmt:message key="modifica.dettagli.attività" />" onclick='displaymodify("+rs.getstring(1)+")' style='border:none;background-color:transparent;background-image:url(../images/modify_20.png);width:20px;height:20px'></button></td>"; enter code here any appreciated

Nutch + HBase: hbase versions issue and java exception -

i'm trying setup nutch 2.2.1 using hbase 0.94.14, on debian squeeze. i've followed nutch 1 , 2 tutorials , various documentations. build hbase 0.94.14, , got work (i can create tables etc.) build nutch without issue (it's set on gora 0.3) now issues are: 1- when trying launch nutch, following trace: ./nutch inject /root/nutch/apache-nutch-2.2.1/urls/ injectorjob: starting @ 2014-11-27 09:43:53 injectorjob: injecting urldir: /root/nutch/apache-nutch-2.2.1/urls injectorjob: java.lang.classnotfoundexception: org.apache.gora.memory.store.hbasestore @ java.net.urlclassloader$1.run(urlclassloader.java:372) @ java.net.urlclassloader$1.run(urlclassloader.java:361) etc. using strace -f, i've figured out "hbasestore.class" not found: stat("/root/nutch/apache-nutch-2.2.1/runtime/local/org/apache/gora/memory/store/hbasestore.class",\ <unfinished ...> [pid 1827] <... futex resumed> ) = -1 eagain (resource temporarily un...

osx - Do not receive echo-reply from ping request with scapy -

i use scapy , try make ping , receive reply. my_ping = ether() / ip(dst='8.8.8.8') / icmp() rep,no_rep = srp(my_ping) the problem don't receive answer. ping 8.8.8.8 works using terminal. i've problem on mac (os x 10.10 yosemite) , on ubuntu vm installed on mac. however, commands work on aws ubuntu machine. if has clue... feel free answer

java - download class from http://docs.spring.io/ -

i need download java class: http://docs.spring.io/spring-framework/docs/2.0.8/api/org/springframework/jdbc/object/storedprocedure.html but can't find download, clicked everywhere upon website. can me find code? it's accepted other website or link code of class. this class spring framework, download spring library, try download following spring library add project, do: import org.springframework.jdbc.object spring framework accessible here and direct link jar file of class accessible link: org.springframework.jdbc-3.0.1.release-a i hope you, best regards

sql - PostgreSQL : How to select values with only two digits after decimal point in a table? -

i have table called nums . create table nums (num numeric); insert nums select * (values(10.11),(11.122),(12.22),(13.555)) t; it have following rows select * nums num -------- 10.11 11.122 12.22 13.555 so question how values 2 digits after decimal point( . )? expected output :- num -------- 10.11 12.22 you can try pattern matching select * nums num::text ~ '(^\d+(\.\d{1,2})?$)'; or mathematical functions , operators - floor select * nums floor (num*100)=num*100

php - How do I put this array into csv or excel? -

Image
i can't figure out way , bad working arrays hope can me. i have array $stuck contains names, $stuck = array('daniel','alex','alfredo','dina'); i using sort put names in alphabetical order, this sort($stuck); now thing want put array csv or excel file first letter of name title , names letter under title. this example of trying accomplish here try this. added comments between code. $csvarray = array(); $namearray = array('daniel','alex','alfredo','dina'); //create array can used creating csv foreach($namearray $name) { $firstletter = strtoupper(substr($name, 0,1)); $csvarray[$firstletter][] = $name; } //determine subarray have must rules $maxrulecount = 0; foreach($csvarray $firstletter => $namearray) { if(count($namearray) > $maxrulecount) { $maxrulecount = count($namearray); } } //create first rule (letters) $csvcontent = implode(';', array_keys...

java - WebSocket in Javascript not connecting to servlet -

i trying use javascript websockets connect java servlet, onerror function being called, , not providing information. javascript: var websocket = new websocket('ws://localhost:8080/test'); websocket.onerror = function(event) { onerror(event); }; websocket.onclose = function(event) { onclose(event); }; websocket.onopen = function(event) { onopen(event); }; websocket.onmessage = function(event) { onmessage(event); }; function onclose(event) { var code = event.code; var reason = event.reason; var wasclean = event.wasclean; alert(code + "; " + reason + "; " + wasclean); } function onmessage(event) { //do stuff } function onopen(event) { websocket.send('opening socket'); } function onerror(event) { alert(event.message); } for servlet, have @serverendpoint("/test") public class transcodersnsservlet extends httpservlet { ... } the useful error codes i've been able find event.code = 1006...

sql server - How to add an extra column to handle error message in a SSIS data flow? -

Image
i'm working on ssis project in order import calls rows (excel file) in sql server database. here data flow : i added lookups check rows before import process. first 1 checks if row exists (made prevent duplicates because user drag & drop import files in specified folder). others lookups check foreign keys constraints. moreover, no matching rows redirected database. i'm able check invalid rows, audit package let me know if nomatchingrowscall table changed during inport. now, add "error message" no matching rows check "what problem row ?". think add "derived column after each lookup (no matching output) add error message. way ? how add text content in "derived column" ? should use package variable ? here : id | c1 | c2 | c3 | error_message 1 | .. | .. | .. | row exists 2 | .. | .. | .. | fk error column c1 3 | .. | .. | .. | fk error column c2 ... i want "soft" solution track failing rows without stop package e...

rounding - PHP round function returned a weird result -

i execute simple script round(8.32, 1) in cgi, returns 8.300000000000001. when execute in cli php -r "echo round(8.32, 1);" , result 8.3 expected. php version 5.6.2. you have different settings of precision in config. ini_set('precision', 10); var_dump(round(8.32, 1)); // double(8.3) ini_set('precision', 20); var_dump(round(8.32, 1)); // double(8.3000000000000007105) why happens read here: http://en.wikipedia.org/wiki/ieee_floating_point

git - How to review code in existing github repositories? -

i want go , review code in existing github repository. is possible? if possible, how should 1 it? go commits of repository, open commit clicking on hash. when hover on code little '+' button appears near line numbers. click on add comment line. can write general comments @ bottom of commit page.

jQuery - Find .attr of the last-child element -

i'm trying jquery .attr("msg_g") of last-child element <div id="append"> <div class="h" msg_g="1">a</div> <div class="y" msg_g="2">b</div> <div class="h" msg_g="3">c</div> </div> i'm pretty sure script below must work returns me undefined var msg_g = $( "#append div:last-child" ).attr( "msg_g" ); console.log(msg_g); i use script below checking if last-child 'hasclass' , works perfect, why doesn't work on .attr() example .hasclass() if($( "#append div:last-child" ).hasclass( "y" )){ var last_msg_class="by_you"; }else if($( "#append div:last-child" ).hasclass( "h" )){ var last_msg_class="by_friend"; } instead of adding msg_g attribute,try using data-* attribute. modify html :-- <div id="append"> <div...

How can I disable xml header generation in Spring Integration's xpath-splitter component -

my problem <xpath-splitter> si component generates fragments xml-header theoretically can disabled setting omit-xml-declaration property of underlying transformer "yes" how can that? how can set property when use <xpath-slitter> ? thanks h-m. can like: transformerfactory tf = transformerfactory.newinstance(); transformer transformer = tf.newtransformer(); transformer.setoutputproperty(outputkeys.omit_xml_declaration, "yes"); but don't have access transformer xpathmessagesplitter . i think 1 more request implement 1 https://jira.spring.io/browse/int-2042 . will difficult right workaround provide input payload <xpath-splitter> node instead of string , result list<node> . after can provide custom <transformer> code: transformer transformer = transformerfactory.newinstance().newtransformer(); transformer.setoutputproperty(outputkeys.omit_xml_declaration, "yes"); stringresult result = new st...

javascript - Two column webpage, menu loading seperate HTML files with Jquery -

it sounds simple none of find on google worked far. i've found similar question on here solution looks i'm looking for: http://jsfiddle.net/sj6bj/4/ here's html: <html> <head> <title>two-pane navigation</title> </head> <body> <div id="content"> <div id="navigation"> <h1>navigation</h1> <ul> <li><a href="#page1" class="page-link">page 1</a></li> <li><a href="#page2" class="page-link">page 2</a></li> </ul> </div> <div id="pages"> <div id="page1" class="page"> <h1>page 1</h1> <p>this lovely content on page 1.</p> ...

ios - JQuery manipulate div width on iPad / iPhone -

i have number of divs change 0 variable width. doesn't work on ipad/iphone; divs stay @ 0 get html: var items = { item1:22, item2:55, item3:88, item4:36 }; (var key in items ){ $('.bars').append("<li><div data-percentage='"+items[key]+"' data-title='"+key+"' class='bar'></div></li>"); }; display function animate(){ $(".bars .bar").delay(1000).each(function(i){ var percentage = $(this).data('percentage'); $(this).delay(i+"00").animate({'width': percentage + '%'}, 700); }); } i've tired changing animate width & css doesn't work. why seem happen on apple devices? any solutions? thank solved! problem css nothing jquery animate

c - Segmentation fault 11 on boolean method -

i'm trying use method return 1 true , 0 false, gives me "segmentation fault: 11" if returns false. i've been janking brain trying figure out i'm messing can't seem find anything. here's code. first call function int delete_number; printf("select number remove list?\n"); scanf("%i", &delete_number); if(remove_num(delete_number)) { printf("deleted %i ", delete_number); } else { printf("number %i not found in list", delete_number); } now function itself int remove_num(int data) { int result = 0; node *curr_ptr; node *prev_ptr; node *temp_ptr; if(queuer.first != null) { if(queuer.first->data == data) { temp_ptr = queuer.first; queuer.first = queuer.first->next; if(queuer.first == null) { queuer.last = null; } free(temp_ptr); result = 1; }...

initialization - Can't initialize int at 0 in c -

i'm making program image treatment , have variables initialized: int minr, ming, minb = 255; int maxr, maxg, maxb = 0; printf("%d", maxg); and when print this, instead of getting 0 should be, 16384 value of maxg. yet, if this: int minr, ming, minb = 255; int maxr, maxb = 0; int maxg = 0; printf("%d", maxg); then goes ok. does know why be? thank you. the initializer applies 1 declarator follows, not of other declarators in list! so int = 10, b, * c = null; initializes a , c , b remains uninitialized. (by way, reading uninitialized variable has undefined behaviour .)

sql - Display data from database using explode in php -

i have table named "test". retrieve data 1 column. each row have multiple data separate coma. how can display data of column in drop-down? id | qualification 1 | be,phd,me 2 | mca,mba 3 | mba how can display data of qualification column in dropdown? output should following be phd me mca mba mba loop throught rows , create array of each row exploding rule. merge arrays together. this: //example data todo: replace table data $rows[0]['qualification'] = 'a,b,c'; $rows[1]['qualification'] = 'a,b,c'; $qualificationarray = array(); foreach($rows $rowdata) { $rowdataarray = explode(',',$rowdata['qualification']); $qualificationarray = array_merge($qualificationarray,$rowdataarray); } then use qualificationarray create dropdown echo '<select name="qualification">'; foreach($qualificationarray $qualification) { echo '<option value="'.$qualification....

jquery - PHP Header Location not working With BootStrap 3 [Normal header location working fine] -

this question has answer here: how fix “headers sent” error in php 11 answers i facing php header redirection issue bootstrap, please find code below, index file: <?php if(!isset($_session)){ session_start(); } include("db.php"); ?> <html> <head> <title> </title> <!-- jquery imports <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>--> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- latest compiled , minified css --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1 /css/bootstrap.min.css"> <!-- latest compiled , minified javascript <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstr...

Android action bar slide-out animation with RecyclerView -

i want achieve following effect: i have recyclerview android:fitssystemwindows="true" android:cliptopadding="true" and while scrolling, actionbar should hide sliding out of screen when "hit" element of recyclerview. if being pushed out of screen recyclerview element. (so actionbar.hide() won't do). if scroll stops actionbar having been pushed halfway out, should hide completely. actionbar should reappear when scrolling down again. all in same effect of action bar in newsstand app.

mysql - Php- Check string is either a decimal or fractions -

i have input box users can type in odds bet. can either in form of decimal -> 1 or 6.2 ect or fraction e.g 5/1 or 13/2 ect what best way check these input? i think regex best way this if(preg_match("@^\d*\.?\d+(/\d*\.?\d+)?$@", $value)) { echo "$value valid"; } this regex allow : .1 | 2.0/54 | 2.3 | .5/.8 | 8/7 | 85.98 | ..... if need , character (for language use it) "@^\d*[\.,]?\d+(/\d*[\.,]?\d+)?$@"" edit fixed "4/" case

javascript - jQuery change/toggle classes between buttons from inside PHP loop -

i have set of 2 buttons inside loop. <button class="dislike-btn" data-id="dislikebtn-1>">dislike</button> <button class="like-btn" data-id="likebtn-1">like</button> <br /> <button class="dislike-btn" data-id="dislikebtn-2">">dislike</button> <button class="like-btn" data-id="likebtn-2">like</button> <br /> <button class="dislike-btn" data-id="dislikebtn-3">">dislike</button> <button class="like-btn" data-id="likebtn-3">like</button> the desired functionality 1 button in each set/iteration selected, achieved adding/removing class ( .dislike-btn-solid .dislike-btn , .like-btn-solid .like-btn ) other button. in other words, if user clicks "like" .like-btn-solid added .like-btn , if .like-btn-solid selected on .dislike-btn before remove it. i'...

javascript - How do i pass a variable to a nested function? -

this question has answer here: how generate event handlers loop in javascript? [duplicate] 3 answers i have started use createjs , have come problem (which doesnt have t odo createjs): for (a in ship.weapon) { //code button[a].addeventlistener("click", function() { ship.weapon[a].amount = ship.weapon[a].amount.plus(1); }); //code } the "a" variable ofcourse @ time button pressed lenght of ship.weapon array. how make "a" inside click function stay @ value of loop when made? you can use closure freeze a value for (a in ship.weapon) { (function(index) { button[index].addeventlistener("click", function() { ship.weapon[index].amount = ship.weapon[index].amount.plus(1); }); })(a); // calls function defined passing 'a' parameter }

android - Display object is not recognised by eclipse -

i reading this question , when tried display display = ((windowmanager) getsystemservice(window_service)).getdefaultdisplay(); eclipse underscored red line though have imported required libraries

Mysql join query on two tables with multiple colums but redundant many times -

i have 2 tables this: studentanswer stunum | quiznum | questionid | stuanswer ------------------------------------------ 2012 | 1 | 15 | optiona 2013 | 1 | 15 | optionb 2012 | 2 | 16 | optionc 2012 | 2 | 17 | optiona 2012 | 2 | 18 | optionb questionquiz quiznum | questionid | question | correctans ---------------------------------------------------- 1 | 15 | sql | optiona 2 | 16 | web | optionc 2 | 17 | android | optiona 2 | 18 | math | optionb i want result : question | correctans | stuanswer ------------------------------------- web | optionc | optionc android | optiona | optiona math | optionb | optionb i want stuanswer based on stunum=2012, quiznum=2 i tried code loop 3 times select b.stunum , b.quiznum , b.questionid , c.question , c.correctans , c.markqui...

datetime - Python 3.4: how to add zero milliseconds and change their formatting -

i need format datetime displayed in following way: "2014-06-04 12:05:10.000", "2014-06-04 12:05:10.250", "2014-06-04 12:05:10.500", "2014-06-04 12:05:10.750". my current datetime "2010-01-01 12:05:10.250000", , it's sum of initial datetime , incrementing timedelta: delta = datetime.timedelta(hours=0, minutes=0, seconds=0, milliseconds=250) time = (date_initial + delta) here 2 questions: 1). how add "000" when there no milliseconds (i mean adding whole seconds), otherwise face "index out of list" error when trying smth milliseconds part datetime_split = str(time).split('.') date_2 = datetime_split[1] is there shorter , cleverer way add ".000" milliseconds other loop "split -- if there right of "." -- if no, add ".000". additional problem here string format instead of datetime. 2). how change milliseconds formatting ".250000" ".250...

php - Round only int of variable -

i busy webshop, , have issue: i display quantity of products, , attribute of product. like: 2,4 cm 2,56 dm now want round numbers of variable, if use: $qty = round($_product->getbundle_qty()); but if use: $aantal = $_product->getbundle_qty(); works okay, doesn't round. then attribute doesn't show anymore ( dm, cm, m etc) can me? is $_product->getbunlde_qty() double or float? or string? in case, can use: $qty = round(floatval($_product->getbundle_qty())); edit: if want keep cm / dm in behind string can take string , explode @ spaces, creating array string. last value in array 'cm' or 'dm' text. $qtypieces = explode(" ", $_product->getbundle_qty()); //explode @ space $qtypiecescount = count($qtypieces); //count pieces $qty = round(floatval($_product->getbundle_qty())) . " " . $qtypieces[$qtypiecescount - 1]; //get last value in array, count minus 1 because start counting 0

javascript - jQuery selector eq:() not working -

i made toggle button pure css/jquery , works perfectly. problem comes when duplicated , tried toggle it. supposed, toggles 'toggled' @ same time, here code far: html <div id="container"> <div id="switch-1"><div class="light-1"></div><div class="switch"><div class="space"><div class="circle"></div></div></div><div class="light-2"></div></div><br><br> <div id="switch-2"><div class="light-1"></div><div class="switch"><div class="space"><div class="circle"></div></div></div><div class="light-2"></div></div> </div> jquery $(function(){ $('.space').click(function(){ if($('.circle').hasclass("detector")){ ...

haskell - How can I constraint QuickCheck parameters, e.g. only use non-negative ints? -

i'm new haskell. it's nice far, i'm running copy-pasting quickcheck properties, , i'd fix that. here's made-up example: prop_myfunc :: [int] -> (int,int) -> bool prop_myfunc ints (i,j) = ints !! == ints !! j this won't work because quickcheck generates negative numbers, get *** failed! (after 2 tests , 2 shrinks): exception: prelude.(!!): negative index i've tried google solutions this, , i've found e.g. nonnegative , ==>, don't understand how work. how can restrict above example , j never negative? , also, neither high? is: 0 <= i,j < length ints constraining wrappers (from test.quickcheck.modifiers , if aren't reexported implicitly) can used in way: prop_myfunc :: [int] -> (nonnegative int, nonnegative int) -> bool prop_myfunc ints (nonnegative i, nonnegative j) = ints !! == ints !! j you can treat somewrapper a a modified distribution. example, nonnegative a ...

Resque Capistrano Deployment in Rails -

i have rails 3.2.20 app i'm introducing resque environment background job mail , sms alerts. have setup in development , i'm point of preparing merge branch , push staging , production testing. have few questions. 1.) how memory need run resque in production (approximately). understand starting resque worker loads full environment. i'm bit tight on memory , don't want have issues. i'll using single resque worker our email/sms traffic light , don't mind queues being backed few seconds minute. know question vague, i'd feel memory footprint resque requires. 2.) have redis running need figure out how start resque worker on deployment kill existing resque worker. i've come following add cap after deploy action. task :resque_restart run "kill $(ps aux | grep 'resque' | awk '{print $2}')" run "cd #{current_path}; bundle exec rake resque:work queue=*" end i haven't tested capistrano 2 (which i'm...

MYSQL find corresponding value in a range of values -

i have problem how find corresponding value ... i have table structure this: (column-names -> column_headers (except first one) contains "range") value | value_level_1 | value_level_2 | ... | value_level_n | so table looks like: value | 0 | 10 | 20 | 50 | 100 | 500 | 1000 | final_value | ------------------------------------------------------------------------------ 15 | 1 | 0 | 3 | 5 | 0 | 0 | 0 | = 15 * (1/100) | 246 | 2 | 0 | 4 | 0 | 6 | 8 | 0 | = 246 * (6/100) | etc ... in first column, value (for example price) , others % value .. commission schema .. what need do, find highest range (by value), value achieved .. , grab it's percentage value count final column (final_value) ... formulas in example above... to make difficult :) first row, should 3rd column (10), because hights value achieved (to achieve 20 needs increased 5) .. sql should take value (=0%) ...