Posts

Showing posts from January, 2011

c# - ObservableCollection binding on condition -

Image
i have observable collection marketprices , observable collection have bind itemscontrol below . 1) don't want show items in observable collection , want show items user click add , selected pair (gbpjpy, usdgbp..) needs show in items control. 2) if user changed item in comobobox gbpjpy usdgbp , price( datatemplate) of gbpjpy need update usdgbp. how can achieve both conditions. please note below code doesn't have real-time update in project have relatime price update well, observable collection updates on price changes. code far public class pricemodel : inotifypropertychanged { private double _askprice; private double _offerprice; private string _selectedpair; public pricemodel() { pairs = new observablecollection<string> {"gbpusd", "gbpeur", "usdgbp", "gbpjpy"}; } public double askprice { { return _askprice; }

java - Why cannot I modify collection through up bounded reference but can through its iterator? -

list<? extends number> list1 = new arraylist<number>(){ {addall(arrays.aslist(1,2,3,4,5));} }; listiterator listiterator = list1.listiterator(); listiterator.next(); listiterator.set(999); system.out.println(list1); this code works , outs [999, 2, 3, 4, 5] but if write so: list<? extends number> list1 = new arraylist<number>(){ {addall(arrays.aslist(1,2,3,4,5));} }; list1.set(0,999); i see java: method set in interface java.util.list<e> cannot applied given types; required: int,capture#1 of ? extends java.lang.number found: int,int reason: actual argument int cannot converted capture#1 of ? extends java.lang.number method invocation conversion plese clarify behaviour. p.s. question arisen after watching code collections.reverse method public static void reverse(list<?> list) { int size = list.size(); if (size < reverse_threshold ||

OpenCV Android with nonfree package (SURF) -

i'm trying make app can detect similarity in pictures in android. i'm trying opencv , surffeaturedetector . in opencv it's not package nonfree , i'm trying go according tutorial https://sites.google.com/site/wghsite/technical-notes/sift_surf_opencv_android i'm getting problem: description resource path location type make: * [obj/local/armeabi-v7a/libmixed_sample.so] error 1 appname c/c++ problem recipe target `obj/local/armeabi-v7a/libmixed_sample.so' failed appname line 588, external location: c:\nvpack\android-ndk-r9d\build\core\build-binary.mk c/c++ problem undefined reference 'cv::surf::surf(double, int, int, bool, bool)' appname line 54, external location: c:\nvpack\android-ndk-r9d\toolchains\arm-linux-androideabi-4.6\prebuilt\windows\arm-linux-androideabi\bin\ld.exe: .\obj\local\armeabi-v7a\objs-debug\mixed_sample\jni_part.o: in function java_sk_appname_myopencvactivity_mo

php - open_basedir allow including "trusted" code -

i writing application want allow users write / run / test code on server, preloaded code application. want these users able work in directory , task can done open_basedir(); , problem if want include application's code permission denied if require or include inside function or class file not included before open_basedir called. example : <?php function test() { require 'test.php'; } test(); // ok ini_set('open_basedir', 'users/username/'); test(); // permission denied is possible somehow allow "trusted" code of application included don't allow user's code access directories? , if possible, give me example or main idea on how can resolve this, if not related open_basedir() in example, not have permission denied. give me possibility add great features application. another example : spl_autoload_register(function($class) { require $class . '.php'; }); ini_set('open_basedir', 'folder/

What to use instead of css `line-height` to avoid spoiling Unicode tables? -

is there alternative css line-height not ruin of unicode tables (tables drawn unicode box-drawing characters : ┌─────────────┐ │ character │ ├─────────────┤ │ donald duck │ └─────────────┘ (stack overflow , others use line-height: 130%; or similar improve visual appearance of posts, want have neat alternative propose se - particularly for dba.se - can use unicode art tables without looking naff.) your question bit vague. there no alternative line spacing if want lines spaced closer together. unless have else in mind, should elaborate. the context question vague too. stackexchange site itself? if so, should have been asked on https://meta.stackexchange.com/ that said, effect depend on font used. in fonts, length of vertical line │ longer in others; instance line 1em long in lucida console , 1.17em in consolas. when using consolas, can use maximum line-height of 1.17 before gap becomes visible, while lucida requires line height smaller. one possible solution t

c++ - Swapping each pair of values in a multimap<int, int> -

i have multimap containing on 5 million pairs , need swap keys values. unordered_multimap<int, int> edge; due large size of container , processes involved, prefer not have create new multimap swapped pairs iterating on each element of map. what best way, if any, in place ? the proper approach not @ all , instead have bi-directional map in first place, on can perform lookup in either direction. consider looking boost.bimap .

javascript - Unexpected character error in JQuery ajax function -

i have 'unexpected character error' problem, jquery ajax code looks that: function test(){ if(true){ $.ajax({ type: 'post', url: 'test.php', datatype: 'json', data: { godot: 'godot', jobadze: 'jobadze' }, success: function(data){ alert(data); }, error: function(jqxhr, textstatus, errorthrown) { alert("error status: "+textstatus+"\nmessage: "+errorthrown); } }); and php code: <?php echo 'test'; ?> it should alert "test", calls error. going on? you wrote datatype: 'json' , php script required return valid json. since you're not, gets error when tries parse response json, , reports error. you should use json_encode : <?php echo json_encode('test'); ?>

What type of array should I use to combine numerical values and string values and have the ability to sort them in octave/matlab -

i'm trying link numerical (octave/matlab) values in array string values in array how can go doing this. reason i'm trying sort array based on numerical values. example: array=[1,2,'filename1';3,4,'filename2';5,6,'filename3'] (i know incorrect , give error) this i'm trying can sort based on first or second column , have third column "linked" / follow sort. (please note numbers not sequential sequence 1,2,3... used example) 1,2,filename1 3,4,filename2 5,6,filename3 if sort first numerical column in descending order should this 5,6,filename3 3,4,filename2 1,2,filename1 how can go doing , still values of array individually? example: array(1,1) 5 , array(3,3) filename1 if want know, plan on creating playlist of wavfile names based on sort. ps: i'm using octave/matlab you can use 2 separate arrays, 1 2 columns of number , 1 strings. when sort first array based on first number, function return b

shift - Bitshifting in C++ producing the wrong answer -

i tried running following code code: char c = (2 << 7) >> 7 which should return 0 because 2 has binary representation char : 0 0 0 0 0 0 1 0 after 7 shifts left, 0 0 0 0 0 0 0 0 then, after 7 shifts right, get 0 0 0 0 0 0 0 0 however, i'm getting result 2, not 0. the compiler says 2 << 7 256, it's char , shouldn't 256. i understand 2 << 7 calculated int s , answer put c 256 >> 7 2. i tried cast 2 char (ex: (char)2>>7 ) doesn't work either. i'm trying extract each bit char , wrote code: char c = 0x02; for(int i=0;i<7;i++) { char current = (c<<i)>>7; } how can each bit? what's wrong way? the result of arithmetic shift operation 1 operand being int in c++ int . therefore, when write current = (c << i) >> 7; c++ interpret (c << i) , (c << i) >> 7 int s, casting char when assignment done. since temporary values int s, no overflow

actionscript 3 - Use array as a dataProvider to populate DataGrid not working AS3 -

var lista:datagrid = new datagrid(); var tablaarray:array = new array(); var externalfile:urlrequest = new urlrequest("https://las.api.pvp.net/api/lol/las/v1.4/summoner/by-name/goncyrlz?api_key=mykey"); var textloader:urlloader = new urlloader(externalfile); lista.columns = ["id","name","profileiconid","summonerlevel","revisiondate"]; lista.setsize(stage.stagewidth, stage.stageheight); lista.x = 0; lista.y = 0; textloader.addeventlistener(event.complete, agregar); function agregar(event:event):void { var textocargado:string = textloader.data; tablaarray = textocargado.split(","); trace(tablaarray.tostring()); lista.dataprovider = new dataprovider(tablaarray); addchild(lista); } the response on trace is: {"goncyrlz":{"id":96893,"name":"goncyrlz","profileiconid":590,"summonerlevel":30,"revisiondate":1402143493000}} b

php - mysql_fetch_array while loop -

Image
i have while loop contains while loop. both loops iterating on different mysql result sets. problem second time outer while loop calls inner while loop doesn't run. mysql_fetch_row discard after has been iterated over? here code looks like: $counter = 0; while ($r = mysql_fetch_row($result)){ $col = ""; $val = ""; while($d = mysql_fetch_row($dictionary)){ $key = $d[0]; for($i= 0; $i< count($tablecolumnames); $i++){ if($tablecolumnames[$i] == $key){ $col .= "`".$d[1]."` ,"; $val .= "`".$r[$i]."` ,"; /* echo $tablecolumnames[$i]." table columnname <br>"; echo $d[1]." key<br>"; */ } } echo $key."round".$counter."<br>"; } var_dump ($col); var_dump ($val); $counter++; echo $counter;

javascript - AngularJS Directive Issue retrieving template from templateUrl -

i'm new creating directives in angular, , i'm kind of stuck here, want create basic mini calendar directive select date in given month. i'm still getting error template when it's requested. help? thanks function calendarcontroller($scope) { $scope.config = new date(2000, 0, 1); } angular.module("calendar", []).directive('minicalendar', function($parse) { return { restrict: "e", replace: true, templateurl: "../views/template.html", transclude: true, controller: mcalbinding, compile: function(element, attrs) { debugger; var modelaccessor = $parse(attrs.ngmodel); return function(scope, element, attrs, controller) { var processchange = function() { // var date = new date(element.datepicker("getdate")); scope.$apply(function(scope) { // change bound variable debugger; mod

c# - Stop a thread if it takes too long -

i new in windows phone development , trying create windows phone app using c# thread t = new thread(doaheavywork); t.start(); if (!t.join(1000)) // give operation 1s complete { t.abort(); } i cannot alter doaheavywork function. i need result omputed within 1 or 2 seconds, since may run long time. i have read using abort wrong way. i using above in photochoosertask complete function. first run executes fine. is, when click button select photo, doaheavywork function doesn't exceed 1 sec. if try second time, photochoosertask throws exception , stops. is because aborted process in 1st run? or else? there other way it? .abort() causes thread destroyed completely. if generating new thread each time in example, work. if using same t object, need create new thread object, can't run .start() on aborted thread. however fact aborting thread concern. happens application when take more 2 seconds. should showing user, please wait, taking longer expected. do

bash - How to launch tmux with pre-opened second window and execute commands? -

there's possible duplicate it's closed , unanswered. as i'm using chef automation, nice automate tmux launch pre-launched python web server , second window opened. (this development environment). , way of doing specifying parameters command line. commands want execute in window title "daemon": source bin/activate cd project debug=1 python app.py i'm unable find command line parameters allows pre-execute commands when launching tmux, , open more windows on launch. you want create session without attaching (using -d option), can send additional tmux commands open second window before attaching. tmux new-session -t mysession -d 'source bin/activate; cd project; debug=1 python app.py' tmux new-window -t mysession tmux attach-session -t mysession

mysql - Foreign Key in SQL pivot table - database design -

Image
i using dbdesigner 4 designing database relations. i have users table , recipes table. 1 user can own many recipes 1 recipe cannot owned many users. relationship shown user_recipes relation in picture. (a one-to-many relationship users recipes ). however, recipes can liked users. many users can many recipes. many-to-many relationship between users , recipes , pivot table users_like_recipes . but when create pivot table, need users_id , recipes_id column. recipes_users_id column getting added on own , not able remove it. says third column has come relation defined in model. guess user_recipes relation. when remove user_recipes relation, pivot table want to. but need user_recipes relation too! please. appreciated. i suggest removing user_id primary key from recipes table. combination if id , user_id provides identification recipes table. in situation multiple user_id's can create same recipe id because combination has unique. user_id can normal c

java - XMLHttpRequest cannot load which is disallowed for cross-origin requests that require preflight -

i've troubles when try perform auth request app sandbox.feedly endpoint. i've configured server , client cors request, after post request can't perform redirect https://sandbox.feedly.com/v3/auth/auth?client_id=sandbox&response_type=cod…loud.feedly.com%2fsubscriptions&state=5a....2 . has had same problem?

mysql - Can grouped expressions be used with variable assignments? -

i'm trying calculate row differences (like mysql difference between 2 rows of select statement ) on grouped result set: create table test (i int not null auto_increment, int, b int, primary key (i)); insert test (a,b) value (1,1),(1,2),(2,4),(2,8); gives | | b --------- | 1 | 1 | 1 | 2 | 2 | 4 | 2 | 8 this simple sql group , max(group) result columns: select data.a, max(data.b) ( select a, b test order ) data group order the obvious result is | | max(data.b) ----------------- | 1 | 2 | 2 | 8 where i'm failing when want calculate row-by-row differences on grouped column: set @c:=0; select data.a, max(data.b), @c:=max(data.b)-@c ( select a, b test order ) data group order still gives: | | max(data.b) | @c:=max(data.b)-@c -------------------------------------- | 1 | 2 | 2 (expected 2-0=2) | 2 | 8 | 8 (expected 8-2=6) could highlight why @c variable

javascript - Access knockoutjs ViewModel from outside binding scope -

i have page has parent area has 2 children areas, simplified following <div id='parent'> ....other parent's html markups .... <div id='signin'> ... signin's html markups .... </div> <div id='register'> ... register's html markups .... </div> </div> each of 'child' divs binds own viewmodel ko.applybindings(new signinmodel(), document.queryselector('#signin')) ko.applybindings(new registermodel(), document.queryselector('#register')) how can bind parent's html markups outside of both children divs properties of either signin or register viewmodel ?? or have merge 2 viewmodels one, bind parent? how can bind html markup inside 'signin' div property of signinmodel viewmodel, or otherway round? thanks i don't think can. have bind parent , can use data-bind span.

objective c - Certificate In iOS McSEssion -

in ios mcsession, can initialize section using following method initwithpeer:securityidentity:encryptionpreference: most online tutorials authors put nil securityidentity. however, wonder whether damage (hacked) if leaving nil real app. if so, how generate secidentityref this? i found following articles/discussions security in ios, still have trouble connect secidentityref mcsession. thank precious time on question, , comment helpful. securing , encrypting data on ios: http://code.tutsplus.com/tutorials/securing-and-encrypting-data-on-ios--mobile-21263 how establish secidentityref in iphone keychain ? (without .p12): how establish secidentityref in iphone keychain ? (without .p12) generate key pair on iphone , print log nsstring: generate key pair on iphone , print log nsstring

c# - Workflow required to perform lengthy ASP.NET task -

i have asp.net webforms application mimics desk system. application works fine, recently, asked me make can text message in system whenever new desk ticket opened. i using twilio , working fine. problem is, there 15 people in system should getting text message , when ticket submitted, application takes 15-20 seconds repost submit. in future, there more 15 people, double even. what wondering if there way send these messages in background, page come submit right away. here relevant code: this main method wrote sending text message. in utility class: public static string sendsms(string phonenumber, string message) { var request = (httpwebrequest)webrequest.create("https://api.twilio.com/2010-04-01/accounts/" + constants.twilioid + "/messages.json"); string postdata = "from=" + constants.twiliofromnumber + "&to=+1" + phonenumber + "&body=" + httputility.htmlencode(message); byte[] data =

xml - Positioning overlapped view in Android -

Image
simply - how place 1 view on top of view (which can shrink) in strictly defined place regardless of screen resolution , density? example - place textview on top of image on pyramides. when using margins (frame or relative layout) dp units fail on different screen size :( xml <framelayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/image" /> <textview android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginbottom="20dp" android:layout_marginleft="30dp" android:layout_gravity="left|bottom" /> </framelayout> when using margins (frame or relative layout) dp units fail on diff

sql - sqlite: no column after alter table -

i try add column existing table, , use it: sqlite> create table tst(id_key integer primary key, s1 text); sqlite> .tables tst sqlite> insert tst (s1) values ("aa"); sqlite> select * tst; 1|aa sqlite> alter table tst add colum s2 text not null default "bb"; sqlite> select * tst; 1|aa|bb sqlite> .schema tst create table tst(id_key integer primary key, s1 text, colum s2 text not null default "bb"); so looks fine. but sqlite> select s2 tst; error: no such column: s2 so in scheme there "s2" column, sole record contains data in "s2" field, sqlite don't know column s2. what wrong, used "alter table" in wrong way? your column not named s2 , colum . check alter table spelling. sqlite> select colum tst; bb this question should closed, typo. btw, code should formatted 4 spaces in front, not text quote; gives monospace font , syntax highlighting; latter might have helped

PDKeychain is not storing the data ( swift ) -

i have added pdkechainbindingscontroller.m & h files + pdkeychainbindings.m & h files swift project. i have created bridge header.h file. then included pdkeychain header files in bridge file: #import "pdkeychainbindings.h" #import "pdkeychainbindingscontroller.h" i have rewritten existing objective c code in swift shown below. var url:nsurl = nsurl(string: shopurl.text) var securestore: pdkeychainbindings = pdkeychainbindings() securestore.setobject("url", forkey: "shopurl") var usernamesecured:nsstring = nsstring(string: username.text) securestore.setobject("usernamesecured", forkey: "username") var passwordsecured:nsstring = nsstring(string: password.text) securestore.setobject("passwordsecured", forkey: "password") i cannot store information reason. getting error: could not store(add) string. error was:-34018 any appreciated. thank you. edit: have far , no joy :(

android - Use getDefaultSharedPreferences before user opens settings activity -

i have settings activity in android app. settings have default values in res/xml/preferences.xml . problem i'm having until user goes settings page, default preferences not saved , cannot retrieve default values stored in xml file. the code: res/xml/preferences.xml <?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android" > <edittextpreference android:defaultvalue="xml default value" android:title="foo" android:summary="bar" android:key="mykey" /> </preferencescreen> settingsactivity.java package bh.gov.cio.gdt.app; import android.os.bundle; import android.preference.preferenceactivity; import android.preference.preferencefragment; public class settingsactivity extends preferenceactivity { @override protected void oncreate(final bundle savedinstancestate) { super

css - rounded corners on html5 video -

is there way can cut off corners of html5 video element using css3 border-radius attribute? check out this example . it's not working. create div container rounded corners , overflow:hidden. place video in it. <style> .video-mask{ width: 350px; -webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%); -webkit-transform: rotate(0.000001deg); -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; overflow: hidden; } </style> <div class="video-mask"> <video></video> </div>

Sql Server retrieve last date for multiple records -

i have table 5 columns emp , surname , csd , term rsn , date . first 4 columns stay same date change eg. there can 30 records emp 30 different dates. this code works when add [date] select returns 30 records whereas trying return 1 record last date create procedure testpro( @reportstartdate date, @reportenddate date ) begin select distinct emp, surname, csd, case when csd<= @reportstartdate case when [term rsn] != 0 case when [date] <= @reportenddate (datediff(dd,@reportstartdate, [date]) - (2* datediff(wk,@reportstartdate,[date])))+1 else (datediff(dd,@reportstartdate, @reportenddate) - (2* datediff(wk,@reportstartdate,@reportenddate)))+1 end else (datediff(dd,@reportstartdate, @reportenddate) - (2* datediff(wk,@reportstartdate,@reportenddate)))+1 end else case when [term rsn] != 0 case when [date] <= @reportenddate (datediff(dd,csd, [date]) - (2* datediff(wk,csd,[date])))+1 else (datediff(dd,csd, @reportenddate) - (2* datediff(wk,csd,

c# - Dropdown SelectedItem.Value with a different text -

Image
i have dropdownlist textm use half of phrase how can easy? show code, right can full text. i want take hours in text: 1hr, 24hrs. delete text. example:text="send reminder 1hr before" so want that: text="1hr" i want take hour , guys <asp:dropdownlist id="reminderoptions" runat="server"> <asp:listitem value="-1" text="don't send reminder" /> <asp:listitem value="3600" text="send reminder 1hr before" /> <asp:listitem value="86400" text="send reminder 24hrs before" /> </asp:dropdownlist> lblreminderset.text = reminderoptions.selecteditem.value; lblreminderset.text = string.format("a message sent {0} lessons", reminderoptions.selecteditem.text); let's use regex pull time frame out: (\d+hr[s]?) debuggex demo this expression says find me digit, 1 or more times, followed hr , optionally followed s . now, u

android - Netbeans IDE: Unknown error when running a Cordova project -

ok, having real painful issue on netbeans ide 8.0. have installed android sdk, git, cordova , node.js. however, tried test index.html sample page clicking on "run" above, , got unknown error (refer attached screenshot here ). why this? thank!

angularjs - Fieldset and disabling all child inputs - Work around for IE -

i have fieldset has ui-view under it. each view had lots of fields(a field directive wraps input) under it. it looks this: <fieldset ng-disabled='mycondition'> <div ui-view></div> // changes lot's of fields <div field='text-box'></div> </fieldset> now, worked great, fields disabled on browsers except ie . i've done google , seen ie doesn't support fieldset + disabled , i'm looking quick workaround. i've tried things close not perfect , assume i'm not first 1 needs solution(even though didn't find on google). seems related ie issues, see this , related (sorry, can't post more 2 links yet). first 1 fixed in next major ie release (edge?). second 1 still opened. as suspect, problem user still can click inputs inside disabled fieldset edit them. if so, there "css only" workaround ie 8+ creates transparent overlay above disabled fieldset prevents fieldset being clicked

asp.net mvc - Crystal report export to rtf and open with word 2013 reduces image proportion(size) and align to left -

when export crystal report 13 rtf format , open ms word 2013 , seems document content , image size getting minimised , aligned left. noticed there no option export word 2013 2003,2007 , other options, should overcome problem. please find solution this. in advance. crystal not useable office 2013. should use reporting tool if need embed reports in word.

AngularJs Directives with DropDown lists -

perhaps i'm aiming big reusable directive idea, i've been asked give demo company in less 2 weeks, i'm aiming higher normal. i'm building on top of question asked , answered here: angular list directive i've added new features, such "click edit". here's plnkr here's works: click edit here's i'm having problems with: display text instead of id drop down list auto-focus object force input have focus can capture blur next question be: how know object i'm updating send server? i did spend day sunday trying tasks work, failed. cleaned code of of failed attempts. i want save record each time edit field. i'm updating object, think beautiful, don't know trigger send object server. perhaps that's jquery background talking? thanks, duane to display text instead of id dropdown list : you can create function in directive loops through options, , returns name when id matches value you&

emacs - Generate link to table of contents from a headline in Org -

when export org file html, generates table of contents headlines. however, want every headline have link entry in table of content. there way this? i found answer here: http://lists.gnu.org/archive/html/emacs-orgmode/2014-01/msg00028.html i realized need floating table of content. , worg.css provides that: http://orgmode.org/worg/style/worg.css this awesome css.

css - Multiple Classes not working in Responsive Email HTML -

i have responsive html email working on. code inlined exception of media queries. (i know not work on email clients!) within media queries have 2 classes defined: @media screen , (max-device-width: 480px), screen , (max-width: 550px) { img[class="width320"] { width: 320px !important; } img[class="autoheight"] { height:auto !important; } } when add them html - <tr> <td width="700" class="" style="display: block;" border="0"> <img src="welcome_woodbottom.jpg" class="width320 autoheight" height="26" width="700" border="0" alt="" style="display:block;" /> </td> </tr> both styles not work. styles work individually, not when together. when inspect code in firebug, classes "width320" , "autoheight" not show in inspector. what missing? can not use multiple classes in email media

context suggester not working in elasticsearch -

i'm using elasticsearch version 1.2.1: i'm following example given in elasticsearch documentation throws error. it may possible i'm missing something. when run query, error is: { "_shards": { "total": 5, "successful": 4, "failed": 1, "failures": [ { "index": "services", "shard": 2, "reason": "broadcastshardoperationfailedexception[[services][2] ]; nested: elasticsearchexception[failed execute suggest]; nested: nullpointerexception; " } ] } } here's complete example: put /services put /services/service/_mapping { "service": { "properties": { "name": { "type" : "string" }, "tag": { "type" : "string"

jquery - Adding values of a particular property from all javascript objects in an array -

i have array of javascript objects: var myobjects = [{figure: 3}, {figure: 5}, {figure: 2}]; i code give me total of 10 based on addition of figure properties of objects in myobjects . what i've tried/done i loop through using jquery's .each() don't feel iterating (and using temporary 'store' variable) elegant. obviously do: myobjects[0] + myobjects[1] etc. - assume there arbitrary amount of objects. i've done similar getting minimum already: var lowest = math.min.apply(null, myobjects.map(function (x) { return x['figure']; })); but equivalent total. you use array.prototype.reduce : var data = [{figure: 3}, {figure: 5}, {figure: 2}], sum = data.reduce(function(memo, c) { return memo + c.figure }, 0); reduce part of ecmascript 5, available in ie9+ , recent versions of other browsers - see this compatibility table .

android download manager download to external removable sd card -

i tried use android download manager download file. request.setdestinationinexternalpublicdir("/myfile", "abc.txt"); enqueue = dm.enqueue(request); so file downloaded /storage/sdcard/myfile/abc.txt . however, external removal sd card, path /storage/sdcard1/ . request.setdestinationinexternalpublicdir defaults /storage/sdcard/ . how can set download path /storage/sdcard1/myfile/abc.txt ? use setdestination instead. example. change environment.getexternalstoragedirectory() hardcoded path. file root = new file(environment.getexternalstoragedirectory() + file.separator); uri path = uri.withappendedpath(uri.fromfile(root), "this_is_downloaded_file.png"); request.setdestinationuri(path);

ruby - Rails - how to add parameter to the "params.require(:model).permit" construction? -

i have following code in controller: def create @company = company.new(company_params) .... end private def company_params params.require(:company).permit(...list of columns...).merge(latlng: geocode) end i need save database column called slug . value of column be slug = params[:company][:name].parameterize the column slug not mentioned in permit list. how add & save information database? thanks

ios - main.lua is not called using Corona Enterprise -

i have made significant changes corona enterprise app writing ios. code using .xib file launch appdelegate, , have removed , loading different appdelegate in main.mm the following main.mm // // main.mm // examples // #import <uikit/uikit.h> #import "coronaapplicationmain.h" #import "myappdelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { coronaapplicationmain( argc, argv, [myappdelegate class] ); } return 0; } this myappdelegate.h // // myappdelegate.h // #import <foundation/foundation.h> #import "coronadelegate.h" @interface myappdelegate : nsobject< coronadelegate > @end and finally, myappdelegate.mm // // myappdelegate.mm // #import "myappdelegate.h" #import "coronaruntime.h" #import "coronalua.h" @implementation myappdelegate - (void)willloadmain:(id<coronaruntime>)runtime { nslog ( @"willloadmain" ); } - (void)

javascript - Angularjs highlighting columns ng-table -

i trying figure out how can highlight column using ng-table directive angular. though understanding on directive in current setup not capable of achieving looking do, have modify myself. i'd know if has had success getting table column highlighting working angular sorting , ng-repeat, doesn't have done ng-table, example appreciated. in table definition, add table-hover class, example: < table ng-table="mytable" class="table table-hover table-striped table-condensed table-bordered" > customize color in app.css .table-hover > tbody > tr:hover { background-color: #dadada; }

ajax4jsf - a4j:ajax nested on h:inputText prevents execution of h:commandButton action on first click -

i have following code: ... <h:inputtext id="valormoedalocal" value="#{pagamentoregistrarmb.valormoedalocal}" styleclass="right dinheiro" size="12" maxlength="12"> <f:convertnumber type="number" minfractiondigits="2" maxfractiondigits="2" /> <a4j:ajax event="change" execute="valormoedalocal" render="valorpagamento" listener="#{pagamentoregistrarmb.calculavalorrealourocorrecao}" /> </h:inputtext> <h:outputtext id="valorpagamento" value="#{pagamentoregistrarmb.valorpagamento}" maxlength="12"> <f:convertnumber type="number" minfractiondigits="2" maxfractiondigits="2" /> </h:outputtext> ... <h:commandbutton id="cbcorrigir"

c++ - How do i fix this code so that it wont pop_back or back() if the vector/stack is empty? -

there wrong stack.h , i'm unsure missing. receiving segmentation fault error. know has "void pop()" , "t top()" functions. i'm pretty sure caused empty stack. editing these 2 functions, how can ensure program run? .cpp file needs have s2.pop outside of (!s2.empty) check. the answer should remove s2.pop() @ end. doesn't make sense there. while (!s2.empty()) { cout << s2.top(); s2.pop(); } // s2 empty now, pop() wouldn't make sense. cout << endl; s2.pop(); you change pop() function to void pop() { if (!empty()) container.pop_back(); } then pop() work on empty stack, top() still crash. can't fix top() easy either, you'd end different behaviours confusing , shouldn't have. or unintuitive implementations bad.

Questions about operators in java? -

i have 1 class: public class prog3 { public static void main(string[] arg){ int k = 0, = 0; boolean r , t = true; r = (t & 0 < (i +=1)); r = (t && 0 < (i +=2)); r = (t | 0 < (k +=1)); r = (t || 0 < (k +=2)); system.out.println( i+ " " + k); } } why results of program are: 3 1 && , || short circuit operators, means: in && , if left side false , right side not evaluated. in || , if left side true , right side not evaluated. while & , | bitwise operators, means both sides evaluated. with @ hand, let's perform each operation: r = (t & 0 < (i +=1)); //true & +=1 -> = 1 r = (t && 0 < (i +=2)); //true && i+=2 -> = 3 r = (t | 0 < (k +=1)); //true | k +=1 -> k = 1 r = (t || 0 < (k +=2)); //true || ... no need evaluate right side

r - How to replicate a ddply behavior that uses a custom function with dplyr? -

i'm trying replace plyr calls dplyr . there still few snags , 1 of them group_by function. imagine acts same way second ddply argument , split, apply , combine based on grouping variables list. doesn't appear case. here rather trivial example. let's define silly function mm <- function(x) return(x[1:5, ]) now can split species in iris dataset , apply function each piece. ddply(iris, .(species), mm) this works intended. however, when try same dplyr , doesn't work expected. iris %>% group_by(species) %>% mm what doing wrong? as shown in ?do , can refer group . in expression. following replicate ddply output: iris %>% group_by(species) %>% do(.[1:5, ]) # source: local data frame [15 x 5] # groups: species # # sepal.length sepal.width petal.length petal.width species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7

selenium-how to click on link which is nested inside div -

i have div , hyperlink this: <div id="food-add-actions" class="actions food_dialog fd_food_dialog_s-fndds2-f41210000"> <div class="right"> <a href="javascript://" class="food-add-button add button"><span></span><span>add food log</span></a> <a href="javascript://" class="edit button"><span></span><span>edit</span></a> </div> </div> how can click on edit hyperlink? i tried below did not worked me driver.findelement(by.classname("edit button")).click(); the problem have have space in by.classname. there question similar problem here. webdriver classname space using java you should able select by.css selector, such as. by.css('.right a.button')

c++ - Is it possible to add some condition to `boost::signal` -

is possible add condition boost::signal . may boolean function , when emit signal should check if function returns true emit. i don't want check condition during emitting because emitted many places. don't want check condition in slot because should not know condition. if need emit signal many places way, add method it: void emitsignal() { if( /* condition */ ) { _signal(); } } then call emitsignal() instead of emitting signal directly.

jquery - Success function not executing in ajax while using ashx hanler -

i uploading data , image using ashx handler , working fine. but success function in ajax not getting executed see here: $.ajax({ type: "post", url: "../scripts/uploadify/uploadhandler.ashx", contenttype: false, processdata: false, data: imag, success: function(data){ console.log(data.bb); alert('hii'); } }); ashx: public void processrequest(httpcontext context) { httppostedfile postedfile = context.request.files[0]; if (!(postedfile == null)) { | | } context.response.contenttype = "application/json"; string bb = postedfile.filename; context.response.write(bb); //im getting bb name correctly suppose 'koyla.jpg' context.response.statuscode =

angularjs - Reusable Button Directive -

i got 2 buttons different functions , name, classes same. can create directive buttons? <div class="sub l"> <button class="b week" ng-click='manageday(cadd, csub = csub + 7)' ng-model="csub" ng-init='csub=0'>substract week/button> </div> <div class="sub l"> <button class="b day" ng-click='manageday(cadd, csub = csub + 1)' ng-model="csub" ng-init='csub=0'>substract day</button> </div> how can create button directive out of this? as: <div substract-button></div> var app = angular.module('testapp', [ ]); app.directive('telsavebutton', function() { return{ restrict: 'e', template: '<button type="submit" ng-click="onformsubmit()" >directive button</button>', transclude: true, scope: {

java - Read file from sFtp server -

i'm reading file sftp server , load file database using spring batch framework below code m getting error code: <bean id="cvsfileitemreadermeta" class="org.springframework.batch.item.file.flatfileitemreader"> <!-- read csv file --> <property name="resource" value= "ftp://scmuser:scmuser%40123@172.18.228.32:22/home/scmuser/csv/meta.csv" /> error: org.springframework.batch.item.itemstreamexception: failed initialize reader @ org.springframework.batch.item.support.abstractitemcountingitemstreamitemreader.open(abstractitemcountingitemstreamitemreader.java:142) @ org.springframework.batch.item.support.compositeitemstream.open(compositeitemstream.java:96) @ org.springframework.batch.core.step.item.chunkmonitor.open(chunkmonitor.java:115) @ org.springframework.batch.item.support.compositeitemstream.open(compositeitemstream.java:96) @ org.springframework.batch.core.step.tasklet.taskletstep.op

utf 8 - How do I convert the OpenShift MySQL 5.1 cartridge to UTF-8 -

the default mysql 5.1 cartridge apparently creates tables latin1 character set. have application (review board, python/django application) has issues unless db running utf-8. how change that? can't edit my.cnf because wiped @ next cartridge restart. mysql> show variables 'character_set%'; +--------------------------+----------------------------+ | variable_name | value | +--------------------------+----------------------------+ | character_set_client | latin1 | | character_set_connection | latin1 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | latin1 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+-----------------------

ruby on rails - Listen to Prosody Offline messages directory -

i have developed chat application using prosody , need send push notification when receives message , isn't online. this chat application works webapp written in ruby on rails. i searched lot , didn't found sends push notifications prosody(i found ejabberd had problems ejabberd). decided gem ror monitors directory, can monitor prosody's offline message directory , callback when message couldn't delivered user , send push notification him. i found gem listen guard( https://github.com/guard/listen ) need, don't know should start listener , when should stop since need run aways webapp online. you trying make over-complicated things, because think prosody "black box". in fact need: prosody module, "hooks" offline message , send webapp - see example here: https://github.com/jorgenphi/prosodypush push notification module favorite web framework - think can find tons of ruby gems it.

adding category to new created journal article in liferay -

i trying add category new created article. code here: servicecontext servicecontext = servicecontextfactory.getinstance( journalarticle.class.getname(), actionrequest ); article = journalarticlelocalserviceutil.addarticle( importerconstants.importer_id, importerconstants.group_id, importerconstants.doc_folder_id, titlemap, descmap, content, structureid, templateid, servicecontext ); assetentry ae = assetentrylocalserviceutil.fetchentry( journalarticle.class.getname(), article.getresourceprimkey() ); //returns assetentry assetentrylocalserviceutil.addassetcategoryassetentry(48183, ae); article created without problem, when try call assetentrylocalserviceutil.addassetcategoryassetentry(48183, ae) or assetcategorylocalserviceutil.addassetentryassetcategory(ae.getentryid(), 48183) it won't bring results , table assetentries_assetcategories without changes. number 48183 categoryid from table `assetcategory.

php - codeigniter active record query using two order by -

i'm new in ci, , have question.. my normal sql is: $tb1 = 'se_avg'; $tb2 = 'se_school'; $sql_top = "(select * $tb1 ,$tb2 $tb1.sid = $tb2.sid , gid = '$gid' , avg_mark > $s_mark , $tb1.year = '2014' order avg_mark asc limit 0 , 20) order vg_mark desc"; i wanna rewrite in ci active record. but have no idea put order outside sql: $sql_top = "(select * $tb1 ,$tb2 $tb1.sid = $tb2.sid , gid = '$gid' , avg_mark > $s_mark , $tb1.year = '2014' order avg_mark asc limit 0 , 20) now, ci active record is: $tb1 = 'se_avg'; $tb2 = 'se_school'; $sql_top = $this->db ->select('*') ->from($tb1) ->join($tb2, "$tb1.sid = $tb2.sid", 'left') ->where('gid', $gid) ->where('avg_mark >', $s_mark) ->where("$tb1.year", '2014') ->order_by(&quo