Posts

Showing posts from June, 2013

php - Array merge at second level -

i have 2 arrays shown below. need merge content of arrays can structure shown in third array @ last. have checked array_merge can't figure out way possible. appreciated. thanks. array( (int) 0 => array( 'gross_value' => '100', 'quantity' => '1' ), (int) 1 => array( 'gross_value' => '200', 'quantity' => '1' ) ) array( (int) 0 => array( 'item_title_id' => '1', 'order_id' => '4' ), (int) 1 => array( 'item_title_id' => '2', 'order_id' => '4' ) ) i should merged array this array( (int) 0 => array( 'gross_value' => '100', 'quantity' => '1', 'item_title_id' => '1', 'order_id' => 4 ), (int) 1 => array( 'gross_value' => '200', 'quantity&

Does python re (regex) have an alternative to \u unicode escape sequences? -

python treats \uxxxx unicode character escape inside string literal (e.g. u"\u2014" gets interpreted unicode character u+2014). discovered (python 2.7) standard regex module doesn't treat \uxxxx unicode character. example: codepoint = 2014 # got dynamically somewhere test = u"this string ends \u2014" pattern = r"\u%s$" % codepoint assert(pattern[-5:] == "2014$") # ends escape sequence u+2014 assert(re.search(pattern, test) != none) # failure -- no match (bad) assert(re.search(pattern, "u2014")!= none) # success -- matches (bad) obviously if able specify regex pattern string literal, can have same effect if regex engine understood \uxxxx escapes: test = u"this string ends \u2014" pattern = u"\u2014$" assert(pattern[:-1] == u"\u2014") # ends actual unicode char u+2014 assert(re.search(pattern, test) != none) but if need construct pattern dynamically? use unichr() function create un

javascript - Finding dom index based on selection -

html markup <div> <div class="selector"></div> </div> <div> <div class="selector"></div> </div> <div> <div class="selector1"></div> </div> <div> <div class="selector1 active"></div> </div> <div> <div class="selector2"></div> </div> <div> <div class="selector2"></div> </div> based on user click, want find clicked bucket , based on bucket want find index. javascript var sectiontype = $(this).attr('class'); var sectionindex = sectiontype.find("active").index(); but not giving me selected/hover element index. can please me? you can pass dom element index method, returns index of element in jquery collection. $('div[class]').click(function () { var cls = this.classname.split(' ')[0]; var

css - Chrome tr height skips pixels -

i'm having strange behaviour in chrome when using 'height' property or 'tr' elements. if set 25px rows 26px, 1 pixel larger , behaves same sizes 25-29 or 35-39. if set 20-24 or 30-34px display normally. table tr { height: 25px; } you can see here in fiddle: http://jsfiddle.net/uw53u/1/ . works in ff. note: i'm using windows 7 , chrome 26.0.1410.64 m on windows7 , chrome 26.0.1410.64 m working fine example, try deactivate chrome extensions.

class - Python: differences among __setitem__ ; setattr ; set -

simple explanations examples 3 of them cannot interchanged. def __setitem__(self,**k): #self.val=k key in k: self.val.setdefault(key,[]).extend(v v in k[key]) can above step done in iterations setattr(obj,val[,can optional stuff come here??]) why not create our own style , private methods? def _add(self,**k): if isinstance(self, cclass): key in k: self.val.setdefault(key,[]).extend(v v in k[key]) q: class's scope allows these private methods accessed , used? __setitem__ can used setting one item: def __setitem__(self, key, value): self.val.setdefault(key,[]).append(value) if prefer extend @ once 1 call, can build dict 's .update() method takes iterable and/or keyword arguments: def update(self, it, **k): key, val in it: self.val.setdefault(key,[]).extend(v v in val) key, val in k.iteritems(): self.val.setdefault(key,[]).extend(v v in val)

servicebus - Use oauth token provider through configuration -

is there way configure oauth access behaviour in wcf configuration? can not make work. easy in connection strings in console app, being nightmare in wcf configuration. <behavior name="securitybehaviorsts"> <transportclientendpointbehavior> <tokenprovider> <windowsauthentication> <stsuris> <stsuri value="https://url:9355/servicebusdefaultnamespace/$sts/oauth/" /> </stsuris> </windowsauthentication> </tokenprovider> </transportclientendpointbehavior> </behavior> thanks

Sql Server change fill factor value for all indexes by tsql -

i have expoet db bacpac file import azure. when try export error because indexes have fillfactor value. i've found how set fillfactor value indexes can't specify 0, value have between 1 100. if change value in management studio can set 0. the problem have got lots of indexes change , change fillfactor value of them trough tsql. any ideas?. thanks. this isn't straight t-sql way of doing it. though generate pure t-sql solution can apply db. your results may vary depending on db... example poor referential integrity might make bit trickier.. also comes @ own risk disclaimer :-) get db want migrate ssdt project http://msdn.microsoft.com/en-us/library/azure/jj156163.aspx http://blogs.msdn.com/b/ssdt/archive/2012/04/19/migrating-a-database-to-sql-azure-using-ssdt.aspx this nice way migrate schema azure regardless... it's way better creating bacpac file.. fixing... exporting...fixing.. etc... recommend doing anytime want migrate db azure fo

subquery - MySQL: sub query returns more than one row -

i need delete rows responses table after questions table has been updated error: sub query returns more 1 row. there way around working? create trigger delete_responses after update on questions each row begin if new.active != old.active delete responses option_id = ( select option_id options question_id = old.question_id); change = = any or in : create trigger delete_responses after update on questions each row begin if new.active != old.active delete responses option_id in ( select option_id options question_id = old.question_id);

image processing - MATLAB Computing distance from a point to a set of points -

consider matrix a: a = magic(5) 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 i have compute following formula: w_ij = ||i(i) - i(j)|| ^ 2 point a(1,1) neighborhood i.e. a(1:2, 1:2). don't understand formula stand since not specified. euclidean distance? i tried norm(a(1, 1) - a(1:2, 1:2)) but gives me scalar. i'm expecting vector of 4 elements. can me? you can see formula in context on page 4 of http://www.cs.berkeley.edu/~malik/papers/sm-ncut.pdf (equation 11). in paper use f intensity assume have i. since intensities scalars, want take square of differences. you want calculate weight matrix calculates affinity of entry in other entry in a. because has 25 entries, weight matrix 25x25. since worried brightness easy: len = length(a(:)); w = zeros(len); = 1:len j = 1:len w(i,j) = (a(i) - a(j))^2; end end now if want weight between a(1,1) , a(1

html5 - HTML Pattern - regex not working -

i'm trying pattern attribute first time, , can't work (my browser support it, though). right have: input type="text" pattern="[a-za-z0-9]{6}" name="formname" the first problem is doesn't notify me if it's blank; second problem if type in something, won't accept it. want accept alphanumeric characters , 6 characters length. tried forward slashes , few other variations. as duikboot pointed out, right way is: <input type="text" name="formfield" pattern="[a-za-z0-9]{6}" required> the required attribute causes validation fail, when field empty. pattern attribute defines regex test against, when field not empty. (your initial pattern seems work fine.) more info can found here . simple enough not require demo, nonetheless can find 1 here .

execution of javascript functions in parallel in phonegap -cordova, -

i use phonegap - cordova notification , phonegap statusbarnotification plugin. need run vibrate, beep , statusbarnotofication on 1 moment, how can this? navigator.notification.vibrate(1000); window.plugins.statusbarnotification.notify(data.title, data.message); navigator.notification.beep(1); when did this: window.plugins.statusbarnotification.notify("title", "data"); navigator.notification.vibrate(1000); navigator.notification.beep(1); it worked fine on htc sensation phone running android 2.3, , on nexus 7 running android 4.2. try other devices if need. 1 thing note devices don't have functionality...for example, nexus 7 doesn't have vibrate capability, code above show notification , make beep noise. also, make sure have volume turned , ring tone set.

tomcat7 - What is the difference between managed tomcat and embedded tomcat? -

i not sure understand difference between these 2 types of tomcats (embedded , managed). i going setup arquillian test project on tomcat , have choose between embedded tomcat or managed tomcat (since there different ppom.xml settings , dependencies). please tell me difference , 1 should choose running arquillian tests. i found answer "arquillian testing guide" book. embedded containers: arquillian start during test process , shutdown after test run, on same jvm test case. managed containers : arquillian start during test process , shutdown after test run run in different jvm remote containers : assumed running prior test , have deployments sent , tests executed

php - Use MySQL Trigger to Limit Inserts? -

we have internal php web app that's used scheduling. have multiple users trying schedule appointments same time slot, have hard limit on how many appointments can have per available time. we've used php verify there available slots before booking, there's still enough time between php checking table , insert overbooking can still happen. i believe solution mysql trigger checks table before insert. problem need mysql able count number of records have same "schedule_id" , "schedule_user_date" record inserted (this how many appointments exist time slot). i have somehow let trigger know maximum time slot is, i'm stuck, since can change client client. if have other suggestions other mysql trigger, i'd hear well.

ruby on rails - Make users verify that they have read something in the Devise new registration form -

i creating user account system rails app, , using devise , simple form handle user account creation. have static pages controller handle terms , conditions page. i have devise create user account if user checked box saying have read relevant terms , conditions, bit on every website have sign for. you can add checkbox form. , in controller, create user, make check if checkbox checked or not. as other, not recommended option, add field database(boolean), , validate presence of 1

python - class method as a model function for scipy.optimize.curve_fit -

there statement in manual of curve_fit the model function, f(x, ...). must take independent variable first argument , parameters fit separate remaining arguments. however, use model function method of class defined as: def model_fun(self,x,par): so, first argument not independent variable, can see. there way how can use method of class model function curve_fit sure, create instance , pass bound method: class myclass(object): ... def model_fun(self,x,par): ... obj = myclass(...) curve_fit(obj.model_fun, ...) you can find explanation bound/unbound/etc. in this question .

svn - create and use branch in anksvn -

i ask proper method of using current version of anksvn when working visual studio 2010. right have 'original' version of code checked 'trunk'. modify existing code , place modified code branch. to place code 'branch', can tell me of following should and/or tell me proper method: do 'create branch' first , check in copy original code branch? or do 'create branch' first , check in modified code branch? or check out original code location on workstation, modify code, , checkin modifed code @ same time 'create' branch. and/or can tell me proper procedures checking in modifed code anksvn? create 'branch' before checking code subversion or during process of checking in modified code anksvn? you can either create branch based on url or #3 in question, copy current state of working copy new branch. to create branch remotely (without considering state of working copy) using ankh: right click solution -> sub

how do i run command-line ant with stuff in the classpath? -

in eclipse, can tell external ant tool run stuff in classpath. if want run ant command line, how that? for argument's sake, classpath want add c:\some\folder\here\hooray.jar use -lib argument. ant docs on this page : additional directories searched may added using -lib option. -lib option specifies search path. jars or classes in directories of path added ant's classloader.

ajax - Return an array of values from toggled images in jquery -

i using jquery post return xml dataset. using drop down form controls filter data returned. now want able display list of manufacturer icons , have user click on toggle them on , off. $('#sho').click(function() { $(this).toggleclass('highlight'); if ($(this).hasclass('highlight')){ $(this).attr('alt','sho'); alert(manufac); } else { $(this).attr('alt',''); }}); currently have toggle code in place image gets box around when clicked. setting alt attribute value. want able gather alt attribute have values , pass them jquery post. function loadxml(so) { <!-- clothing version --> timestamp = math.round(new date().gettime() / 1000); $("#wrapper").html('<div id="load"><img src="http://static.phmotorcyclescom.dev/images/loading.gif" alt="loading" align="center" /></div>'); $("#results&

objective c - Check if any values have changed a certain amount -

does know efficient ways check if set of integers contains integer has changed amount. for example have: int1 = 10; int2 = 20; int3 = 30; and want know if of these 3 integers change 30 now if int1 becomes 40 call should triggered. @ first thought of doing this. if (abs((int1+int2+int3)-(newint1+newint2+newint3)) >= 30) { but many problems can arise this... false triggers (e.g. each new int value increases 10, making net change greater 30 not individual int greater 30) untriggered reactions (e.g. 1 of new integer values has increased 50 should called new integer value decreased 50 (again, should called) net change 0 because -50+50=0 ) does have efficient way of doing this? (yes, know check each value individually or statements...) so far best stab @ if ((((abs(int1-newint1))>=30)+((abs(int2-newint2))>=30)+((abs(int3-newint3))>=30))>0) { but that's basically same using or statement (probably takes little longer or statment. i do

ios - How can I center rows in UICollectionView? -

i have uicollectionview random cells. there method allows me center rows? this how looks default: [ x x x x x x ] [ x x x x x x ] [ x x ] here desired layout looks like: [ x x x x x ] [ x x x x x ] [ x x ] a bit of background first - uicollectionview combined uicollectionviewlayout determines how cells placed in view. means collection view flexible (you can create layout it), means modifying layouts can little confusing. creating entirely new layout class complex, instead want try , modify default layout ( uicollectionviewflowlayout ) center alignment. make simpler, want avoid subclassing flow layout itself. here's 1 approach (it may not best approach, it's first 1 can think of) - split cells 2 sections, follows: [ x x x x x ] <-- section 1 [ x x x x x ] <-- section 1 [ x x ] <-- section 2 this should straightforward, provided know width of scroll view , number of cells can fit in each row. then, us

fluent nhibernate - How do you automap database schema for a set of entities -

my database has multiple schemas, fluent nhibernate faq states can specify schema entire database, or per entity. want specify schema per autopersitencemodel, can done? got it: public class schemaconvention : iclassconvention { public void apply(iclassinstance instance) { instance.schema("schemaname"); } } autopersistencemodel model = automap.assemblyof<whatever>(); model.conventions.addfromassemblyof<schemaconvention>();

Elegant way for multiple asynchronous function calls in Javascript -

i need call same asynchronous function multiple times not till 1 call finished (i.e. when callback function executed). code looks this: syncfunc(a, function() { syncfunc(b, function() { syncfunc(c, function() { syncfunc(.....) }); }); }); is possible shorten somehow? first idea using loop, like: syncparams = [a, b, c, ...]; for(var = 0;; i++) { syncfunc(syncparams[i], function() { if(i < syncparams.length - 1) { alert('finished'); break; } else { continue; } } } but not work there's no connection continue , break loop. other idea using interval check every second if 1 async call finished , call next 1 next parameter, seems complicated. there easy way without using library? edit : because nobody unterstood library issue: developing phonegap mobile app , ide i'm working not pleasent include third party library. curious how work. i see want call

Fortran extension to Python via f2py: How to profile? -

i'm using extension python (2.7.2) written in fortran (gfortran 4.4.7) compiled via f2py (ver. 2). i can profile python part cprofile , result not give information fortran functions. instead time attributed python function calling fortran function. i have enabled "-pg -o" flags fortran objects build, in f2py call creating shared object via: f2py --opt="-pg -o" ... any hint on how fortran informations highly appreciated. if uses similar set-up, different profiler, i'd interested. a fortran function call appears as: <ipython-input-51-f4bf36c6a947>:84(<module>). i know, can't identify module being called @ least gives idea. another way wrapping python function , see timing python function.

asp.net mvc - Kendo Multiselect: Selected values from binded model are not initialized -

update: to shorten question: how bind selectlist kendo ui multiselect widget using razor? original question: in asp.net mvc 4 application, trying kendo multiselect working. binding multiselect widget model/viewmodel init values not being used. selecting , works perfectly. model: public class data { public ienumerable<int> selectedstudents{ get; set; } } public class student { public int id { get; set; } public string name { get; set; } } controller: list<student> students = new list<student>(); students.add(new baumaterial { id = 1, name = "francis" }); students.add(new baumaterial { id = 2, name = "jorge" }); students.add(new baumaterial { id = 3, name = "drew" }); students.add(new baumaterial { id = 4, name = "juan" }); viewbag.students= new selectlist(students, "id", "name"); data data = new data { selectedstudents = new list<int>{2, 4} }; return partialview(data);

java - String assignments and output -

given following code: string str1 = new string("hello"); string str2 = str1; string str3 = new string(str1); string str4 = str3; str4 += " world "; if (str3==str4) system.out.println(“one”); if (str3.equals(str4)) system.out.println(“two”); if (str1==str2) system.out.println(“three”); if (str3.equals(str2)) system.out.println(“four”); the output : 3 , four i don't it.. did str3 == str4 . how can not refer same object..? str3 == str4 seem false , dont why. in addition, str3.equals(str4) return false guess has first thing dont get. would love explanation. because string immutable, += operator creates new instance , assignes str4 . therefore str4 not equal str3 .

javascript - Is there any way in Highcharts to auto show Labels/Text on a scatter chart? -

Image
i scatter chart able automatically show next each plot point or bubble, piece of text identifying it. any appreciated !! you need name in data, , add datalabel in series, check this: series: [{ datalabels: { enabled: true, x:40, formatter:function() { return this.point.name; }, style:{color:"black"} }, data: [{ "x": 23, "y": 22, "z": 200, "name":"point1" }, { "x": 43, "y": 12, "z": 100, "name":"point2" }] }] example: http://jsfiddle.net/tqvf8/

Understanding the job of routes in Node.js (api) when utilizing Backbone.js (frontend) -

i beginning learn using backbone.js. have used web framework built on top of node.js handle routes , responses. backbone possibility of spa (single page application). i believe question related one: account backbone.js pushstate routes node.js express server? (a question of express.js + backbone). in code given: app.get('/', function(req, res) { // trigger routes 'domain.com' , 'domain.com/#/about' // here render base of application }); app.get('/about', function (req, res) { // trigger toure 'domain.com/about' // here use templates generate right view , render }); from using node web frameworks have not used json requests data, have queried database in route closure. job of node.js (in node+backbone environment) serve backbone page , not query database? directs clients specified backbone.js template without passing data, , backbone takes over? so if wanted display book models (example.com/books) instance, send use

bash - Running command via ssh also runs .bashrc? -

in reading of bash manpage, .bashrc should executed when shell run interactively. manpage defines interactive as: an interactive shell 1 started without non-option arguments , without -c option standard input , error both connected terminals (as determined isatty(3)), or 1 started -i option. ps1 set , $- includes if bash interactive, allowing shell script or startup file test state. yet, executing command ssh causes .bashrc run, contrary expect, given command not run interactively. so, behavior seems bug, seems pervasive on versions of red hat , bash i've tried. can explain why behavior correct? one additional point: though .bashrc run, $- , $ps set if shell non-interactive (as expect). $ grep user /etc/passwd user:x:uid:gid:uname:/home/user:/bin/bash $ cat ~/.bashrc echo bashrc:$-,$ps1 $ bash -c 'echo $-' hbc $ ssh localhost 'echo $-' </dev/null 2>/dev/null user@localhost's password: bashrc:hbc, hbc $ ssh localho

sql server - Stored Procedure Count(*) -

i have stored procedure: create procedure [dbo].[getcorrespondingrespcode] @rc char(3) begin set nocount on; declare @webrccount int select webrc, count(*) webrccount payterm.response_codes_mapping rc = @rc group webrc end how can set @webrccount value of webrccount ? need if @webrccount = 1 print'ok' select @webrccount = count(*) payterm.response_codes_mapping rc = @rc select @webrccount [webrccount] that should it...

java - how to create web service from existing web dynamic application -

my problem follows: have web dynamic project (java ee) 2 classes , servlet. the servlet contains method sendimage 2 parameters ( string , httpservletresponse ), , method returns result want use in response, servletoutputstream . i'm trying use project create stand alone web service (with jax-ws ), can call other web application. does have idea how should it? you should checkout jax-ws documentation, or search internet jax-ws tutorial?

sql server - Remove Duplicates ... With NULLs -

in ms sql server trying remove duplicates table nulls. que groans. lots , lots of null s. bottom line need retain 1 copy of duplicate record or without null s. want null act normal record value of " null " duration of operation, , go being real null . possible? there simpler solution? table1 looks like: uid data1 data2 1 null 2 null 3 b abc 4 b abc 5 c null 6 d ghj i want command throw away line 2 , 4 , keep rest. (the select testing.) ;select uid, data1, data2 table1 t not exists ( select 1 table1 t2 t2.data1 = t.data1 , t2.data2 = t.data2 , t2.uid >= t.uid ) , data1 not null note: select distinct not work duplicates have different timestamps. this should do: ;with cte ( select *, rn = row_number() over(partition data1,data2 order uid) t

xml - PHP - How to read RSS feeds with limit ( Pagination ) -

i know there lot of ways read rss in php like $rss = simplexml_load_file('http://rss.cnn.com/rss/edition.rss'); var_dump($rss); and when searching paginate feeds , limit them offset pagination example found more 1 way displaying rss feed php pagination http://www.phpexpertsforum.com/display-rss-feeds-with-pagination-using-php-t2173.html http://bavotasan.com/2010/display-rss-feed-with-php/ all of them paginate feeds after getting of them form rss provider my question "is there way read rss feeds in paging way twitter or facebook apis?" thank there's no generic way work providers - give in response requests them. can/will paginate, others won't - you've discovered; won't - they'll give rss feed is. if you're trying create generic module, need able handle paginated feeds if gets one. either need keep white-list of providers give paginated feeds or learn recognise paginated feeds when receives them - , handle them

java - Checking if window has keyboard focus again -

preface i'm designing application @ 1 stage have it's keyboard focus taken away , redirected application. application in question google-chrome. @ stage program should pause, or halt it's operations entirely until keyboard focus has been returned. some information: my application being written in java the application granted keyboard focus google-chrome what need a way test if jframe has keyboard focus maybe like: jframe.hasscreenfocus() or effect. you should able use windowlistener , listen windowactivated() event. need listen windowdeactivated() stop current processing.

dart - how do I simply run latest examples of project like web ui or widgets -

if have specifies web ui in pubspec ends in place $home/.pub-cache/hosted/pub.dartlang.org/web_ui-0.4.7+3. noticed todomvc appears in example folder. hoping run examples, loaded existing folder web_ui-0.4.7+3 darteditor. tried pub install/update , build. did not work due '+' in folder name. so, next git cloned web-ui project , tried pub update similarly. issue "web_ui requires sdk version >=0.5.7+1 current sdk 0.5.5+0.r22416", can understand - out on github more bleeding edge. update whenever icon on darteditor indicates time to, here seems if latest of package can depend on later sdk have editor. have had same issue when clone package such 'widgets'. author said issue going directly github instead of using pub , if used pub ok. i'm not clear on means, because me using pub means have project in pull in , use specific library , maybe resources. run latest of /examples/ in project web ui or widgets need create own project , reference them run them?

jquery datatables modal form -

i have button on form has onclick event handler open modal dialog form: <button id="btnaddnewrow">add</button> $("#btnaddnewrow").click(function(){ $( "#mydialog-form" ).dialog( "open" ); } ); this adds row current grid , works well. however, thought grid better if had add in grid header div moved this: "sdom": '<"h"l<"btnaddnewrow">r>t<"f"<"clear">>', "idisplaylength": 25, "fninitcomplete": function () { $("div.btnaddnewrow").html("<div id='btnaddnewrow' class='tblaction'><a href='#'>add</a></div>"); } the form opens okay no errors in console. when click on "add" in header modal form doesn't open fire ajax that's attached commit button on modal form. errors because nothing has been entered. i don't understand why behaviour

c++ - Parallel OpenMP reduction vs. function definition? -

i'm using openmp problem i'm declaring/defining function follow: void compute_image(double pixel[nb], double &sum) { #pragma omp parallel reduction(+:sum) (int j=0;j<640;j++) { if ... sum=sum+pixel[0]; .... } .... } what realise : error 2 error c3030: 'sum' : variable in 'reduction' clause/directive cannot have reference type c:\users...\test.cpp 930 actually, cannot rid of openmp. solution? instead of reduction, put sum=sum+pixel[0] under #pragma omp atomic or #pragma omp critical line. another option have double local_sum = sum; before omp section, reduce on local_sum, , have sum = local_sum; after loop.

javascript - d3 example of Stacked Bar Chart into jsfiddle -

i referencing d3 example of stacked bar chart , try implement in jsfiddle 1 i want add example jsfiddle , have added 5 external source alone source csv file got no output. here jsfiddle 2 can on need add there. the problem have embed csv data in different way, since can neither included fiddle js/css, nor requested within javascript, because of browser restrictions . you can example include in html part of fiddle: <pre id="csvdata"> date,wounds,other,disease 5/1854,0,95,105 [...] </pre> i updated your fiddle , working now.

How to access boolean array Java -

i have following constructor defines board , checks if of 3 jbutton s have been clicked: timer timer = new timer(500, this); private boolean[][] board; private boolean isactive = true; private int height; private int width; private int multiplier = 40; jbutton button1; jbutton button2; jbutton button3; public board(boolean[][] board) { this.board = board; height = board.length; width = board[0].length; setbackground(color.black); button1 = new jbutton("stop"); add(button1); button1.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { isactive = !isactive; button1.settext(isactive ? "stop" : "start"); } }); button2 = new jbutton("random"); add(button2); button2.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { this.board = randomboard(); } }); button3 =

sql server - How to merge a select statement with a calculated value as new columns? -

this question has answer here: how merge select statement new dynamic values columns? 4 answers in sql server code, have select statement select distinct a.hirelastname, a.hirefirstname, a.hireid, a.position_id, a.barnumber, a.archived, a.datearchived, b.position_name newhire join position b on a.position_id = b.position_id join workperiod c on a.hireid = c.hireid a.archived = 0 , c.inquiryid not null order a.hireid desc, a.hirelastname, a.hirefirstname and want add new column it. column not column table, used store float calculation make existing columns. the number calculated this: @acc a.hireid above select statement. cast((select count(*) hire_response hireid = @acc , (hireresponse = 0 or hireresponse = 1)) float) / cast((select count(*) hire_response hireid = @acc) float) how can this? thanks. you

html - JavaScript: reduce Google Analytics / Yandex.Metrica to referrer and screen size -

i don't feel comfortable embedding external javascript on site kinds of tracking don't need. what need referrer , screen size, cannot accomplished static html img tag alone. what's standard-compliant, browser-supported , rendering-friendly way load invisible image, 1×1 gif, referrer , screen size part of url? i'm looking generic answer, although phrase in terms of google analytics gif request parameters . document.referrer referrer. window.screen.width , window.screen.height screen resolution. you can use these new image() have browser request tracking pixel. use encodeuricomponent sanitize values before appending them url. var r = encodeuricomponent(document.referrer), x = window.screen.width, y = window.screen.height, img = new image(); img.src = '/tracking.gif?x=' + x + '&y=' + y + '&r=' + r; note on subsequent requests, cached, won't count of pageviews (although didn't wanted this).

excel - Comparing and matching a range of data with another range of data -

each row of 4 columns represents set of data a1 : d1 1,2,3,4 a2 : d2 4,2,1,5 a3 : d3 5,3,2,1 etc. now column set compared column set f1 : i1 4,6,3,1 f2 : i2 4,3,2,1 f3 : i3 2,3,5,1 the set matches other column set marked red. in example f2:i2 , f3:i3 marked red. need contain same numbers. order not important numbers should match. i thought of using conditional statements can't seem find way compare , match sets of range other sets of range. as alternative, thought of adding columns =a1&" "&a2&" "&a3&" " &a4 sort match there tried sorting left right sets , doesn't seem sorting right if @ once. sheet contain large amount of rows chore 1 1. so i'm out of ideas not excel. :( appreciate can get. :) also, don't mind learning other languages if makes things easier. (as long can import data excel) if want create single column match on should it: =concatenate(large(a1:d1,1),":

html5 - in indexed database, how to get a keysList in which key start with "some string"? -

function fetchemployeebyemail() { try { var result = document.getelementbyid("result"); result.innerhtml = ""; if (localdatabase != null && localdatabase.db != null) { var range = idbkeyrange.lowerbound("john"); var store = localdatabase.db.transaction("employees").objectstore("employees"); var index = store.index("emailindex"); index.get(range).onsuccess = function(evt) { var employee = evt.target.result; var jsonstr = json.stringify(employee); result.innerhtml = jsonstr; }; } } catch(e){ console.log(e); } } in above sample, how emails have first name "john"???? a nosql approach databases means should think alternate storage access patterns. if want support query first name, , want in performant manner, consider storing derived first name property per employee, create index on derived

playframework 2.0 - Serving dynamic content in Play 2.x -

on level, i'm doing similar post: how serve dynamic content in playframework 2 which have web app clients can specify various parameters , have play! server initiate process generates custom image file...which needs served client, preferably play! anticipated image life expectancy anywhere several seconds several minutes (maybe hours). angle, have reasons believe attempting send image data directly response not viable approach...and instead going send url dynamic image. i prefer not rely on separate http server being set serve these dynamic images variety of reasons. believe reasons many, including not limited to... maintaining simpler architecture both developer work environments production servers. have small/restricted user base few concurrent users (i don't believe serving these images needs terribly high performance anyway - assuming play! can serve these dynamic images, find hard imagine performance wouldn't acceptable considering simplicity tradeoff). i&

java - What is in android.util.Log#println_native()? -

here android.util.log source code. at bottom (line 340), in method: public static native int println_native(int bufid, int priority, string tag, string msg); i guess println_native() more or less println() , int bufid different. but got codes of println_native() , still lack com.android.internal.os.runtimeinit (line 19, import ) simulate android.util.log in old android version. just did digging in android source code. function maps to static jint android_util_log_println_native(jnienv* env, jobject clazz, jint bufid, jint priority, jstring tagobj, jstring msgobj) { const char* tag = null; const char* msg = null; if (msgobj == null) { jnithrownullpointerexception(env, "println needs message"); return -1; } if (bufid < 0 || bufid >= log_id_max) { jnithrownullpointerexception(env, "bad bufid"); return -1; } if (tagobj != null) tag = env->getstringutfchars(tagobj, null); msg = env->getstringut

php - What is getScenarioPath and getScenarionResourceFolder? -

i looking @ someones project , keep getting line: $resource_folder = getscenarioresourcefolder(getscenariopath($scenario)); i cannot find function implemented under 2 names - getscenarioresourcefolder , getscenariopath . started wandering maybe name scenario has $scenario variable being in functions. know might sound dumb, not know else think. does know these function? i know these: you can search function: http://id1.php.net/manual-lookup.php?pattern=getscenariopath if no result, must user-defined function. you can check using if (function_exists('getscenariopath')) { ... } else { ... }

haskell - Every monad is monoid? -

since every monad monoid on sequencing operation. why doesn't monad inherit monoid in haskell? it doesn't have monad even, works every applicative . yes, define: class (functor f, monoid (f ())) => applicative f but means have provide monoid instance every time write applicative instance. can quite annoying, since monoid instance not used often. a better solution create newtype wrapper around f () , , can provide monoid instance applicative functors once , all. there's 1 readily available in the reducers package .

git : give me the repo, nuke everything local, I don't care -

does git have pull/checkout 'nuclear option' repo? don't care conflicts, don't need of local stuff, want goods can work. [edit] clarify issues: $ git pull error: local changes following files overwritten merge: <...files couldn't care less about...> please, commit changes or stash them before can merge. error: following untracked working tree files overwritten merge: <...more files couldn't care less about...> better understand various git commands find 1 need "right now" come situation many times , learn piecemeal while grumbling , blaming git. edit: went ahead , tried options , should it. pauljz in comments. git clean -df # remove untracked files , directories git reset head --hard # revert uncommitted changes the above should need. other options: git pull -f # replace local files if have unpushed commits. or git reset head --hard # remove unchanged, uncommitted files git pull or git clean -f # remov

ide - Gedit plugin installation -

Image
i'm trying install gedit plugin: https://github.com/elijahr/gedit-rename plugin, able rename files in ide. well, can't install despite following installation instructions. in fact, i've never managed install gedit plugin in entire life. , tried many times. if has time , me make work nice. or point me ide allows renaming files , has vertical split view. open terminal: sudo apt-get update sudo apt-get install gedit-plugins there plugin in gedit let rename files. go edit -> preferences -> plugin -> file browser panel : , select , close. now see file browser on left side , rename files there for different ide: there many depending on language working with: general : sublime text editor, emacs, vim, geany python : pycharm, anaconda, enthought canopy c#,c++ : visual studio(for windows), qt, codeblocks java : eclipse, netbeans, qt

web config - 301 Redirect Rule is not working when I use full URL -

i have rule in web.config on asp.net 4.5 , iis 7.5 <rule name="baad4041-5e25-499f-abb7-6bd4f76b2ed3" stopprocessing="true"> <match url="http://www.domain.com/thisisold.html" /> <action type="redirect" url="http://www.domain.com/newurl.aspx" /> </rule> it not seem work, when hit url, sends me 404. rule works: <rule name="baad4041-5e25-499f-abb7-6bd4f76b2ed3" stopprocessing="true"> <match url="thisisold.html" /> <action type="redirect" url="http://www.domain.com/newurl.aspx" /> </rule> i need have full url match site has multiple domains, how can make happen? you can try; <rule name="test" patternsyntax="exactmatch"> <match url="http://www.domain.com/thisisold.html" /> <action type="rewrite" url="http://www.domain.com/newu

ubuntu 12.04 - Where does Lynx store its cookies? -

i wondering lynx text based web browser stores cookies. having @ manual there options on how enable cookies, etc. couldn't find way have lynx delete stored cookies. therefore might have delete them manually not sure located! from man page : -cookie_file=filename specifies file use read cookies. if none specified, default value ~/.lynx_cookies systems, ~/cookies ms-dos.

javascript - Can't alter element's html after selecting it with querySelector -

i trying change html in div using queryselector, it's not working. html: <div class="test"> <p>par1</p> <p>par2</p> <p>par3</p> </div> js: var d = document.queryselector('.test'); var d.innerhtml = '<p>works</p>'; fiddle just remove var keyword before d.innerhtml , property, not variable. code: var d = document.queryselector('.test'); d.innerhtml = '<p>works</p>';

sql - Join tables in sqlite with many to many -

i have following database schema: create table people ( id integer primary key autoincrement, ); create table groups ( id integer primary key autoincrement, ); and have people members of groups in separate file (let's in tuples of ( person id , group id ). how can structure database schema such it's easy access person's groups, , easy access members of group? difficult , slow read tuples have, want in database form. can't have things member1 , member2 , etc. columns because number of people in group unlimited. move text file database table create table groups_people ( groups_id integer, people_id integer, primary key(group_id, people_id) ); and select people member of group 7 select * people p left join groups_people gp on gp.people_id = p.id gp.groups_id = '7'; and select groups person 5 in select * groups g left join groups_people gp on gp.groups_id = g.id gp.people_id = '5';

Choosing PHP version for a Heroku app -

i deployed app heroku , correctly detected php app. works great, there's small issue. heroku chose use php version 5.3, , i'd use version 5.4. is possible? if so, how? there several unofficial buildpacks use more modern php versions, here's example uses php 5.4 , has several other improvements: https://github.com/iphoting/heroku-buildpack-php-tyler to use: heroku config:add buildpack_url=git://github.com/iphoting/heroku-buildpack-php-tyler.git ... , push new build.

python - TypeError deleting items in a nested dictionary -

i have nested dictionary following: g = { 'a': { 1.55: { 'cd': [1.55, 12], 'lm': [1.55, 12], }, 1.45: { 'af': [1.45, 15], }, 1.6: { 'nr': [1.6, 26], } } } i want search through every element, , remove if has 12 in list. i've written following code, typeerror . wondering if help. for e, p in g.iteritems(): p,o in g[e].iteritems(): if g[e][p][o][1]==12: del g[e][p][o] because o dictionary, can't use index, why receiving typeerror . the following code want, urge think of better way can organize data. for k1 in g.keys(): k2 in g[k1].keys(): k3 in g[k1][k2].keys(): if 12 in g[k1][k2][k3]: del g[k1][k2][k3] note need use .keys() instead of .iterkeys() avoid runtimeerror: dictionary changed size during iteration . similarly, in @eric's solution .it

c# - Setting DefaultValue to first and last date of current month -

how can set defaultvalue 's in following code start date (first controlparameter) , last date (second controlparameter) of current month? <selectparameters> <asp:controlparameter controlid="txtfromdate" name="expensedate" propertyname="text" type="string" defaultvalue="01-05-2013" convertemptystringtonull="true" /> <asp:controlparameter controlid="txttodate" name="expensedate2" propertyname="text" type="string" defaultvalue="30-05-2013" convertemptystringtonull="true" /> </selectparameters> datetime today = datetime.today; int daysinmonth = datetime.daysinmonth(today.year, today.month); datetime startofmonth = new datetime(today.year, today.month, 1); datetime endofmonth = new datetime(today.year, today.month, daysinmonth); then can set these values controls.

jquery - Mousemove event working on document but not 'body' -

i trying make div turned-off light , when mouse moves, light turns on. i done part mouse movement turns light on. @ this fiddle . jquery code: $(document).mousemove(function() { $('div').addclass('glow'); }); i have 2 questions it if put 'body' instead of document, doesn't work, why? how can detect mouse stop? 1) 'body' works must move mouse on body, doesn't go until bottom of window (yes, body strange , incoherent thing). 2) detect mouse stop, simplest solution use settimeout , define delay : (function (){ var =0; var timer; $('body').mousemove(function() { cleartimeout(timer); // 'body' doesn't work instead of document += 1; $('p').text(function() { return 'moved: ' + i; }); $('div').addclass('glow'); timer = settimeout(function(){$('div').removeclass('glow')}, 2

Hide a single element in a layer - Kineticjs -

this code uses kineticjs. using mouseover , mouseout events 1 of images. layer has 2 images. want hide 1 of them. need create separate layer each image? img.onload = function(){ var image = new kinetic.image({ image: img, name:'iconimage', width: 50, height: 50, //draggable: true, //visible:true, listening:true }); var image2 = new kinetic.image({ x:100, y:100, image: img, name:'iconimage', width: 50, height: 50, //draggable: true, //visible:true, listening:true }); iconlayer.add(image).add(im

xslt 2.0 - XSLT2.0 Uppercase first Letter of Regex Match -

i have a use case convert camelcase elements in xml document newcase shown: current: <firstname>john</firstname> <lastname>smith</lastname> <userid>5692</userid> desired: <firstname>john</firstname> <lastname>smith</lastname> <userid>5692</userid> i must facilitate through xslt. in order this, identified regex capture camelcase requirement: \b([a-z])([a-z]*[a-z][a-z]*)\b from there, have been attempting via xslt2.0 using replace function: replace($xmltoparse,"\b([a-z])([a-z]*[a-z][a-z]*)\b","replaced") for final block, want take first segment of matched regex (in lowercase segments 'l' , 'owercase' based on above regex), , use upper-case function change first segment/letter upper case (so lowercase lowercase), , every regex match in xml. unfortunately far have been unable achieve it. would able give insight on how link together? this transformati

Storing 'shared' items MongoDB in application with RESTful API -

i creating application in users can share articles. currently, when user shares article , adds article id of shared item array called shares on user . var userschema = { // `shareditems` list of article ids user has shared shareditems: { type: array } }; however, because need way query shared items multiple user ids (similar news feed sort of query), decided go down route of creating separate collection shared items. var shareschema = { // id of user shared article userid: { type: string }, // id of article shared articleid: { type: string }, datecreated: { type: date } }; to tie in application code, when user updated, there check whether or not shareditems array on user updated – if is, task delegated shares collection add or remove matches respectively. have done because, when user shares item, client-side application has worry making post request user resource, rather making post user and share resources. trouble here relying on replication,

objective c - Error: No visible @interface for 'XYZPerson' declares the selector 'saySomething' -

this question has answer here: objective-c error "no visible @interface 'xyzperson' declares selector 'saysomething' 3 answers searched through several threads cannot find answer. i new objective-c , going through briefer @ apple development , experimented , keep getting error: no visible @interface 'xyzperson' declares selector 'saysomething' the console program has added class called xyzperson. here .h , .m files: this xyzperson.h file: #import <foundation/foundation.h> @interface xyzperson : nsobject @property (readonly) nsstring *firstname; @property (readonly) nsstring *lastname; @property (readonly) nsdate *dateofbirth; - (void)sayhello; - (void)saybooboo; - (void)saysomething; + (id)person; @end this xyzperson.m file: #import "xyzperson.h" @implementation xyzperson - (void)sayhello {

Data modelling for 'followers count' in MongoDB app with RESTful API -

i have user entity has array of other user ids he/she following. var userschema = { following: { type: array } }; i have restful api, , when request user , application needs know how many followers user has. the 2 options see are: when user requested, count query such as: { following: { $in: [userid] } } when user post ed, check see whether user ids added or removed following array, , if were, use mongodb's $inc increment or decrement followerscount property on user document have been followed/unfollowed. are other options? if not, best option? feel weird putting followerscount property in document itself, because suggests can updated application, when in fact dynamic count. i have similar situation need restful api return number of article s associated website . count articles website on request, or store count property , update every time new article associated website created? don't scared of storing more data think need in document. wh

Total Friend Count in Twitter API 1.1 version -

is there twitter api version 1.1 call provide total number of friends user following? the get friends/ids closest found, however, provides list of user friend ids, not total amount. https://api.twitter.com/1.1/friends/ids.json?cursor=-1&screen_name=twitterapi&count=5000 yes. if use users/show endpoint of v1.1 api can retrieve information particular user. one of fields returned called friends_count - value looking for. full details here: https://dev.twitter.com/docs/api/1.1/get/users/show

mysql - How to create a subquery -

how can combine 2 mysql statement 1 statement. these statements mysql 1 select et.imei imei, max(from_unixtime(et.timestamp)) tid exp_terminal_log et group et.imei order tid desc; mysql 1 output imei latest date 351895053434419 2013-04-28 11:12:28 354851057203265 2013-04-28 11:10:44 354851057234989 2013-04-28 11:10:32 mysql 2 select ct.title title, t.phoneid imei transactions t inner join exp_channel_titles ct on (ct.entry_id = t.restaurant_id) t.cardid != '88888888' , t.cardid > 0 , ct.status= 'open' group ct.entry_id mysql 2 output title imei café katz 351895053434419 restaurant1 354851057203265 restaurant2 354851057234989 desired output title imei latest date café katz 351895053434419 2013-04-28 11:12:28 restaurant1 354851057203265 2013-04-28 11:10:44 restaurant2 354851057234989 2013-04-28 11:10:32 this how tried, not work, because of subquery returning more 1 row. select et.i

javascript - Modify an UpdatePanel by calling server-side code from client code -

it's possible there's no way this, figure ask. i'm relatively new asp.net, having played week now. have right page calls web service, polls until it's done (with progress displayed in updatepanel), hides progress text , instead displays result (a recursive list of files metadata) creating treeview , adding updatepanel. clicking node in treeview update second updatepanel extended information (obtained server-side) node clicked on. don't see way call codebehind function clicking treenode, can call javascript code setting node's navigateurl "javascript:function([the full path of node])". at point, though, i'm kind of stumped. stackoverflow full of correctly-answered questions how call codebehind javascript (using webmethod, or equivalent), apparently can't call code isn't static, mean couldn't modify page itself, or matter, access session or page state. stackoverflow full of questions how have javascript request updatepanel refresh

Freebase MQL query issues -

below query code.. trying put several types 1 query build set of data off of...but query not work php, work inside of query editor on freebase.com <?php function getquery($type,$id=null){ //leaves off closing can return , append end of following... $query = "[{ \"type\":\"$type\", \"limit\":10, \"id\":null, \"name\":null,"; return $query; } function getsportsteamsstructure(){ $query = "\"/sports/sports_team/sport\":null,"; $query .="\"/sports/sports_team/league\":[{\"team\":null,\"league\":null,\"from\":null,\"to\":null}],"; $query .="\"/sports/sports_team/location\":[{".getlocationstructure()."}],"; $query .="\"/sports/sports_team/founded\":null,"; $query .="\"/sports/sports_team/arena_stadium\":[{"