Posts

Showing posts from April, 2014

python - Using subprocess and pkexec -

i'm trying use run command alongside pkexec, says no such file found. process = subprocess.popen(["pkexec cat", "/dev/input/event4"], stdout=subprocess.pipe) line in iter(process.stdout.readline, ''): sys.stdout.write(line) oserror: [errno 2] no such file or directory however, path okay , file there. you want use: subprocess.popen(["pkexec", "cat", "/dev/input/event4"]) since subprocess.popen quotes each entry in list; example same using on commandline: $ "pkexec cat" /dev/input/event4 instead of: $ pkexec cat /dev/input/event4 from the documentation (emphasis mine): args required calls , should string, or sequence of program arguments. providing sequence of arguments preferred, allows module take care of required escaping , quoting of arguments (e.g. permit spaces in file names) . if passing single string, either shell must true (see below) or else string must name progr

c# - How to return a field from another entity in Odata V4 -

i working on odata v4 project , wish return field table in result set. so have 2 tables account: id, name, address, colorcode, product: id, accountid accountid foreign key mapped id field in account table i have following partial class public partial class product { public string colorcode { { return account.colorcode; } } public datetimeoffset? edmcreated { { return created ; } } } and controller: [enablequery(pagesize = 200)] public iqueryable<product > get() { return _db. product.asqueryable(); } this returns data product data entity cant seem colorcode field in result set. how can achieve above please refer answer other question: how join 2 entities in odata model builder and in addition, don't need write specific $expand , $select in request url mentioned in answer. enablequery attribute in products

svg - manipulate mouseover "hit area"in d3.js -

i'd show , hide node in svg when mouseover / mouseout , issue shape inside node path 1.5px width not easy hit area in mouseover event, that's inconvenient user experience. i'd know if there's way make hit area wider using arbitrary width, invisible user? a snippet of code: link.enter() .append('g').attr('class', 'link') .append('line') .attr('class', 'path') .attr('marker-end', function(d, i) { if (i === 2) { return 'url(#arrow)'; } else { return null; } }).on('mouseover', function(d) { //alert(json.stringify(d)); alert('mouseover'); }).on('mouseout', function(d) { alert('mouseout'); }); the css: .node .path { stroke: #878f8f; stroke-width: 1.5px; fill:none; } you can add line g transparent stroke , large stroke-width, increase hit area. //

django - How to read a csv file script Python? -

how read csv file script python? import csv open('some.csv', 'rb') f: reader = csv.reader(f) row in reader: print row gives error python2 test.py traceback (most recent call last): file "test.py", line 1, in <module> import csv file "/home/miruss/virtualbox/csv.py", line 4, in <module> f = open(sys.argv[1], 'rt') indexerror: list index out of range the reason error not understand. your error comes "sys.argv[1]". you meant execute code against file name. python2 test.py filename.csv

JavaScript LetterGrade function -

i want write function using conditionals, determines letter grade numerical grade, passed in parameter. have correctly written in python, not sure javascript. in js, keeps returning "you made b", "you made a(n) c", ... , "you made a(n) f", no matter number place function. function lettergrade(grade) { if (100>=grade && grade >= 90) { alert('you made a(n) a.');} if (80 <= grade && grade< 90) { alert('you made a(n) b.');} if (70<= grade && grade < 80) { alert('you made a(n) c.');} if (60<= grade && grade < 70); { alert('you made a(n) d.');} if (0<= grade && grade < 60) { alert('you made a(n) f.');} }

f# - Completely lost in trying to mutate property in sequence -

i @ loss why code doesn't mutate member variable in sequence of types: for p in prescrs p.atc <- "a" c in p.drug.components s in c.substances s.dosetotal.adjust <- adjustkg s.dosetotal.time <- "day" s.dosetotal.unit <- s.drugconcentration.unit s.doserate.adjust <- adjustkg s.doserate.time <- "day" s.doserate.unit <- s.drugconcentration.unit prescrs sequence of prescriptions simple 'poco' defined type member values. don't have clue why doesn't work. i tried simple test case like: type itertest () = member val name = "" get, set member val itertests = [] |> list.toseq : itertest seq get, set let iterseq = [ new itertest(name = "test1") new itertest(name = "test2") ] |> list.toseq iterseq |> seq.iter(fun x -> x.itert

c# 4.0 - accented chars in windows 8.1 embeded Sqlite -

i'm in struggle sqlite , accented chars such á or é. what i'm trying select accent insensitive. select * customers name "%risque%" in database -> id =1; name=risqué -> id =2; name=risque second d the select return record id =2 name=risque second i've tried: select * customers name "%risque%" collate nocase select * customers name "%risque%" collate noaccents

angularjs - Angular print string array without quotes -

i have simple string array coming server: [{"things":["me", "my"]}] in page, display array have: {{things}} and prints: ["me", "my"] how control printing, instance, if want eliminate brackets , quotes? you can implement scope function display arrays comma separated strings shown in this fiddle . $scope.array = ["tes","1","2","bla"]; $scope.arraytostring = function(string){ return string.join(", "); }; now can call function within template: {{arraytostring(array)}} update you can use join() method of arrays directly within template without using function inbetween displayed within updated fiddle . {{array.join(", ")}}

c# - Session variable does not maintain value across different controllers -

i working 2 controllers, both save value session 1 of controller manages maintain it's value. the line of code saves value is session["logindate"] = <datetimeobject>; and same in both controllers . second controller gets called first controller , while in second controller, if set value of session we're ok until in calling controller. if call first controller only, value can set , sent client. i have tried modifying second config file include <sessionstate mode="inproc" timeout="30" /> and have made sure @ same version of .net, mvc, etc... any ideas how debug this? else should check? update there way pass session state different servers or usign cookies better since cookie on client browser? new discovery second controller an redirect("serverofcontroller_1"); the controller gets initialised mvc core, has correct references context of current request. when create instance of controller yourse

c++ - Find previous power of 2 in 64 bit number -

// objective : verify 64 bit input power of 2.if number not power of 2, find previous value , power of 2. using namespace std; int main() { //input. 64 bit number unsigned long long int input = 13174607262084689114; //check number power of two. if (!((input && (input & (input - 1))) == 0)) { cout<<"the number not power of 2"<<endl; //find previous value of input, should power of 2. //step 1 : find next power of 2 input. //step 2 : divide number 2 /*end*/ // step 1 input |= input >> 1; input |= input >> 2; input |= input >> 4; input |= input >> 8; input |= input >> 16; input |= input >> 32; input = input + 1; // input holds next number , power of 2. // step 2 input = input >> 1; cout<<"power of 2: 64 bit: "<<input<<endl; } return 0; } (!((input) && (input & (input - 1)))

shell - Specifying a non-sequential array for the SGE task ID -

i submit job array list of non-sequential numbers sge_task_id , error says, "the initial portion of string 'file.sh' doesn't contain decimal numbers". suggestions? i have file containing values use sge_task_ids. call file "tasknumbers" (exactly how appears in file). 3 5 10 25 50 100 i have shell script retrieve values input sge_task_ids #!/bin/sh #taskid.sh taskid=~/folder/tasknumbers id=$(awk "nr==sge_task_id" $taskid) i have additional file sge_task_id used input parameter call file.sh (this wrapper takes task id , inputs value in test). in terminal typed (which returns error): qsub -cwd -n output -t $id ./file.sh -pe the error: qsub: numerical value invalid! initial portion of string "./file.sh" contains no decimal number maybe work: tasknumbers file: 1 3 5 10 25 50 100 use loop submit 1 job per task id: for id in `cat tasknumbers` qsub -cwd -n output -t $id ./file.sh -pe done

jquery - Retrieve nested javascript objects in Django view as a dict -

i have simple view receives ajax request containing javascript object. jquery request looks this: $.get(url, {'kwargs': {test: 1}}, function(data){//whatever}) the problem is, request.get contains rather strange key , looks this: {'kwargs[test]': [1]} how can decode this? side note, impossible know key (test) beforehand the expected format obtained python dict looks 1 in request. i've tried: request.get.get('kwargs', none) and i'd expect result: {'test': 1} however, none, real key 'kwargs[test]' edit i know use kind of regex accomplish this, feels 'reinventing wheel', use case not rare i recommend using json when communicating , forth between server , client type of situation. json meant handle these types of nested structures in uniform manner. take @ using jquery $.getjson functionality, http://api.jquery.com/jquery.getjson/ the following example of how structure look... javscript va

sql - Rewriting the HAVING clause and COUNT function -

i'm trying conceptually understand how rewrite having clause , count function. i asked "find names of reviewers have contributed 3 or more ratings. (as challenge, try writing query without having or without count.)" in relation this simple database: http://sqlfiddle.com/#!5/35779/2/0 the query having , count easy. without, i'm having difficulty. help appreciated. thank you. one option use sum(1) in place of count in subquery, , using where instead of having : select b.name (select rid,sum(1) sum1 rating group rid )a join reviewer b on a.rid = b.rid sum1 >= 3 demo: sql fiddle update: explanation of sum(1) : adding constant select statement result in value being repeated every row returned, example: select rid ,1 col1 rating returns: | rid | col1 | |-----|------| | 201 | 1 | | 201 | 1 | | 202 | 1 | | 203 | 1 | | 203 | 1 | ...... sum(1) applying constant 1 every row , aggregating it.

javascript - Replacing mutliple characters -

i trying write function parameter string , specific character needs replaced. give alert box converted string. i have following code isn't working. want alert() converted string. function encryption(astring){ return astring.replace(/a/g, '@') .replace(/e/g, '()') .replace(/h/g, '#') .replace(/l/g,'1') .replace(/r/g,'+') .replace(/s/g.'$') .replace(/v/g,'^') .replace(/x/g,'*'); } at first sight see typo here .replace(/s/g.'$') it should .replace(/s/g,'$') you can see working here after fixing typo

java - Rescale JFrame content -

i creating jframe , , when window expanded want content stay centered, instead of staying same distance away side. using windowbuilder on eclipse. is there quick way this? one way, have container use gridbaglayout , add single content container without constraints. for example: import java.awt.gridbaglayout; import java.awt.image.bufferedimage; import java.io.ioexception; import java.net.url; import javax.imageio.imageio; import javax.swing.*; public class centeredcontent extends jpanel { public static final string img_path = "https://duke.kenai.com/iconsized/duke.gif"; public centeredcontent() throws ioexception { url imgurl = new url(img_path); bufferedimage img = imageio.read(imgurl); icon imgicon = new imageicon(img); jlabel label = new jlabel(imgicon); setlayout(new gridbaglayout()); add(label); } private static void createandshowgui() { centeredcontent mainpanel = null; try { ma

windows 7 - How to set path to ruby on win 7 -

i using git-bash in win7. have installed c:/ruby/bin/ruby.exe. i've added c:/ruby/bin/ path environmental variable , restarted. when do: $ ruby /c/opscode/chef/embedded/bin/ruby $ echo $path /c/ruby/bin:/c/st:/c/users/bill/bin:.:/usr/local/bin:/mingw/bin:/bin:/c/windows/system32:/c/windows:/c/windows/system32/wbem:/c/windows/system32/windowspowershell/v1.0/:/c/program files (x86)/quicktime/qtsystem:/c/python27:/c/python27/lib/sitepackages/django/bin:/c/python27/scripts:/c/mingw/bin:/d/opscode/chef/bin:/d/opscode/chef/embedded/bin:/d/virtualbox/vboxmanage:/d/hashicorp/vagrant/bin:/c/opscode/chef/bin:/c/opscode/chef/embedded/bin:/c/programdata/composer/bin:/c/program files (x86)/git/cmd:/c/nodejs/:/c/users/bill/appdata/roaming/npm:/c/ruby193/bin how change "c:/ruby/bin/" ? add following line /c/users/your-username/.bashrc file make /c/ruby/bin placed before other directory in path : export path=/c/ruby/bin:$path or, start git bash, , issue following

javascript - Add Class to element according to pathname -

this script works great adding class "criminal" div named "h1_wrapper" page: if(window.location.pathname == '/criminal-law-blog') {$( ".h1_wrapper" ).addclass( "criminal" ); when click specific blog entry, adds pathname; example: /criminal-law-blog/2014/11/criminal-law-blog-test-entry-1 how edit code make class added path follows "/criminal-law-blog"? know it's easy, can't figure out! thanks in advance! the simplest way window.location.pathname.match(/^\/criminal-law-blog/)

Is possible to use F# pattern matching as a solver/library for another language or DSL? -

i'm building toy language, want have pattern matching. build whole thing (and don't know how) because in f# wonder if can defer whole thing it. so, have interpreter , custom syntax. if give ast, possible use f# use solve pattern matching? another way @ this, possible use f# pattern matching c# , other .net languages? for example, if program (in invented syntax f#): case x ( 1 , 2 , three): print("found 1, 2, or 3!") else var1: print("%d" % var1) is possible matched, error = f#magichere.match(evaluatemyast) i'm not sure if understand question correctly, suspect use f# compiler service need. basically, compiler service lets call of tasks compiler performs (and normal .net library). the first step turn ast valid f# code - guess find systematic way of doing (but requires thinking). can use f.c.s to: type-check expression, gives warnings overlapping cases , missing cases (e.g. when have incomplete patte

git - cloned a branch modified it, pushed it to my own branch but github folders are not accessible -

i cloned branch, modified code, used git remote set-url origin git@github.com:username/repository2.git git add -a git commit -am "pushing code" git push origin there 3 folders in it. but when go browse branch, can not click on folders. git status doesn't show new , git remote -v shows branch. the main folder main github branch have , individual folders clones of other repos. want have files on main github branch. how can accomplish that? fixed running git rm --cached on path on directories , removing .git in sub directories

Finding anagrams in Python -

i solved problem following way in python: s1,s2 = raw_input().split() set1 = set(s1) set2 = set(s2) diff = len(set1.intersection(s2)) if(diff == 0) print "anagram!" else: print "not anagram!" it seemed fine me. professor's program said i'm missing edge cases. can think of edge cases might have missed? the correct way solve count number of characters in both strings , comparing each of them see if characters same , counts same. python has collections.counter job you. so, can do from collections import counter if counter(s1) == counter(s2): print "anagram!" else: print "not anagram!" if don't want use counter , can roll own version of it, normal dictionaries , compare them. def get_frequency(input_string): result = {} char in input_string: result[char] = result.get(char, 0) + 1 return result if get_frequency(s1) == get_frequency(s2): print "anagram!" else:

ios - Passing indexpath to performsequewithidentifier from uitablerowaction button -

here delegate method: -(nsarray *)tableview:(uitableview *)tableview editactionsforrowatindexpath:(nsindexpath *)indexpath { uitableviewrowaction *button = [ uitableviewrowaction rowactionwithstyle:uitableviewrowactionstyledefault title:@"more" handler:^(uitableviewrowaction *action, nsindexpath *indexpath) { [self performseguewithidentifier:@"areadescriptionsegue" sender:indexpath]; nslog(@"more button tapped"); } ]; button.backgroundcolor = [uicolor graycolor]; //arbitrary color return @[button]; //array buttons want. 1,2,3, etc... } and here prepareforsegue : - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { if ([[segue identifier] isequaltostring:@"areadescriptionsegue"]) { nslog(@"segue areas screen"); nsindexpath *newindexpath = [self.listtableview indexpathforcell:sender]; areadescriptioncontroller *vc = (areade

sqlxml - Xquery syntax error in SQL server 2012 -

i want return character 'o' in sql database while working xml data wrote following query: use master select song_type.query ('table/[where o.name % o %]') xmldata but program returned error saying: msg 9341, level 16, state 1, line 2 xquery [xmldata.song_type.query()]: syntax error near '[', expected step expression. please how fix this. try ... select * xmldata cast(convert(varchar(max),song_type) xml).value("o.name[0]","varchar(500)") '% o %'

tomcat - Best way to increase heap size in catalina.sh file for XWiki? -

i trying configure xwiki on ubuntu 14.0.4 project. keep getting error says: java.lang.outofmemoryerror: java heap space. have tried google'ing solution, nothing have found has worked. majority of solutions allocate more memory jvm in catalina.sh file, using line such "catalina_opts="-xmx800m -xx:maxpermsize=192m". how implement change/where put in catalina.sh file? help. how did installed tomcat ? if trough apt-get have few information on http://platform.xwiki.org/xwiki/bin/view/adminguide/installationviaapt#htomcatusability . standard tomcat debian package supposed configured using /etc/default/tomcat7 (change version depending on tomcat version).

qt - Recursive repaint detected in popup window -

i have qpushbutton open new window on clicked. void shownewwindow() { popupwindow *popup = new popupwindow(); popup->show(); } and popupwindow declared following: class popupwindow : public qwidget { q_object public: popupwindow(qwidget* parent); void setcontent(qstring content) { this->content = content; } qstring getcontent() { return content; } private: qstring content; private slots: void handlecontinue(); void handleruntoend(); }; then implement constructor: popupwindow::popupwindow(qwidget *parent):qwidget(parent) { qhboxlayout *hlayout = new qhboxlayout(); qwidget *buttonwidget = new qwidget(); qpushbutton *btncontinue = new qpushbutton(); btncontinue->settext("continue"); qpushbutton *btnrunend = new qpushbutton(); btnrunend->settext("run till completion"); buttonwidget->setlayout(hlayout); hlayout->addwidget(btncontinue); hlayout->addwidget(btnrunend); connect(btncontinue,signal(click

Run "sudo chef-client" from workstation -

i trying figure out way can run "sudo chef-client" workstation. tried following way failed. c:\users\administrator\chef-repo>knife ssh name:node1 -a hostname -x windows -i knife.pem "sudo chef-client" fatal: 1 node found, not have required attribute establish connection. try setting attribute open connection using --attribute.” any guidance? your node doesn't have hostname attribute set. try -a ipaddress instead use default ip address on machine. for posterity, based on comments below user unclear windows hosts don't run ssh daemons , knife ssh cannot used. knife winrm recommended option windows nodes.

c# - Black Background occurs when using microsoft.windows.shell -

i using microsoft.windows.shell customize wpf window chrome. fine until added datagrid. problem appearance of window become black sometimes. situation not happen constantly! looks fine has black background. here xaml code: <window x:class="codegeneratorwpf.config" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="config" height="300" width="300" style="{staticresource mainwindowstyle}" windowstartuplocation="centerowner" loaded="window_loaded"> <grid> <grid.rowdefinitions> <rowdefinition height="*"/> <rowdefinition height="40"/> </grid.rowdefinitions> <datagrid name="datagrid" grid.row="0" itemssource="{binding data}" alterna

sql - Synchronizing client-server databases -

i'm looking general strategies synchronizing data on central server client applications not online. in particular case, have android phone application sqlite database , php web application mysql database. users able add , edit information on phone application , on web application. need make sure changes made 1 place reflected everywhere when phone not able communicate server. i not concerned how transfer data phone server or vice versa. i'm mentioning particular technologies because cannot use, example, replication features available mysql. i know client-server data synchronization problem has been around long, long time , information - articles, books, advice, etc - patterns handling problem. i'd know general strategies dealing synchronization compare strengths, weaknesses , trade-offs. the first thing have decide general policy side considered "authoritative" in case of conflicting changes. i.e.: suppose record #125 changed on server on ja

http - The web application does not utilize HTTPonly cookies -

how avoid cross-site scripting attack not allowing cookies httponly attribute accessed via client-side scripts. using asp.net 3.5, iis 8 , ie9 browser. (it should provide security web browser). after surfing many sites, found solution question: this new security feature introduced microsoft in ie 6 sp1 mitigate possibility of successful cross-site scripting attack not allowing cookies httponly attribute accessed via client-side scripts. recommendations include adopting development policy includes utilization of http cookies, , performing other actions such ensuring proper filtration of user-supplied data, utilizing client-side validation of user supplied data, , encoding user supplied data prevent inserted scripts being sent end users in format can executed. regarding secure cookies add below line under web.config file <system.web> <httpcookies httponlycookies="true" requiressl="false" /> <system.web> requiressl=

javascript - Generate methods at runtime in emberJS -

im trying generate few methods @ runtime in ember , code i'm trying is app.testcontroller = ember.arraycontroller.extend app.anothermixin, unsubmitted: em.computed.filterby("model", "unsubmitted", true) submitted: em.computed.filterby("model", "submitted", true) canceled: em.computed.filterby("model", "canceled", true) # rather using above methods i'm trying generate them meta-programming. that: @ defineattributes: (-> [ "unsubmitted" "submitted" "cancelled" ].foreach ( f ) -> em.defineproperty , f, em.computed.filterby("model", f, true) return return ).on("init") but not generating methods. there im missing? you're defining that property on controller, trying use local variable in defineattributes method. change that local variable in method , should work fine. or better yet, use coff

redirect STDERR of eval to /dev/null in perl -

eval {require $testrequirepath}; while running above, if there syntax error in $testrequirepath file, prints stdout. want redirect /dev/null . how can it? what seeing warning, not error; errors captured eval , placed in $@. suppress warnings also, can do: eval { local $sig{__warn__} = sub {}; require $testrequirepath }

Why does my Celery worker die with signal 6 - SIGIOT? -

i'm running celery based application. every , see following in log: [... error/mainprocess] task [...] raised unexpected: workerlosterror('worker exited prematurely: signal 6 (sigiot).',) traceback (most recent call last): file "/usr/local/lib/python2.7/dist-packages/billiard/pool.py", line 1170, in mark_as_worker_lost human_status(exitcode)), workerlosterror: worker exited prematurely: signal 6 (sigiot). perhaps can come explanation this?

javascript - angular show inputs base checkbox ng-model make inputs unreachable -

please help, have following code <div> <input type="checkbox" id="chk1" ng-model="status" /> <span ng-bind="title"></span> </div> <div id="div1" ng-show="status"> <span ng-bind="spantitle" ></span> <input type="text" id="txtlastname" ng-model="lastname" ng-click="lastnameclick()" ng-blur="lastnameout()" name="txtlastname" /> </div> and when checkbox being checked div1 shown input text cannot clicked or written. any idea please? edit : added controller user's comment function dcontroller($scope) { var defaultinputtext = "hello"; $scope.title = "check"; $scope.spantitle = "span"; $scope.status = false; $scope.lastname = defaultinputtext; $scope.lastnameclick = function () { if (

html - Possible to swap position of div elements using CSS? -

in example there 2 div, wanted first div come down after second div using css let suppose below example <!doctype html> <html> <head> </head> <body> <div class="div1" > first div. </div> <div class="div2" > second div. </div> </body> </html> above code give output below this first div. this second div. but wanted output should be this second div. this first div. don't use margin top:20px because text in mycase bigger in example. here go. use table. must work on 3 elements, container , 2 containing elements. #container { display:table; width: 100%; } #first{ display:table-footer-group; } #second{ display:table-header-group; } <div id ="container"> <div id = "first">this first div</div> <div id = "second">this second div</div> </div

javascript - Display div on mouse hover -

i have link id="show" in header , div id="display" in footer. want display div id="display" when mouse hover on id="show" in header area , div in footer area. html code: <header> <a href="#" id="show"><span> show div </span></a> </header> <---- other content --> <footer> <div id="display"> --- content --- </div> </footer> try : can use .hover() function shown below. pass comma seprated functions it. first function call when mouseover , second mouseleave event. $(function(){ $('#show').hover(function(){ $('#display').show(); },function(){ $('#display').hide(); }); }):

regex - php preg_match() code for comma separated names -

i need validate input patterns using preg_match() patterns " anyname1,anyname2,anyname3, ". note there comma @ end too. letter or number valid between commas, numbers not have appear @ end. e.g "nam1e,na2me,nnm22," valid. i tried ^([a-za-z0-9] *, *)*[a-za-z0-9]$ did no work. have gone through other posts did not perfect answer. can give me answer this? it sounds want validate string contains series of comma separated alpha-numeric substrings, optional trailing comma. in situation, should achieve want. $str = "anyname1,anyname2,anyname3,"; $re = '~^([a-z0-9]+,)+$~i'; if (preg_match($re, $str)) { // string matches pattern! } else { // nope! } if value stored in $str contains trailing space in example, , don't want use trim() on value, following regex allow whitespace @ end of $str : ~^([a-z0-9]+,)+\s*$~i

c# - Generic object to generic object with Automapper -

i have problem copy generic object generic object public class customer { public int customerid { get; set; } public virtual icollection<quote> quotes { get; set; } } i use generic class copy object object : public static class genericautomapper { public static void propertymap<t, u>(t source, u destination) t : class, new() u : class, new() { mapper.createmap(typeof(t), typeof(u)); mapper.map<t, u>(source); //crash here } } when customer (using ef 6.1.2) , use method, on error on "crash here" line. quotes collection : '((system.data.entity.dynamicproxies.customer_ac635ad71ac95634ef9694fdc434135b488fd116f3c2b6a287846a7886521f3f)source).quotes' i don't have problem when include : .include(x => x.quotes) in query, normal collection loaded. is there way manage "not loaded" collection ? thanks, you need either turn off lazy loading or execute query before map

javascript - Load webpage from different domain -

i creating sample project in mvc. suppose have 2 projects , b. in project have javascript file takes index page of project a , put in div having id widget . in project b index page have reference javascript file of project , div id widget . on page load want load project a's index page project b's widget div . here code project index.cshtml (index view) @{ viewbag.title = "index"; } <h2>index</h2> <div id="data">thi index page.</div> widget.js (javascript file) $(document).ready(function (e) { $('#widget').load('/home/contact', function (response, status, xhr) { if (status == "error") { var msg = "sorry there error: "; alert(msg + xhr.status + " " + xhr.statustext); } }); }; here project project b index view call project a's index view @{ viewbag.title = "index"; } <script src="~/scripts/jquery-1.10.2.min.js">

c# - User gets logged out with 'Remember me' -

i seem have trouble understanding way identity 2.0 , cookies work. asp.net mvc 5. what want: if user logs in , checks checkbox 'remember me', don't want him logged out ever.. happens is: user gets logged out after timespan. the 'remember me' functionality works if user closes browser before timespan. (when reopens website, he's still logged in.) this code have signing in: public async task<actionresult> login(loginviewmodel model, string returnurl) { if (!modelstate.isvalid) { return view(model); } // require user have confirmed email before can log on. var user = await usermanager.findbynameasync(model.email); if (user != null) { if (!await usermanager.isemailconfirmedasync(user.id)) { await sendemailconfirmationtokenasync(user.id); modelstate.addmodelerror("", "gelieve eerst je e-mailadres te bevestigen.");

c# - Can a ForEach lambda expression have an optional return type -

is there way foreach lambda expression have optional return type. here pseudo code example of needs achieved: string val = mylist.foreach(listitem => { if(listitem == "yes" ){ return "found" } }); if(val == "found"){ dosomething } no, foreach wrong method result. use any : bool found = mylist.any(listitem => listitem == "yes");

javascript - Cancel uploads in onStatusChange -

in our system allow uploads specific number can done in multiple upload sessions. when number of images in upload session exceed maximum number cancelling uploads in onstatuschange() instead of adjusting itemlimit: thumbnailuploader = new qq.fineuploader({ element: document.getelementbyid('thumbnail-fine-uploader'), template: "qq-simple-thumbnails-template", request: { endpoint: 'uploader/uploader.php' }, thumbnails: { placeholders: { waitingpath: "uploader/waiting-generic.png", notavailablepath: "uploader/not_available-generic.png" } }, validation: { allowedextensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp'], itemlimit: 6 }, callbacks: { onsubmit: function(id, filename){ // console.log("submitting..." + id); }, onstatuschange: function (id, oldstatus, newstatus) { // check see if fil

c# - How to toggle visibilty of a Wizard Page of Devexpress XtraWizard control -

i have problem: using devexpress wizard control , want toggle visibility of wizardpage on basis of checkbox input. problem: if suppose checkbox checked wizard page x must visible while going , fro in wizard control else page should not visible. what have tried: tried toggle visibility in selectedpagechanging event - didn't success tried add or remove page parent control - didn't success please me out in this.. you could: handle selectedpagechanging event . check page property of event arguments page right before page show/hide. if true, set cancel property true . set selectedpage desired page, depending on checkbox a's state. you optionally theck direction property see whether user navigating forward or backward. general hint: when dealing devexpress questions/issues, devexpress support center useful location ask questions or browse solutions. even stack overflow cannot compete there speed , depths of anwsers (imho). so i

php - Get the returned value from a prepared statement MySQL -

i trying make stored procedure want random value on database table name , other conditions of query dynamic (in stored proc params). drop procedure if exists `myproc`; delimiter // create procedure `myproc`(in `tablename` varchar(50), in `isshow` tinyint(1), in `isadd` tinyint(1)) begin set @tname := tablename; set @isshow := isshow; set @isadd := isadd; set @pcode := ''; set @s = concat('select t.pcode ', @tname, ' t join (select round(rand() * (select max(idx) ', @tname,' )) id) x t.idx >= x.id , t.isshow = ', @isshow,' , t.isadd = ', @isadd, ' limit 1'); checkhand: while (!@pcode) prepare sp_query @s; execute sp_query; deallocate prepare sp_query; leave checkhand; end while ; end // delimiter ; since use @var tablename, referred so , create sql query in concat run stored procedure .

javascript - Create a simpler way of nesting functions -

i'm looking lower overhead on code this foo(bar(baz("hello"))) // function hell ideally this var fbb = bind(foo, bar, baz) foo("hello") does exist? native or library? i looked through underscore , bind . underscore has compose function want: var composite = _.compose(foo, bar, baz); composite('hello'); function foo(a1){ return 'foo' + a1; } function bar(a2){ return 'bar' + a2; } function baz(a3){ return 'baz' + a3; } alert(foo(bar(baz("hello")))); var composite = _.compose(foo, bar, baz); alert( composite('hello') ); <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

java - How to execute selected methods of a given class -

for example, class { @test public int add() { .... } @test public int sub() { .... } @test public int div() { .... } @testnew public void mul() { .... } } consider class named a..in class have annotated methods , want display methods has annotation @test. can done using java reflection's getannotation() methods. i'm getting proper output this. i've list of @test annotated methods displayed in jsp page precede checkbox each , every entry of output. for example: int add() [*] int sub() [*] int div() [] [execute] consider square brackets checkboxes. [*] -->selected checkbox.. [ ] -->not selected checkbox... now,i want execute selected check box methods , display result. need generate xml files selected methods know much. don't know how can generate xml files selected methods result of selected methods. once select

I can't understand 'commons-dbcp uses static interfaces' mean from tomcat-dbcp menual -

i found tomcat-dbcp description tomcat web site . , could't understand below explanation. commons-dbcp uses static interfaces. means can't compile jdk 1.6, or if run on jdk 1.6/1.7 nosuchmethodexception methods not implemented, if driver supports it. why static interface not able compile jdk 1.6? , why nosuchmethodexception invoked on jdk 1.6/1.7 ?

Background Music in Android Continously and Forced Close -

well have set of codes activity. have app have more 10 activities. , want have continously background music, stop whenever go activity. , when i'm in activity (also in other activities) when click home button of emu or device, , application "forced closed" hope can me. thankyou public class advancedkids extends activity implements onclicklistener { mediaplayer yourstereo; assetfiledescriptor afd; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.advancelay); view numbers = this.findviewbyid(r.id.button1); numbers.setonclicklistener(this); view alphabets = this.findviewbyid(r.id.button2); alphabets.setonclicklistener(this); view colors = this.findviewbyid(r.id.button3); colors.setonclicklistener(this); view shapes = this.findviewbyid(r.id.button4); shapes.setonclicklistener(this); view back= this.findviewbyid(r.id.buttonback); back.setonclickliste

paypal - Incomplete Delayed Chained Payment Fees Payer -

i'm setting delayed chained payment in php i'm setting feespayer secondaryonly $payrequest->feespayer = 'secondaryonly'; the transaction made primary receiver but second leg of chained payment (from primary secondary receiver) still pending. then 90 days passed (paykey expired) , did not complete payment. who pays fees when paykey expires? based on messages paypal's support, tell no 1 pay fees because payment reverted buyer ! if didn't complete payment, go , not able change receivers during 90 days.

scala - Spark rdd write to Hbase -

i able read messages kafka using below code: val ssc = new streamingcontext(sc, seconds(50)) val topicmap = map("test" -> 1) val lines = kafkautils.createstream(ssc,"127.0.0.1:2181", "test-consumer-group",topicmap) can please me how can write each message read kafka hbase? trying write no success. lines.foreachrdd(rdd => { rdd.foreach(record => { val = +1 val hconf = new hbaseconfiguration() val htable = new htable(hconf, "test") val theput = new put(bytes.tobytes(i)) theput.add(bytes.tobytes("cf"), bytes.tobytes("a"), bytes.tobytes(record)) }) }) well, not executing put, mereley creating put request , adding data it. missing htable.put(theput);

mysql - SQL Join over two tables -

here problem: i have 2 tables. every entry of table has several entries in table b matched on id. want entries of table 1 data entry of table b - 1 highest id in table. table has id table b has own id , id_of_table_a (for relation between both) table has 1 many relation table b. want entries of table a, matched 1 highest id out of b. there way realize in sql statement? tried kinds of joins since need information of matched entry in outcome of select. how about select * tablea inner join tableb b on a.id = b.id_of_table_a b.id = (select max(id) tableb c b.id = c.id)

mysql - Performance between trigger and ordinary update query -

i in great confusion performance between trigger , ordinary update query. in site running cron operation in consists of 2 tables 1. cron log table 2. metadata table crons runs every minute. there 2 ways(i think) update both table, i fetching datas cron log table , calling wistia api upload files. after getting response wistia can update status in both tables via code. i fetching datas cron log table , calling wistia api upload files. after getting response wistia can update status in "cron" table via code , can use trigger update "metadata" table after cron table update. i don't know whether right hit metadata table regualarly when site fetching datas there. in 2nd step in confusion trigger may take time fetch data , update metadata table. trigger has no control on there. please suggest me steps high performance. better trigger or update ?

java - Can ScheduledThreadPool be use to accept different type of threads? -

working on problem have 3 cash counters serving number of customers. every counter take 1 sec process 1 item apart third counter takes 2 sec process each item. (e.g. customer 5 items on counter 1 take 5 seconds complete), customer b 3 items on counter c take 6 seconds. every customer has different time of joining queue. used scheduledexecutorservice create number of threads equivalent cash counters. scheduledexecutorservice scheduledexecutorservice =executors.newscheduledthreadpool(3); now runnable implementation checks number of items , runs loops accordingly. i submitting number of task depending on number of customer. scheduledexecutorservice.schedule(new runnable(),timetojoin, timeunit.seconds); how assign different priorities 3 threads created executor service. last counter(thread) takes 2 second process each item. you have provide custom threadfactory executorservice . threadfactory allow create new threads suit needs. scheduledthreadpoolexecutor(int

php - REQUEST_FILENAME consider requset as real file in live server but in local consider it as not file -

i have htaccess <ifmodule mod_rewrite.c> rewriteengine on rewriterule ^(mdiet|user)($|/) - [l] rewritecond %{request_filename} !-f rewritecond %{request_uri} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [nc] rewriterule ^(.*)$ route.php?q=$1 [nc,qsa,l] </ifmodule> when call url in localhost: http://localhost:8080/comm_cvs/comm/web/group_items htaccess undestand group_items not file , redirect request route.php , went ok. but when move code server: behaivior not expected when call: www.mysite.com/group_items => htaccess consider file , go group_items.php directly without redirect route.php. what's problem in live server??

php - [Joomla 3+]How to show K2 Category, to a user assigned to it -

i have problem or situation want show k2 category/categories user assigned specific category, if user logged in. right display categories if user logged in or not, , can add items/articles specific category assigned if he/she's logged in works expected. here knows how solve it? or suggestions how can make work? appreciated. joomla 3.3.6 k2 v2.6.7 if can code create plugin in maintain mapping of k2 usergroup allowed k2 categories catch onafterroute trigger , add code check k2 usergroup of user , allowed k2 category. function onafterroute() { $user = jfactory::getuser(); $groups = $user->groups; $jinput = jfactory::getapplication()->input; $option = $jinput->get('option', ''); $view = $jinput->get('view', ''); $task = $jinput->get('task', ''); // place k2-user-group related checking here } i not sure view, task , other variables k2 adds in url while displaying category in front-e

c++ - QML applicatin crashes; How to Debug? -

there crash in qml application. there way debug find initiates? thanks in advace. yes, check "enable qml" check box in creator before debugging: in run settings, debugger settings section, select enable qml check box enable qml debugging. as mentioned though, if have c++ code, problem lies there, , shouldn't need enable qml debugging; debug code usual.

android - 'node' is not recognized as an internal or external command error with jenkins -

i trying set continuous code integration of jenkins v1.592 have android hybrid code, i'm, trying build jenkins. have set environment variables ant_home, java_home, android_home, , added path respectively. have added nodejs , npm path. ant version 1.9.2 java version 1.8.0_25 npm version 1.4.28 cordova android version 3.5.1 c:\users\username>path gives c:\users\username\appdata\roaming\npm;c:\program files\nodejs;c:\whateverelse... jenkins $workspace = c:\program files (x86)\jenkins\jobs\myproject\workspace\ now set cmd prompt jenkins workspace , execute following commands cd myproject cordova build android i build_successful after 24 seconds similarly, when go local jenkins server the jenkins dashboard shown , have set myproject there , in project configuration have added lines "cd myproject cordova build android" in build step , saved configuration. when try build following error started command line anonymous building in

ios - Unable to simultaneously satisfy constraints on opening camera -

i have app use webview show html forms. in html forms there added functionality choose image device. functionality html form capturing image. when click on browse button of form webview camera opens , working fine below log in xcode. snapshotting view has not been rendered results in empty snapshot. ensure view has been rendered @ least once before snapshotting or snapshot after screen updates. unable simultaneously satisfy constraints. @ least 1 of constraints in following list 1 don't want. try this: (1) @ each constraint , try figure out don't expect; (2) find code added unwanted constraint or constraints , fix it. (note: if you're seeing nsautoresizingmasklayoutconstraints don't understand, refer documentation uiview property translatesautoresizingmaskintoconstraints) ( "<nslayoutconstraint:0x16fa21f0 uiview:0x180afaa0.height == 0.454545*cammodedial:0x16f06760.height - 4.09091>", "<nslayoutconstraint:0x18065020 camshutterbutton

java - Encoding UTF-8 in HTTPServlet request -

this may like problem that's been solved it's not, because have gone through questions deal utf-8 , none of solutions has helped me. i'm sending http request java servlet containing json object using json simple library. i added utf-8 encoding in tomcat xml file my html pages support utf-8 encoding both database , tables utf-8 encoded i changes default encoding of jvm utf-8 using system variables (yeah! that's how desperate got) this dispatcher function: protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { request.setcharacterencoding("utf-8"); ajaxparser cr = ajaxparser.clientrequestfactory(); clientrequest msg = cr.parseclientajax(request); handlerequest hr = new handlerequest(); handlerequeststatus hrs = hr.handlemessage(msg); ajaxresponsegenerator arg = new ajaxresponsegenerator(); jsonobject jsonobj = arg.handleresponse(hrs);

ibeacon - identifying the beacon in the method didEnterRegion(Region region) and didExitRegion(Region region) -

want this: public void didenterregion(region region) { if(region.getid1.equals("xxxxxxxxxxxxx")){ //display message: welcome area 1 } else if(region.getid1.equals("yyyyyyyyy")){ //display message: welcome area 2 } } the problem when calling get.id1 value returns null , not have differentiate beacons you need use ranging apis in order specific identifiers of visible beacons. can start ranging inside didenterregion callback, , callback in different method identifiers. this: public void didenterregion(region region) { beaconmanager.setrangenotifier(this); beaconmanager.startrangingbeaconsinregion(region); } public void didrangebeaconsinregion(collection<beacon> beacons, region region) { (beacon beacon: beacons) { if(beacon.getid1().tostring().equals("xxxxxxxxxxxxx")){ //display message: welcome area 1 } else if(region.getid1().tostring().equals(&

android - Get the position in a ListView of a Spinner and get its selected value -

i implemented arrayadapter listview : public class calcamrlistadapter extends arrayadapter<amrstatelistentry> implements onitemselectedlistener { public calcamrlistadapter(context context, list<amrstatelistentry> entries) { super(context, r.layout.activity_calc_amr_fragment_row, entries); } @override public view getview(int position, view convertview, viewgroup parent) { amrstatelistentry entry = this.getitem(position); viewholder viewholder = null; layoutinflater inflater = null; if(convertview == null) { viewholder = new viewholder(); inflater = layoutinflater.from(this.getcontext()); convertview = inflater.inflate(r.layout.activity_calc_amr_fragment_row, parent, false); viewholder.spinneractivity = (spinner) convertview.findviewbyid(r.id.calc_amr_row_spinner_activity); viewholder.spinnerhours = (spinner) convertview.findviewbyid(r.id.calc_amr_row_

java - Cordova Twilio plugin connection status -

i using following cordova plugin twilio https://github.com/jefflinwood/twilio_client_phonegap i not able connection status on status change. please if knows how listen status change or request status @ time me. any appreciated. thank you i've been experiencing same problem , changed bit native plugin implementation fix this. can find fork at: https://github.com/ebariaux/twilio_client_phonegap plugin has not been tested extensively, made change got me functionality wanted.