Posts

Showing posts from August, 2014

ruby on rails - jQuery character count onkeyup showing 1 character when 0 left -

i'm using jquery show characters remaining in text input , it's working fine when gets 0 characters remaining showing 1 though doesn't allow enter more. obvious , simple, it's stumping me today. here code i'm using: = form.text_field :name, { required: true, class: "#{'error' if @project.errors[:name].present?}", placeholder: '40 characters max', maxlength: 40, :onkeyup => "countcharname(this)" } span id="charname" class="margin-left-5" function countcharname(val) { var len = val.value.length; if (len >= 40) { val.value = val.value.substring(0, 40); } else { $('#charname').text(40 - len); } }; without testing it, assumption when reaches max length, input length 40. means if statement (len >= 40) true, else statement, updates $('#charname') remaining characters, doesn't run. try changing if statement (l

geospatial - How can I query a MongoDB collection by both a geo spatial index and a text index quickly? -

given collection locations consisting of ~20,000,000 documents 3 properties: { _id, name, // string geo // coordinate pair, e.g. [-90.123456, 30.123456] } and index of name: 1 , geo index setup so: { "geo" : "2dsphere" }, { "v" : 1, "name" : "geo_2dsphere", "ns" : "db.locations", "min" : "-180.0", "max" : "180.0", "w" : 1.0, "2dsphereindexversion" : 2 } how can performantly query against collection both on geo_2dsphere index , on name index? when run $box query on geo index only, takes on 20 seconds return 50 results. when include search against name property goes further. if run $near query, things can perform quickly, queries seem (very randomly) go ~200ms many seconds. see example difference 1 additional character on name index increases time: 200ms: {name: /^mac/, geo: {$near

javascript - Order function call -

i need make submitadapterauthentication() function work first getuserroles() function, current implementation of getuserroles() function being executed first submitadapterauthentication() . how can fix this? checkonline().then(function(onl) { userobj.isloginonline = onl; }).then(function() { submitadapterauthentication(user, pass); }).then(function() { getuserroles(); }); function submitadapterauthentication(user, pass) { var invocationdata = { parameters : [ user, pass ], adapter : "adapterauth", procedure : "submitlogin" }; ch.submitadapterauthentication(invocationdata, { onfailure : function(error) { wl.logger.log("error on fail: ", error); }, onsuccess : function() { wl.client.updateuserinfo({ onsuccess : function() { //return promise wl.client.updateuserinfo({

python - I have five variables that will have different values based on whether they are in Alaska/US and at half/full resolution -

question appropriate data structure: i have 5 variables have different values string based on whether in us/alaska , @ half/full resolution. so i'm building 5/2/2 (array or list or dict). i want access x = dstr(var,'ak','h') , e.g.. alaska/half-res, values osp/ul/lr/etc, variables? this static table, values won't change. there no obvious ordering demand 0,1,2 indices problem is, array doesn't string indices , dict wants 1 key only, not three. any ideas? you can use tuples index dict: >>> values = { ... ("ak", "h"): ("some", "sample", "data", "to", "return"), ... ("ak", "f"): ("more", "sample", "data", "for", "you"), ... # more data here ... } >>> a, b, c, d, e = values[("ak", "h")] >>> "some" or can use nest of dicts:

sql - i have a error in joomla - query please. i have and error in this query -

$datos = explode(';',$linea); $product_ean = trim($datos[0]); $product_price = trim($datos[1]); $name_es = trim($datos[2]); $short_description_es = trim($datos[3]); echo $product_ean,'<br>'; echo $product_price,'<br>'; echo $name_es ,'<br>'; echo $short_description_es,'<br>'; $db = jfactory::getdbo(); $query = $db->getquery(true); $columns = array('product_id' ,'product_ean', 'product_price', 'name_es-es', 'short_description_es-es'); $values = array(null, $product_ean, $product_price, $name_es, $short_description_es); $query ->insert($db->quotename('vrg_jshopping_products')) ->columns($db->quotename($columns)) ->values(implode(',', $values)); $db->setquery($query); $db->execute(); error displaying error page: application instantiation error: have e

node.js - KoaJS how to get files from multipart form data? -

when post multipart form, <form name="acount_manage" action="/update" enctype="multipart/form-data" method="post"> <input type="file" name="file"> </form> it throws: error: unsupported content-type: multipart/form-data @ object.<anonymous> (e:\...\node_modules\co-body\lib\any.js:51:15) any.js: /** * module dependencies. */ var json = require('./json'); var form = require('./form'); var text = require('./text'); var json_content_types = [ 'application/json', 'application/json-patch+json', 'application/vnd.api+json', 'application/csp-report', 'application/ld+json' ]; /** * return a thunk parses form , json requests * depending on content-type. * * pass node request or object `.req`, * such koa context. * * @param {request} req * @param {options} [opts] * @return {functi

mysql - Combine Two Select Statements Using UNION -

i learning sql statements, cannot see why code cannot execute database: (select time mytable) union (select travel mytable); the above statement forbidden. it not columns called time , travel of same datatype... when union 2 select statements, putting 2 values in same column. sql not know type make column. likely, sees time values, makes column datetime column, start trying cram travel varchar strings it. try casting both same type, this: select date_format(time, '%y-%m-%d %h:%i:%s') time mytable union select travel mytable;

data lost with both ckeditor and tinymce editor in asp.net mvc5 with very large texts/images -

i facing strange behavior ckeditor/tinymce editor in asp.net mvc5, razor application. when save large data above 10 mb of size fails store data, truncates large part of it, , not give error, behavior strange, , not able find solution, changes editor ckeditor tinymce, problem remained same. even behavior not static, works larger data, fails of sudden without error. i not sure problem, editor, or mvc controller function in receiving such large data etc, again goes , misbehaves that's crazy. on further analysis found javascript editors tinymce of ckeditor not capable of handling such large data , that's why doing such strange behavior. test further deployed our application on server better processor, , more ram our existing server, , things went well. behavior of dramatically losing data while posting has been strange us, @ least should give error or exception, or should not work together.

How to get random element from multidimensional array in php -

i have multidimensional array composed post variables looks this: $easys = array( array($easy1min,$easy1max,$easy1enc), array($easy2min,$easy2max,$easy2enc), array($easy3min,$easy3max,$easy3enc), array($easy4min,$easy4max,$easy4enc), array($easy5min,$easy5max,$easy5enc), array($easy6min,$easy6max,$easy6enc), array($easy7min,$easy7max,$easy7enc), array($easy8min,$easy8max,$easy8enc), array($easy9min,$easy9max,$easy9enc), array($easy10min,$easy10max,$easy10enc) ); i'm attempting return 1 randomized result this. my function trying shuffle looks this: $shuffle($easy_encounters); $num = rand($easy_encounters[0][0],$easy_encounters[0][1]); return "(".$num.") ".$easy_encounters[0][2]; gives "shuffle expect parameter 1 array.." i have tried iterator_to_array: $easy_encounters = iterator_to_array($easy_encounters); which returns error "catchable fatal error: argument 1 passed iterator_to_array() must implement interface trave

ios - `NSPersistentStoreCoordinator removePersistentStore:` hangs when using permanent object IDs -

i came across issue in our application caused use of temporary nsmanagedobjectids . in response network requests, mapping operation inserts managed objects private queue moc, saved way root moc (the 1 persistentstorecoordinator assigned). we aware not obtaining permanent ids may cause issues, hadn't come across problems, stuck it. i stumbled across issue temporary ids , made switch obtain permanent ids. clear: every time insert new objects part of our mapping operation, obtain permanent ids. the issue solved, happy days! not fast... under ios 7.1 (8.4 works fine), calls nspersistentstorecoordinator removepersistentstore: hang, indefinitely. part of our core data stack teardown when user logs out (to clear data). here's relevant code our persistence manager: - (void)reset { fcyweakifyself; [self.managedobjectcontext performblockandwait:^{ fcystrongifyselfinto(strongself); strongself.managedobjectcontext = nil; strongself.persisten

c# - Parents child threads not exiting properly -

need little regarding multithreading. doing computation in separate threads in unity , rendering result when threads completed. below structure of code. thread 1 | | thread 1.1 thread 1.2 | | thread 1.1.2.1 thread 1.2.1.1 thread 1.1.2.2 thread 1.2.2.2 ... ... every time thread 1.1 , child (thread 1.1.2.1..) exits using join() not case thread 1.2; thread 1.2.1.1.. exits without completing code block. looks join() on childthreadlist not blocking current thread in case of thread 1.2. code simple making blocks of large list , process them in parallel. having same issue thread 1.1 , thread 1.2 exits in midway; reason sharing same variable values when on .start(). make sure not reason now. is there mistaking or missing, please advice. example code: //running in thread 1; started main() private unsafe void addsurfacedata() { float* points; int points_length; float* colours; int colours_len

sql - Select two records where a two way relationship exists -

i have user table contains user id , name. i have likes table contains userid1 , userid2. when user1 likes user2, ids entered in likes table respectively. how can retrieve users both each other? join likes table , select rows mutual likes: select * likes like1 inner join likes like2 on like1.userid1 = like2.userid2 , like1.userid2 = like2.userid1

Plotting colours in R according to values -

i have dataframe columns x , y , value. using ggplot2 plot values @ specified coordinates. wish fill colour based on custom ranges value column. example : value colour 0 2 blue 2 5 green 5 10 red 10 20 yellow 20 30 orange 30 40 grey >40 black how fill specific colour particular values using ggplot2 ? i can resample data if required , map individual resampled value colours after that, example : value resampled value colour 0 2 10 blue 2 5 20 green 5 10 30 red 10 20 40 yellow 20 30 50 orange 30 40 60 grey >40 70 black but values not getting mapped colours code : ggplot2::ggplot() + ggmap::theme_nothing() + ggplot2::geom_tile(data = xydataframe, alpha = 0.6, aes(x = x, y = y, fill=value)) + ggplot2::scale_fill_gradientn(colours = c("blue", "green", "red", "yellow", "ora

c++ - Windows process exit codes in the event of term signals -

in unix/linux environments quite easy determine whether program has exited due signal interrupt (sigterm), , signal interrupt. it possible determine (programmatically using api's or exit code) whether windows program has exited due signal (sigkill, powershell example)? to expand on question: is possible user kill application e.g task manager, or powershell? ?? if application unresponsive , os kills application, exit code be? ?? windows has "many, many" error codes, , want know ones relate process management only. kind regards, no there not since windows not have signals. terminating process happens using terminateprocess api. terminateprocess caller pass in exit code, there no documented value powershell or task manager set to. windows not define process exit codes, application may use exit codes wants. there no "process management error codes" check for. to answer questions directly: is possible user kill application e

java - How do I force a ExecutorService.awaitTermination() timeout? -

the code-under-test executes set of callable objects via executorservice.invokeall() . executorservice thread pool shutdown() , awaittermination() called. executorservice threadpool = executors.newfixedthreadpool(healthchecks.size()); list<future <healthstatus> > checkresults = threadpool.invokeall(healthchecks); threadpool.shutdown(); // wait threads finish part of shutdown. if (!threadpool.awaittermination(status_check_timeout_seconds, timeunit.seconds)) { throw new exception("health checks did not complete in time."); } i want unit test awaittermination() timeout. now, can inject own set of callable objects run , created 1 cause timeout. class object looks (using concurrentunit.waiter object): public static final class timeouthealthcheck implements healthchecker { public final long sleepintervalmillis; string healthname; boolean result; waiter waiter; public timeouthealthcheck(long timeoutinmillis, boolean result

unix - Simple bash/script formatting tool, for paragraph text inside the script? -

context: know how type sentences in word processor, , don't have special formatting if insert new sentence in paragraph, or make existing sentence longer or shorter? i'm writing paragraphs document given script does, inside it. want able output when user invokes script "-help", etc option, not have adjust echo or printf statements everytime add sentence, or make 1 longer or shorter. how can that? i'm willing make output 80 columns or fixed width. edit reader: answers informative found. you use widely-available fmt utility. if have gnu coreutils (which if using linux), can use the gnu version . there very similar utility available on many bsd systems, including mac os x. here's simple example, should work either of implementations. note second paragraph indented 2 spaces, , indentation preserved: description="\ lorem ipsum dolor sit amet, consectetur adipiscing elit. aenean ornare leo non dolor porttitor euismod. cras commodo

javascript - <Select> widget with infinite scroll dropdown -

at page have 20 common html select widgets. example: <select> <option>1</option> ... <option>3000</option> </select> that have 3000 or more elements in each one. have decided convert them ajax selects load items dynamically when scrolling. how can ?? i have provided set of working example of combo-box using jquery ui selectmenu . have used basic json source ajax request, please work on part yourself. $(".ajax-combo").selectmenu({ "width": "100px", }); $(".ajax-combo").selectmenu("menuwidget").addclass("make-scrolling"); $(".ajax-combo").selectmenu("menuwidget").scroll(function(e) { if (e.currenttarget.scrollheight - 10 < e.currenttarget.scrolltop + $(e.currenttarget).height()) { var curtar = e.currenttarget; var lasttop = curtar.scrolltop; $.getjson("http://echo.jsontest.com/10/test/20/rest/30/best/40/v

Java Set and Get variable in other function -

i'm trying variable function in same .java file. this example: public static void showwindow(user user) { string checklist = null; if (user.getnetconnection().getbonus() >= 0.) { checklist = "variable1"; } else { checklist = "variable2"; } showcommunity(user, checklist); } private static void loadsingle() { allsingle = new linkedlist<>(); try (connection con = databasefactory.getinstance().getconnection(); preparedstatement statement = con.preparestatement(checklist); resultset rset = statement.executequery())...(the rest of funcion here) there anyway use variable checklist function showwindow inside function loadsingle? not sure if made typo or what, defining variable checkbufflist never using. if in fact typo, should able defining static variable , getter, this private static string checklist; public static string getchecklist(){ return checklist; }

exception - Class yii\debug\Module does not exist -

i trying run yii2 application on vagran virtual machine. provison use ansible. here ansible playbook file: --- - hosts: vagrant sudo: true tasks: - name: 1. install apache apt: name=apache2 state=present - name: 1.1 delete temporary file file: path=/var/www/web/index.html state=absent - name: 2. install php module apache apt: name=php5 state=latest update_cache=yes - name: 3. install php gd library apt: name=php5-cli state=latest - name: 4. start apache service: name=apache2 state=running enabled=yes - name: 5. install mysql apt: pkg=mysql-server state=present - name: 6. install python-mysqldb apt: pkg=python-mysqldb state=present - name: 7. install php mysql bindings apt: pkg=php5-mysql state=present - name: 8. restart apache service: name=apache2 state=restarted - name: 9. set mysql root password debconf: name='mysql-server' question='mysql-server/root_password' value='password' vtype='password' - name: 10. confi

Add similar IFS function to query with sub-query (oracle sql) -

this part of query. want add column called missed if impact label 1 , hours > 8 -> missed, impact 2 hours > 14 -> missed , impact 3 hours > 80 -> missed. please help. thanks! select o.create_datetime ,o.resolved_datetime ,24 * (to_date(resolved_datetime, 'yyyy/mm/dd hh24:mi:ss') - to_date(create_datetime, 'yyyy/mm/dd hh24:mi:ss')) hours ,o.item ,o.impact_label (select ,to_char(create_date,'yyyy/mm/dd hh24:mi:ss') create_datetime ,to_char(resolved_date,'yyyy/mm/dd hh24:mi:ss') resolved_datetime ,status ,(case impact_label when '1 - ' '1' when '2 - ' '2' when '3 - ' '3' when '4 - ' '4' when '5 - ' '5' else null end) impact_label table )o i'd re-write using "with" clauses, that's me .. :) need layer in ther

javascript - Should I put a Google sign in button on every page? -

i have built quite simple site users sign in google sign in button on index page. after verifying token etc, php session created, carrying google user id page page in order identify user. i wrote bit of code (with intention of including in pages) display google sign-in button, verify token again , exit index.php if google-generated user id doesn't match 1 being carried php session. i'm not sure if necessary, thought might improve security little in case possible spoof session user id. <div class="g-signin2" data-onsuccess="onsignin"></div> <script> function onsignin(googleuser) { var profile = googleuser.getbasicprofile(); console.log('id: ' + profile.getid()); // not send backend! use id token instead. var id_token = googleuser.getauthresponse().id_token; var userid = <? echo $userid; ?>; $.get("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + id_token, function( data ) {

android - How to change Preference text colour programmatically? -

Image
i'm adding preferences programmatically instance of preferencescreen (which add preferenceactivity). works expected except text colour, white despite trying: to set theme through manifest set theme programmatically a few other hacks aren't notable all i'm doing: preferencescreen screen = getpreferencemanager().createpreferencescreen(this); preferencecategory category = new preferencecategory(this); category.settitle("hello"); screen.addpreference(category); checkboxpreference testpreference = new checkboxpreference(getapplicationcontext()); testpreference.settitle("test"); category.addpreference(testpreference); setpreferencescreen(screen); i've set theme themeoverlay.appcompat.dark (which don't want) , text legible, looks in other case (i'm tapping can see text through animation effect): how go making text black? thanks! simple fix, actually: i had called getapplicationconte

algorithm - What makes this prime factorization so efficient? -

i've been doing project euler problems learn/practice lua, , initial quick-and-dirty way of finding largest prime factor of n was pretty bad, looked code see how others doing (in attempts understand different factoring methodologies). i ran across following (originally in python - lua): function main() local n = 102 local = 2 while i^2 < n while n%i==0 n = n / end = i+1 end print(n) end this factored huge numbers in very short time - immediately. thing noticed algorithm wouldn't have divined: n = n / i this seems in of decent algorithms. i've worked out on paper smaller numbers , can see makes numbers converge, don't understand why operation converges on largest prime factor. can explain? in case, i prime factor candidate. consider, n composed of following prime numbers: n = p1^n1 * p2^n2 * p3^n3 when i reaches p1 , statement n = n / = n / p1 removes 1 occurrence of p1 : n / p1 = p1^(n-1) * p2^

jquery - Ajax not making changes -

i'm working through book on php , jquery , i've encountered problem ajax, in not post it's changes , display them. <head> <meta charset="utf-8" /> <title>testing jquery</title> </head> <body> <p>hello world!</p> <p class="foo">another paragraph, 1 ahs class.</p> <p><span>this span in paragraph</span></p> <p id="bar">paragraph id. <span class="foo">and sentence in span</span> </p> <script src="jquery.validate.min.js"></script> <script src="jquery/ajax.js"></script> <script src="jquery/jquery-1.8.3.min.js"></script> <form action="#" method="post"> <fieldset> <legend>sign form</legend> <label for="name">name</la

python truncating a dictionary to get last elements -

i have python dictionary of form: {"1":"sdv","2":"wefc","3":"sdsdv","4":"dvsdv","5":"igsdhc","6":"gvvxas","7":"sdvsfdv","8":"sdagf"} i need remove first 6 elements in dictionary , take remaining once only. length of list may vary greater 6. please me the dictionary doesn't have ordering in keys. can take keys, sort them, , manually remove first 6 of them: d = { "1":"sdv","2":"wefc","3":"sdsdv","4":"dvsdv", "5":"igsdhc","6":"gvvxas","7":"sdvsfdv","8":"sdagf" } key in sorted(d, key=int)[:6]: del d[key] print d result: {'7': 'sdvsfdv', '8': 'sdagf'}

osx - Executable Python Program with Multiple Functions (MacOS) -

i seek advise regarding python. i created main.py using python calls multiple functions, located in separate python script files. i'd create executable files in macos , found command: chmod +x main.py however, since main.py calls function, can't run gave me error. kindly advise how link function scripts main script. thanks. i'm not sure issue , since there isn't lot of detail i'm going start beginning: the command chmod +x main.py indicating system file main.py executable file. since main.py isn't program can executed, going have tell osx how run script have created. shebang comes in shebang (unix) . at top of script going need put following line: #!/usr/bin/env python this tell computer pass main.py script python execution. now onto import stuff. python going in following locations when use import statement see python docs more info : the directory containing input script (or current directory when no file specified).

scala - Which JSON library to use when storing case objects? -

i need serialize akka events json. based on " what json library use in scala? " tried several libraries. since serializer should know nothing of concrete events, events consisting of case classes , case objects should serialised using reflection. json4s seems match requirements best. class json4seventadapter(system: extendedactorsystem) extends eventadapter { implicit val formats = serialization.formats(fulltypehints(list(classof[evt]))) override def tojournal(event: any): = event match { case e: anyref => write(e).getbytes(charsets.utf_8)} override def fromjournal(event: any, manifest: string): eventseq = event match { case e: array[byte] => { eventseq.single(read[evt](new string(e.map(_.tochar))))}} the problem using json4s is, no matter implementation used deserialization of objects produces different instances . since heavily use pattern matching case object breaks our existing code. so question is: json library used scala , akka persistenc

android - Recycleview contains child fragments -

Image
hi guys want example of recycle view contains child fragments , layout manager gridlayoutmanager made 1 add in first cell , ignores others public class simplefragment extends fragment { private recyclerview mrecyclerview; private myadapter madapter; private recyclerview.layoutmanager mlayoutmanager; @nullable @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { return inflater.inflate(r.layout.fragment_simple, container, false); } @override public void onviewcreated(view view, @nullable bundle savedinstancestate) { super.onviewcreated(view, savedinstancestate); sethasoptionsmenu(true); mrecyclerview = (recyclerview) view.findviewbyid(r.id.my_recycler_view); mlayoutmanager = new gridlayoutmanager(getactivity(), 4); mrecyclerview.setlayoutmanager(mlayoutmanager); list<card> cards = new arraylist<>(); cards.add(new card(size.large, new fragmenthalf())); cards.add(new ca

javascript - Mustache JS, How to create a recursive list with an unknown number of sub lists? -

i have seen discussed in few threads , looked (or is) way this. can't seem work. must missing something. output should like <ul> <li>parent <ul> <li> sub child <ul> <li> sub sub child</li> </ul> </li> </ul> </li> </ul> what is <ul> <li>parent <ul> <li> sub child </li> </ul> </li> </ul> what have far template <script type="text/template" id="template"> <ul class="parent"> {{#menu}} <li> {{item}} <ul class="popupmenu"> {{#menu}} <li>{{item}}</li> {{/menu}} </ul> </li> {{/menu}} </ul> </script> js var data = { menu : [{

web - How to fetch data from database after 2 seconds on a jsp page -

currently i'm working on college web project. application/web page sports application/web page, wanted fetch fresh score database or external api after every 2 seconds on jsp page please provide me solution in not have refresh page ( if possible ) , fetch latest score. i'm not getting do. please me out. try function getscore(){ $.ajax( { url: "/yoururl/score.jsp", type:'post', data: "input data", contenttype: "application/json", //here specify content type success: function(result){ alert(result); // here result response return score.jsp }) }, error: function(e) { alert("error in getting score!"); } }); settimeout(getscore, 2000); } here settimeout(getscore, 2000); 'settimeout' java script method call getscore method on every 2000 m seconds. in getscore call ajax method request data on particular servlet or

c - Printing a string due to a new line -

is there efficient (- in terms of performance) way printing arbitrary string, until first new line character in (excluding new line character) ? example: char *string = "hello\nworld\n"; printf(foo(string + 6)); output: world if concerned performance might (untested code): void myprint(const char *str) { int len = strlen(str) + 1; char *temp = alloca(len); int i; (i = 0; < len; i++) { char ch = str[i]; if (ch == '\n') break; temp[i] = ch; } temp[i] = 0; puts(temp); } strlen fast, alloca fast, copying string first \n fast, puts faster printf is far slower 3 operations mentioned before together.

php - Sending " (quote marks) sign over cURL with JSON -

i'm sending array data on curl server (with php). code before sending prepare data: $array['fielda'] = urlencode('something "special" here'); $array['fieldb'] = urlencode('text & number\'s content'); $data = json_encode($array); // {"fielda":"something+%22special%22+here","fieldb":"text+%26+number%27s+content"} and sending curl curl_setopt($ch, curlopt_httpheader, array('content-type: application/x-www-form-urlencoded')); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields, "params=".$data); code on other side $data = json_decode($_post, true); $data['fielda'] = urldecode($data['fielda']); $data['fieldb'] = urldecode($data['fieldb']); var_dump of $_post different: "{"fielda":"something "special" here","fieldb":"text & number's content"}" a

netbeans - Changing which java file runs first when opening jar -

i'm not entirely sure how word how go changing java file in package first 1 open when compiled jar file executed? i'm using netbeans if helps. you can changed in netbeans. when run whole project in netbeans, first class executed there first class executed in jar file built netbeans. you can right click project in project window , select properties. window opens, select run category in left side. on right side, there button browse , select file main class.

How do I add a string to all existing elements in array in javascript? -

if have array such following var = ["a","b","c","d"]; how can add onto string of each item using loop make result return so? ["i a", "i b", "i c", "i d"] ["a","b","c","d"].map(function(e) { return "i " + e }); or full code (thanks mplungjan!) var = ["a","b","c","d"]; = a.map(function(e) { return "i " + e });

winapi - In Windows API programming how do I prevent mouse from leaving window? -

how limit mouse 1 particular hwnd in win32 api programming? hwnd not created me. browser window, or photoshop program window. i'm trying write program doesn't let mouse leave particular windows program. can hwnd of program getwindowtext . check out msdn: clipcursor function

sas - How to get minimum and maximum value of all the columns of a table? -

how minimum , maximum value of columns of table? please note columns may both numeric, date or character. have find min , max of variables in following format: name_of_columns, minimum, maximum here's macro asking doesn't require know variable names or type: %macro maxmin; /* variable names */ proc contents noprint data = test.hashval out=test.contents;run; proc sql noprint; select count(*) into: cnt test.contents;quit; %let cnt = &cnt; proc sql noprint; select name into: name1 - : name&cnt test.contents;quit; /* length of variable names , results */ proc delete data = test.results; run; %let name_len = 0; %let max_len = 0; %let min_len = 0; %do = 1 %to &cnt; proc sql noprint; select max(&&name&i),min(&&name&i) into: max&i, :min&i test.hashval;quit; %let max&i = %cmpres(&&max&i); %let min&i = %cmpres(&&min&i); %if (&name_len < %length(&&name&

php - Array to string conversion error with json_encode -

i have connect function mysql database so: function connect() { $config = parse_ini_file('../../config.ini'); // try , connect database self::$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']); //check if both bools , false === checks type , equality if(self::$conn === false) { header("http/1.1 500 internal server error"); header("content-type: application/json"); $response = array("response"=>"failed connect database"); echo "json_encode($response)"; die(); } } i having issue when json_encode (for fail connection). error : notice : array string conversion in /var/www/html/somesite.co/public_html/api/index.php on line 47 json_encode(array) really have no idea why i'm getting error. have encoded , echo'd , array be

css - select the last element having some style property -

table { border-collapse: collapse; border : 1px solid #e2e2e2; } caption, th, td { text-align: left; line-height: 1.4; padding: 8px; } tr { border-bottom: 1px solid #ccc; vertical-align: top; } <table> <caption>optional table caption.</caption> <thead> <tr class="heade_class"> <th>#</th> <th style="display:table-cell">first name</th> <th style="display:table-cell">last name</th> <th style="display:none">username</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>mark</td> <td>otto</td> <td style="display:none">@mdo</td> </tr> <tr>

android - List installed sdk package via command line -

i want list installed sdk packages command lines.(for reasons cannot use gui) i have done research , found out several commands list available packages on remote server, fail find command list installed sdk packages yet. thanks with android sdk tools 25.2.3 (and higher): $android_home/tools/bin/sdkmanager --list see: https://developer.android.com/studio/command-line/sdkmanager.html#usage

php - My Select top query isn't working -

this question has answer here: is there alternative top in mysql? 5 answers can tell me wrong query? it's printing else statement, , it's giving error: you have error in sql syntax; check manual corresponds mysql server version right syntax use near '2 * `sql_tbl`' @ line 1. <?php $con=mysqli_connect("localhost","root","","sql_db"); $sqli="select top 2 * `sql_tbl`"; $querys=mysqli_query($con,$sqli); if($querys){ echo "query correct";} else{ echo "query not write". mysqli_error($con); } ?> the equivalent "top" syntax in mysql "limit": so: $sqli="select top 2 * `sql_tbl`"; becomes: $sqli="select * `sql_tbl` limit 2";`

jenkins checkmarx plugin does not take envirnoment variables in exclude folder property? -

im trying pass exclusions in checkmarx plugin setting envirnoment variables. plugin not seem take envirnoment variables parameter in exclude folder field. i have installed checkmarx plugin 7.2.1-26 , jenkins ver. 1.596.3 i afraid checkmarx jenkins plugin supports environment variables in project name , comment fields only.

javascript - Custom Zoom Control Results In Maximum Call Stack Size Exceeded Error -

i'm trying change zoom increment when using google maps javascript api on ios. example, instead of going zoom 14 zoom 15, go straight zoom 16 , zoom 18, , on... when user uses pinch zoom gesture. i know can achieve buttons, can't seem find solution pinch zoom gesture. realize zoom_changed event needs tracked. i error of maximum call stack size exceeded map.setzoom(zoom + 2); , map.setzoom(zoom - 2); when added on line 17 , 19, respectively. check out jsfiddle: http://jsfiddle.net/2zmn9173/4/ . part need with: if (useragent.indexof('iphone') != -1) { google.maps.event.addlistener(map, 'zoom_changed', function () { if (map.getzoom() > zoom) { alert("zoomed in level " + zoom); } else if (map.getzoom() < zoom) { alert("zoomed out level " + zoom); } zoom = map.getzoom(); }); } the buttons on top demonstrate functionality trying achieve, pinch zoom gesture.

ruby on rails 4 - Escape string to url-fit -

i want escape string nice looking in url. example white-spaces changed '_'. thing that's bother me '%number'.. site has multi-languages words. <%= link_to tag.name tag_details_path(tag.id,url_encode(tag.name)) %> so url_encode doesn't fit me.

ios - Details ViewController for MKAnnotation -

i'm trying make detail view after user clicks on mkannotation switch on new view (in navigationcontroller). looking making view similar see click on annotation in apple maps. see picture @ top of view, followed various entries of text. i need show following fields in view , want display in organized way. var business_name : string var category : string var address : string var city : string var type : string var location : string var valid : string var comments : string var date : string var username : string var additional_comment_count : string how can make view similar apple maps detail view controller looks? need incorporate different types of views? need make own custom views? it looks table view controller, diferent type of cells. top cell have image view, many of ther other cells normal title/detail cell , other cells have collection views/scrollviews in them

javascript - Store.getGroups returns an array of undefined objects in Extjs 5.1 -

i stuck in 1 situation have expand selected row of group grid made in extjs 5.1. store.getgroups returns array of undefined objects, can 1 had similar issue, working fine extjs 4.2.x? fiddle code - works in 4.2.x, doesn't work in 5.1 https://fiddle.sencha.com/#fiddle/8mi please help. the getgroups() method returns ext.util.collection you the first group name following way: var firstgroupname = store.getgroups().getat(0).getgroupkey(); check out fiddle . to groups use getrange() method. var groups = store.getgroups().getrange();

Visual Studio 2015 bower - not installed -

using empty template in visual studio 2015, following configuration fails install dependencies. { "name": "asp.net", "private": true, "dependencies": { "bootstrap": "3.0.0", "bootstrap-touch-carousel": "0.8.0", "hammer.js": "2.0.4", "jquery": "2.1.4", "jquery-validation": "1.11.1", "jquery-validation-unobtrusive": "3.2.2" } } while same configuration web application sample template in asp.net completes successfully . my colleagues running same problem. is known issue? there work around? missing? error in output window : "c:\program files (x86)\microsoft visual studio 14.0\common7\ide\extensions\microsoft\web tools\external\bower.cmd" install --force-latest bower bootstrap#3.0.0 enotfound request https://bower.herokuapp.com/packages/bootstrap failed: getaddrinfo en

In python Django, I want to query a foreignKey coloumn of a table, it raise django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet -

i have app name publisher. run code in publisher/views.py. runs ok inserting entries , newspapers = newspaper.objects.values('newspaper_link') tables ok when view in sqlite db browser. when run newspapers = newspaper.objects.values('country_id') or newspapers = newspaper.objects.values() it raise django.core.exceptions.appregistrynotready: models aren't loaded yet. here publisher/models.py: from django.db import models class country(models.model): country_link = models.urlfield() country_name = models.textfield(primary_key=true) class newspaper(models.model): newspaper_link = models.urlfield(primary_key=true) newspaper_name = models.textfield() country = models.foreignkey(country) here traceback information: traceback (most recent call last): file "d:/teamproject/djangoprojectone/djangoprojectone/mysite/publisher/views.py", line 99, in <module> preorder('a') file "d:/teamproject/dja