Posts

Showing posts from September, 2015

Oracle SQL. How to select specific IDs where value of columns specify criteria? -

i have following statement/query: select table1.file_id, table1.status, table2.status table1 inner join table2 on table1.file_id = table2.file_id; the result follows: file id | status table 1 | status table 2 ----------------------------------------------------- 5500002 | ax | ics 5500002 | ax | icso 5500002 | axo | ics 5500003 | ax | ics 5500003 | ax | ics 5500003 | ax | ics 5500004 | null | icso test 5500004 | axo | ics 5500004 | ax | null i need each file id check 4 statuses: - ax - axo - ics - icso i want run select on file id s cover 4 statuses. can see file id occurs multiple times , i'd want query return file id fulfills requirement, in instance return 5500002 , 5500004. for 550000...

python - Robot Framework location and name of keyword -

i want create python library 0 argument function custom robot framework keywords can call. needs know absolute path of file keyword defined, , name of keyword. know how similar test cases using robot.libraries.builtin library , ${suite_source} , ${test name} variables, can't find similar custom keywords. don't care how complicated answer is, maybe have dig guts of robot framework's internal classes , access data somehow. there way this? thanks janne able find solution. from robot.running.context import execution_contexts def resource_locator(): name = execution_contexts.current.keywords[-1].name libname = execution_contexts.current.get_handler(name).libname resources = execution_contexts.current.namespace._kw_store.resources path = "" key in resources._keys: if resources[key].name == libname: path = key break return {'name': name, 'path': path} execution_context...

methods - python can't use function in submodule -

my folder structure this: pythonstuff/ program.py modulea/ __init__.py foo.py bar.py here's code bar.py : def hello(): print("hello, world!") here's code program.py : #!/usr/bin/env python3 modulea import bar bar.hello() i run $ python3 program.py somehow error: file "program.py", line 3, in <module> bar.hello() attributeerror: 'module' object has no attribute 'hello' edit: __init__.py file empty. edit2: after trying realized had bar.py in root directory contained hello() method. bar.py in modulea/ directory empty. add it import os __all__ = [] module in os.listdir(os.path.dirname(__file__)): if module != '__init__.py' , module[-3:] == '.py': __all__.append(module[:-3]) the init .py files required make python treat directories containing packages; done prevent directories common name, such string, unintentionally hiding v...

Desktop Launcher for Python Script Starts Program in Wrong Path (Linux) -

i can not launch python script .desktop launcher created on linux mint 17.1 cinnamon. the problem script launched in wrong path - namely home folder instead of directory placed in. thereby can not find other vital files accompanying in folder , hence not work. to examine misbehaviour created short script check folder python script executing in: #!/usr/bin/env python import subprocess import time subprocess.call(["pwd"], shell=true) time.sleep(7) # chance read output executing own folder gives output: /home/myusername/pythonprojects i setting desktop launcher via nemo's menu. executing same script yields: /home/myusername i not understand behaviour. how create working desktop launcher python script? the page https://linuxcritic.wordpress.com/2010/04/07/anatomy-of-a-desktop-file/ describes format of .desktop files. you may note "path" element, specifies working directory file run in. in case want desktop file specified path=/...

netbeans - How to keep java.awt.List from covering javax.swing.JMenu -

to put simply, have menus in menu bar that, when @ start of application, goes on list when expand it. however, if list ever updated, menus go behind list, covering menu items. i have theorized need when list updated, make tell list go layer (which set bottom, lowest on list in application using netbeans). but, not know call tell program keep list there. (i still new java , learning go) have idea on how wish or better, causing problem? thank time , have wonderful day :3 you should use jlist instead of list. the problem components in java.awt have peer components, native os components, whereas swing 100% java. cannot write on these native peers... @ least not in java.

Extracting specific parts of a HTML-File with PHP Simple HTML DOM Parser -

i've got html-file several tables try extract link , image part. i'm using php simple html dom parser. here's html-file parse: <h1>title</h1> <p>text</p> <table cellspacing="0" cellpadding="0" border="0"> <tbody> <tr><td> <a href="http://www.google.com/some_url"> <img width="100" height="100" border="0" src="http://google.com/some_image.jpg"/> </a> </td></tr> </tbody> </table> <h2>title</h2> <p>text</p> <table cellspacing="0" cellpadding="0" border="0"> <tbody> <tr><td> <a href="http://www.google.com/this_url"> <img width="100" height="100" border="0" src="http://g...

angularjs - Redirect to a new template in angular js -

i new angularjs, please consider mistakes. the scenario is, have index.html page , login.html page, index , login have different layout different header footer , all. other pages expect login share same layout index.html now, how can navigate login.html using anuglar ui router. myapp.config(function ($stateprovider, $urlrouterprovider) { $stateprovider.state('home', { url: '/', templateurl: 'app/views/site/home.html', controller: 'homectrl' }).state('login', { url: '/login', templateurl: 'app/views/site/login.html' }) }); this not work loads content of login index keeping header , footer same of index. know state supposed work way. now, there way can call new view using ui.router. i appreciate help. thanks you set multiple named views ( https://github.com/angular-ui/ui-router/wiki/multiple-named-views ). this allow make header , footer separate views can ...

excel - Multiple IF, AND, OR statements -

i trying create excel formula represent logic: if (b8 < 0 & a8 > 0), b8+a8 or if (b8 < 0 & a8 < 0), b8-a8 or if (b8 > 0 & a8 > 0), b8-a8 i can't seem syntax right. alternatively, following put more closely/literally: =if(and(b8<0,a8>0),b8+a8, if(and(b8<0,a8<0), b8-a8, if(and(b8>0,a8>0), b8-a8, "null?" ))) should trick. wasn't sure put if none of cases fail, showing "null?" .. change desired. (but suspect pascx64's more efficient in long run ;) )

c++ - How to pass a 2d array through pointer in c -

possible duplicate: passing pointer representing 2d array function in c++ i trying pass 2-dimensional array function through pointer , want modify values. #include <stdio.h> void func(int **ptr); int main() { int array[2][2] = { {2, 5}, {3, 6} }; func(array); printf("%d", array[0][0]); getch(); } void func(int **ptr) { int i, j; (i = 0; < 2; i++) { (j = 0; j < 2; j++) { ptr[i][j] = 8; } } } but program crashes this. did wrong? it crashes because array isn't pointer pointer, try reading array values if they're pointers, array contains data without pointer. array adjacent in memory, accept single pointer , cast when calling function: func((int*)array); ... void func(int *ptr) { int i, j; (i = 0; < 2; i++) { (j = 0; j < 2; j++) { ptr[i+j*2]=8; } } }

c# - DataValidation using Regex not working -

so have maskedtextinput box follows: <telerik:radmaskedtextinput margin="2" borderbrush="lightgray" isclearbuttonvisible="false" mask="(###) ###-####" updatevalueevent="propertychanged" textmode="plaintext" value="{binding path=phonenumber, mode=twoway, notifyonvalidationerror=true, validatesonexceptions=true, updatesourcetrigger=propertychanged}" /> and bound through viewmodel following code-behind: //phone number [required(allowemptystrings = false, errormessage = @"a phone number required.")] [regularexpression(@"^\d{10}$", errormessage = @"invalid phone number...

python - More Pythonic way to turn any number of different lists or tuples into one list -

this question has answer here: making flat list out of list of lists in python 23 answers i trying write function take in number of different lists or tuples arguments , return 1 big list. def addify(*args): big_list = list() iterable in args: if isinstance(iterable, tuple): big_list.extend(list(iterable)) else: big_list.extend(iterable) return big_list >>> print addify((1,2,3), [2, 5, 3], (3,1,3), [3, 2344, 3]) [1, 2, 3, 2, 5, 3, 3, 1, 3, 3, 2344, 3] i learning args , kwargs , , code working right, seems code simple. there must better way writing long function check if argument tuple , if add convert list , add on. seems bloated. itertools.chain looking for: >>> itertools import chain >>> print list(chain((1,2,3), [2, 5, 3], (3,1,3), [3, 2344, 3])) [1, 2, 3, 2, 5, 3, 3,...

php - Escaping apostrophies and other characters in text area -

so have found form have falls apart , doesn't submit content until first apostrophe when types in apostrophe text area. how go escaping contents make mysql table? thanks! <form action=\"./functions/notes.php\" method='post'> <input type='hidden' id='id' name='id' value='{$row['id']}' /> <textarea placeholder=\"add more notes here...\" name=\"notes\"></textarea><br /> <input type='submit' name='formnotes' id='formnotes' value='add notes' /> </form> then in notes.php file $notesid = $_post['id']; $note = $_post['notes']; $date= date('y-m-d'); $result = mysql_query("update project_submissions set notes=concat(notes,'<br />".$date." ".$note."') id ='".$notesid."'"); apostrophes have special meaning sql, them data need "escaped...

javascript - Rendering HTML to Canvas on Retina displays -

this mdn article (citing this blog post ) teaches how render html content canvas. i've implemented in project , works. but on "retina" displays, draws canvas @ half of full resolution display supports. example, if have canvas on render html string "hello" , next canvas put <span>hello</span> , latter (rendered browser usual way) smoother , crisper former (rendered html onto canvas, using technique in links above, uses svg , image ). i believe there's way detect retina displays, know when higher resolution needed, given in this source code . when detect i'm on retina display, question is: is there method renders html canvas @ full retina resolution? look @ post var image = new image(); var ratio = window.devicepixelratio || 1; var canvas = document.queryselector("canvas"); var context = canvas.getcontext("2d"); // 1. ensure element size stays same. canvas.style.width = canvas.width + "px...

python - Non-greedy mode in re.search() does not match to end of string -

i'm trying parse values of cookie this: import re m = re.search("(.*?)=(.*?); path=(.*?); domain=(.*?)", "name=value1; path=/; domain=my.domain.com") print (m.group(0)) result this: name=value1; path=/; domain= my question is: why not match @ last non-greedy position? expected result be: name=value1; path=/; domain=my.domain.com of course, change greedy mode or use end of line character ( $ ) i'd understand why it's not working expected work :) non-greedy means match little can while still allowing entire match succeed. * means "zero or more". least can match zero. matches 0 , match succeeds. the other occurrences of .*? in regex cannot match zero, because entire regex fail match.

Select & retrieve multiple rows from a sorted datatable in R Shiny -

using https://demo.shinyapps.io/029-row-selection/ reference, building app select number of rows in sorted/unsorted data & retrieve corresponding indices. if use code as is , not work on sorted data. changed code follows: server.r library(shiny) shinyserver(function(input, output) { output$tbl <- renderdatatable( mtcars, options = list(pagelength = 10), callback = "function(table) { table.on('click.dt', 'tr', function() { $(this).toggleclass('selected'); shiny.oninputchange('rows', table.rows('.selected').data()[0][0]); # returns actual row number not allow multiple selection }); }" ) output$rows_out <- rendertext({ paste(c('you selected these rows on page:', input$rows), collapse = ' ') }) }) ui.r library(shiny) shinyui(fluidpage( title = 'row selection in datatables', sidebarlayout(...

c++ - Map a range of values to a single value -

i need map values ranging between lowerbound , upperbound value. illustrative example: for example, imagine have gps system has users subscribed it. system able provide me distance of user point. based on distance of user want assign them id. thus users in distance 1 100 id: 8.4 101 200 id: 7.2 201 300 id: 3.6 401 600 id: 4.1 and on... my approach: so did, created std::map initializing follows: std::map<int, double> distancetoidmap; distancetoidmap = { {100, 8.4}, {200, 7.2}, {300, 3.6}, }; then use code id given distance: double rounduptohundred = std::ceil(realdistance / 100.0) * 100; double powerfordistance = distancetoidmap.at(rounduptohundred); however approach breaks down 401 600 distance, because ceiling nearest hundred distance of 400+ value 500 don't have entry in map. of course trivial solution add entry 500 distancetoidmap not how want handle problem. i have map ...

c - Infinity loop while reading data from file -

i'm trying read data file. there 3 rows. i've done below. problem (file exists) infinity loop while reading file. i've observed program not moving line line until reaches end of file. what's incorrect in code? code: if (desktops == null) { printf("\n no such file.\n"); } else{ printf("\nfile exists. reading\n"); while(!feof(desktops)){ if(numberofobjects== 0) { fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n",&height,&length,&width,&processorclock,&idnumberserial,&processortypechars,&nameinnetworkchars,&id); nameinnetwork = string(nameinnetworkchars); processortype = string(processortypechars); // nameinnetwork = "test"; glowalistyobjektow = new desktop(height,length,width,processorclock,idnumberserial,processortype,nameinnetwork,id); i...

javascript - Why are the radio buttons resetting when clicking on this jquery datepicker -

here jquery datepicker: $.fn.dcalendarpicker = function(opts){ return $(this).each(function(){ var = $(this); var cal = $('<table class="calendar"></table>'), hovered = false, selecteddate = false; that.wrap($('<div class="datepicker" style="display:inline-block;position:relative;"></div>')); cal.css({ position:'absolute', left:0, display:'none', 'box-shadow':'0 4px 6px 1px rgba(0, 0, 0, 0.14)', width:'230px', }).appendto(that.parent()); if(opts){ opts.mode = 'datepicker'; cal.dcalendar(opts); } else cal.dcalendar({mode: 'datepicker'}); cal.hover(function(){ hovered = true; }, function(){ hovered = false; }).on('click', function(){ // scrip...

Is it possible to allow many users to make live broadcasts using YouTube API and a single account? -

i want make web application , want use youtube api allow users make live broadcasts. is necessary users log google/youtube accounts use live stream or possible make them use function without bothering them detail? in order create live event , live stream objects required livestream on youtube, user making requests must authenticated. from docs: your application must have authorization credentials able use youtube live streaming api. obtaining authorization credentials guide here . adding live event similar uploading video. user making upload must authenticated in order video appear on channel.

javascript - Phaser.js: How to use Text as sprites -

Image
in game numbers game elements: can moved, touched, exploded , have collision detected. how can turn text sprites and/or physical bodies using phaser.js? you cant because sprite , text different node can attach text empty sprite , when move sprite text move same collision need manually

java - Determine if Week Number is Even or Odd -

how can check date see if week number or odd? calendar cal = calendar.getinstance(); date currentdate = new date(); cal.settime(date); int week = cal.get(calendar.week_of_year); for example, if return current date 1/6/2015 return string even; odd week number return string odd. system.out.println(week % 2 == 0 ? "even" : "odd");

jquery - Javascript change multiple element style on click -

Image
consider following images, lets user guess win sports match im trying following: change style (text color) of selected teams black, inorder user see selected before pressing submit while($fixtures> $upcoming){ //radio buttons select team <input type="radio" id="'.$x.'"onclick="teams()" name="picks['.$x.']" value="'.$row['team1'].'"/> <input type="radio" onclick="teams()" name="picks['.$x.']" value="'.$row['team2'].'"/> <input type="radio" onclick="teams()" name="picks['.$x.']" value="draw" /> echo'<b>by</b>'; echo'<select name="score[]" id="score[]">'; echo'<option value="0">0</option>'; echo'<option value="1">1</o...

security - See if user is accessing two systems from same computer? -

so have 2 systems. 1 control completely, , other less so, still can put code here or there, javascript/html however. on different domains. 1 flag of potential malicious activity when single machine accessing both systems, i.e. same computer. there reliable way (ignoring people trying circumvent it) can tell if single machine accessed both systems. what tried was, when person viewed critical page on domain.com, used domain2.com's api see ip address last used there , compared them. however, because of nat, many flags since 2 computers on same network have same exposed ip. i investigated cookies, because of browser security doesn't seem viable option. is there reliable method detect this? make site set cookie on load, , make site b send request url on site sets different cookie. if, in either request, user has other cookie, something.

c# - Custom Authorize Attribute on asp.net mvc -

i have asp.net mvc app authorizes azure aad. app based on github example: https://github.com/dushyantgill/vipswapper/tree/master/trainingpoint this app has custom authorize attribute public class authorizeuserattribute : authorizeattribute { protected override void handleunauthorizedrequest(authorizationcontext ctx) { if (!ctx.httpcontext.user.identity.isauthenticated) base.handleunauthorizedrequest(ctx); else { ctx.result = new viewresult { viewname = "error", viewbag = { message = "unauthorized." } }; ctx.httpcontext.response.statuscode = 403; } } } however seems odd me. i have on controller this: public class globaladmincontroller : controller { // get: globaladmin [authorizeuser(roles = "admin")] public actionresult index() { return view(); } } as ...

button - Android pop in animation -

i mave floating action button in app want sort of pop in, invisible , starts grow size 60dp , resizes normal size of 56dp. how can done? know how normal fade in animation, not pop in. i create animation file in res/anim , use sequential scale animation so: expand_in.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:fromxscale="0.0" android:fromyscale="0.0" android:toxscale="1.1" <!--set scale value here--> android:toyscale="1.1" android:pivotx="50%" android:pivoty="50%" android:duration="400"/> <!--length of first animation--> <scale android:fromxscale="1.1" <!--from whatever scale set in first animation--> android:fromyscale="1.1" android:toxscale=...

c# - structured variables pass to method becomes zero? -

unity c# global struct variable treated local surprised need seek advise. in start: struct st{ public float f; public bool b_toprocess;}st st; st = new st(){b_toprocess = true}; in update: if(st.b_toprocess) process(st); somewhere in same .cs: process(st st){ debug.log("f:" + st.f); // 0 st.f += 0.1f; if( st.f > 5){b_toprocess = false;} debug.log("f:" + st.f); // 0.1f } but process run never-ending !!!! logs showed f 0 on start of each , subsequent iteration , after += 0.1f never greater 5. right should accumulative on each iteration. question is: how come st.f @ 0 on each iteration. local variable treated way passed in struct variable. please some1 advise. thanks. my psychic debugging powers telling me expect struct behave reference type. in c#, structs value types. when call process() , whole struct copied, not reference. change in struct not reflected in struct in calling method. if make class instead, wi...

c# - Exporting an ECDSA public key to a format recognisable by non-.NET users (e.g. OpenSSL) -

i've been working on signing , verifying files ecdsa, , have got in-house tests working fine. however, can't complete testing client, because cannot import public key. i'm using cngkey.export(cngkeyblobformat.eccpublicblob) , appears format of resulting byte[] proprietary (and therefore useless). how might export in more-common format (such pem or der), readable non-.net users, without over-reliance on third-partly libraries (e.g. don't want have rewrite use bouncycastle)? for example, how from: const string keyname = "my key"; var provider = cngprovider.microsoftsoftwarekeystorageprovider; var cngoptions = cngkeyopenoptions.userkey; if (cngkey.exists(keyname, provider, cngoptions)) { using (var key = cngkey.open(keyname, provider, cngoptions)) { byte[] keydata = key.export(cngkeyblobformat.eccpublicblob); } } ...to: -----begin public key----- mhyweayhkozizj0caqyfk4eeacidygaelkrqn7wigwvhp0hcmubzps/l5zdp4mbg a...

xml - Obtaining Previous element in xslt 1.0 sort order, not dom order -

Image
i have cd list entries not in specific sort order: <?xml version="1.0" encoding="utf-8"?> <catalog> <cd> <title>empire burlesque</title> <artist>bob dylan</artist> <country>usa</country> <company>columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>hide heart</title> <artist>bonnie tyler</artist> <country>uk</country> <company>cbs records</company> <price>9.90</price> <year>1988</year> </cd> <cd> <title>greatest hits</title> <artist>dolly parton</artist> <country>usa</country> <company>rca</company> <price>9.90</price> <year>1982...

oracle - Pl/Sql array inside a statement -

i'm trying prepare function, i've started sql sketch figure out how manage situation: declare x xmltype; begin x := xmltype('<?xml version="1.0"?> <rowset> <row> <start_datetime>29/05/2015 14:23:00</start_datetime> </row> <row> <start_datetime>29/05/2015 17:09:00</start_datetime> </row> </rowset>'); r in ( select extractvalue(value(p),'/row/start_datetime/text()') deleted table(xmlsequence(extract(x,'/rowset/row'))) p ) loop -- whatever want r.name, r.state, r.city -- dbms_output.put_line( 'to_date('''|| r.deleted ||''', '''|| 'dd/mm/yyyy hh24:mi:ss'')'); dbms_output.put_line( ''''|| r.deleted ||''''); delete mytable a.start_datetime not in (''''|| r.deleted || ''''); end loop; end; i've tr...

java - How does the ternary operator evaluate the resulting datatype? -

given piece of code public class main { public static void main(string[] args) { foo(1); foo("1"); foo(true?1:"1"); foo(false?1:"1"); } static void foo(int i){system.out.println("int");} static void foo(string s){system.out.println("string");} static void foo(object o){system.out.println("object");} } this output get: int string object object i can't understand why in last 2 cases foo(object o) invoked, instead of foo(int i) , foo(string s) . isn't return type ternary expression evaluated @ runtime? edit: what confusing me assertion that system.out.println((y>5) ? 21 : "zebra"); compiles because ( oca study guide - sybex ): the system.out.println() not care statements differnt types, because can convert both string while point println overloaded accept object types input. quite misleading, imho. isn't re...

Javascript HTML .children traversal -

i'm trying go through of elements in document , pull ones target class name. importantly, i'm needing without use of document.getelementsbyclassname(classname) / document.queryselectorall , etc. — that's point of learning exercise. here's javascript: var getelementsbyclassname = function(classname){ var rootelem = document.body; var collectionresult = []; if (rootelem.getattribute("class") == classname) { collectionresult.push(rootelem); }; var nexttier = function(collectionresult, rootelem) { var thistier = rootelem.children; (i=0; i<thistier.length; i++) { var classes = thistier[i].getattribute("class"); if (classes != undefined && classes.includes(classname)) { collectionresult.push(thistier[i]); }; var childrenarray = thistier[i].children; if (childrenarray.length > 0) { nexttier(collectionresult, childrenarray) }; }; }; nexttier(collectionre...

etl - Sparse lookup for tracking used records -

i have scenario have claim application table , application claimant table. need sparse application claimant id application claimant table using ssn key. problem there multiple application claimant ids same ssn. pull ones not used in claim_application table. using sparse below query. select ssn, claim_application_claimant_id claim_application_claimant orchestrate.claim_application_claimant_id not in ( select claim_application_claimant_id claim_application ) but when going map key expression in lookup stage, throwing below error. key expression cannot set on key columns of link.the connected stage defines key lookup what issue here? i baffled please explore these options. in nested query add distinct clause , clause equate ssn between both tables try alternate approach involving use of joins. try using sql minus operator if columns equal in number

php - Get images out of product description in phtml file -

as title might let suggest have trouble image url's out of product descriptions in custom phtml file (located in template folder). in cms pages/blocks can use {{media url="wysywig/banner/image.jpg"}} which parts (headlines) of our product descriptions. now when try display description out of phtml file with <?php echo nl2br($productresult[$i]->getdescription()); ?> the description gets loaded image url's dont converted total url's example "/media/wysywig/banner". i know have use mage::geturl("media") in php/phtml files though information doesn't in situation. the idea have set string function search {{media url="wysywig/banner/image.jpg"}} , replace mage::geturl("media/wysywig/image.jpg") kinda feel isn't elegant solution. or way? appreciated. , greetings mpfmon it doesn't work because not planned product description have such media call: {{media url="wysywig...

javascript - removeAttr is partly working -

i trying implement removeattr when page loads overide inline css. partly working isn't everything. here jsfiddle demo problem https://jsfiddle.net/argilmour/efmxol0h/ $(document).ready(function(){ $('.text_default').children().removeattr('style'); }); i think need change jquery selector. change javascript : $('.text_default *').removeattr('style'); according jsfiddle, forgot add jquery. add in html code : <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> and in jsfiddle, add library in column on left side of web page.

Do django db_index migrations run concurrently? -

i'm looking add multi-column index postgres database. have non blocking sql command looks this: create index concurrently shop_product_fields_index on shop_product (id, ...); when add db_index model , run migration, run concurrently or block writes? concurrent migration possible in django? there no support postgresql concurent index creation in django. here ticket requesting feature - https://code.djangoproject.com/ticket/21039 but instead, can manually specify custom runsql operation in migration - https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runsql

algorithm - CLRS Solution 8.4 example of decision tree -

do have example of decision tree solution problem. i want draw decision tree use in response question (for understand). don't know how draw decision tree. example don't know leaf used representation of algorithm question 2 suppose given n red , n blue water jugs, of different shapes , sizes. red jugs hold different amounts of water, blue ones. moreover, every red jug, there blue jug holds same amount of water, , vice versa. your task find grouping of jugs pairs of red , blue jugs hold same amount of water. so, may perform following operation: pick pair of jugs in 1 red , 1 blue, fill red jug water, , pour water blue jug. operation tell whether red or blue jug can hold more water, or have same volume. assume such comparison takes 1 time unit. goal find algorithm makes minimum number of comparisons determine grouping. remember man not directly compare 2 red jugs or 2 blue jugs. 1.describe deterministic algorithm user Θ(n2) comparis...

python - ipython parallel cluster parallel decorator and higher order functions -

i take existing function (from scikit-learn example: "predict" function), , apply using multiple cores dataset. my first naive approach: def parallel_predict(classifier): @dview.parallel(block=true) def predict( matrix ): return classifier.predict(matrix) return predict doesn't work (multiple cores don't start spinning up). there way make work? or way have "non-iterable" functions passed @dview.parallel function? couple of thoughts, both based on remote execution doc . i'm used @remote decorator , not @parallel 1 you've used, they'll still apply case. (can't seem that doc load today, reason). is case remote execution not working because classifier module not accessible on engine? if so, solved adding import statement decorated function explicitly, using with dview.import_sync(): import classifier (as per this example ), or adding @require('classifier'): decorator (from same section ...

Save image in couchbase lite java -

how save image in couchbase lite in core java? save image in couchase server, convert image bytes , save bytes. not having in couchbase lite. kindly me. final bufferedimage image = imageio.read(new file(file.getpath())); bytearrayoutputstream baos = new bytearrayoutputstream(); imageio.write(image, "png", baos); document img_doc = db.getdocument("image"); map<string, object> img_properties = new hashmap<string, object>(); img_properties.put("image", bytes); img_doc.putproperties(img_properties); any non-valid json type (like image example) can stored in couchbase lite binary attachment. attachment created using setattachment on revision object. content of attachment stored in filesystem , revision keeps reference it. way, can attachment through document or revision object. see code example here .

javascript - jquery open div with dynamic id -

i want use jquery open , close div. because code use dynamic , repeated below each other, need use dynamic id. html: <div class="categoryratings-review-<?php echo $this->htmlescape($_review->getid())?>" style="display: none;"> <p>text</p> </div> <span class="showcategoryratings" id="review-<?php echo $this->htmlescape($_review->getid())?>"> <span class="showcategoryratings-text">per category</span> </span> i try use jquery, guess php line not working: $(document).ready(function() { $('#review-<?php echo $this->htmlescape($_review->getid())?>').click(function() { $('.categoryratings-review-<?php echo $this->htmlescape($_review->getid())?>').slidetoggle("fast"); $(this).toggleclass('active'); }); }); how need edit correctly? you can without php in ja...

angularjs - Make blob download work in FireFox and IE10/11 -

Image
i have following code in angularjs supposed receive array of bytes web api method , download file. this code working in latest google, when try in latest firefox code executes without errors, no download occurs. in ie 11, download not happen. question : how can make blob code work in latest firefox , ie 10/11? return mydataservice.getbytearray() .then(function (data) { var bytearray = new uint8array(data); var element = angular.element('<a/>'); element[0].href = window.url.createobjecturl(new blob([bytearray], { type: 'application/octet-stream' })); element[0].download = 'mydatareport.pdf'; element[0].click(); }); update 1 : in ie 10/11, code executes without errors till element[0].click() called, when following error happens.

java - fast way to execute multiple CREATE statements -

i access neo4j database via java , want create 1,3 million nodes. therefore create 1,3 million "create" statements. figured out, query way long. can execute ~100 create statements per query - otherwise query fails: client client; webresource cypher; string request; clientresponse cypherresponse; string query = ""; int nrqueries = 0; for(hashmap<string, string> entity : entities){ nrqueries++; query += " create [...] "; if(nrqueries%100==0){ client = client.create(); cypher = client.resource(server_root_uri + "cypher"); request = "{\"query\":\""+query+"\"}"; cypherresponse = cypher.accept(mediatype.application_json).post(clientresponse.class, request); cypherresponse.close(); query = ""; } } well, want execute 1,3 million queries , can combine 100 1 request, still have 13,000 requests, take long time. there way faster? ...

javascript - Modify a value in a foreach to change another one -

i've got question foreach loop: foreach ($result $row) { $html.='<tr> <td>'.$row['product_name'].'</td> <td>'.recuphourminsec($row['date_add']).'</td> <td><input type="text" name="preparationtime" id="preparationtime" value="15" /></td> <td>'.date('h:i:s', strtotime("+$preparationtime mins".$row['date_add'])).'</td> <td>'.$row['lastname'].' '.$row['firstname'].'</td> <td>'.$row['phone'].'</td> <td>'.$row['phone_mobile'].'</td>'.'</tr>'; } i change value of textbox on website time when order ready. i want add value of text field preperationtime time order taken, 20:00:00 example, , disp...

c# - File types change into .xml while downloading in Firefox -

in asp .net application can upload doc files , after uploading files can view in browser. working in browser, there 1 issue while view through firefox, while clicking hyperlink view file being download, file type changes .xml (xml extension). there problem while open it. can open making changes in firefox settings not practical in clients machine. working in previous version firefox. , still working in other browser chrome , ie, , downloads in same file type while clicking hyperlink view. how can download files original file type in firefox. please me are setting mime type response.contenttype correctly? e.g.: httpcontext.current.response.contenttype = "text/xml"; also remember firefox having problem spaces in filenames - had escape them. might extension getting cut off. years ago, might not relevant anymore. can check out anyways: incorrect: response.addheader("content-disposition", string.format("attachment;filename={0}", filename)...

social networking - Sitecore return field "Fields" with zero count in SocialProfiles -

sitecore return field "fields" 0 count in socialprofiles, fields in social network exist. how can need fields? var socialprofilemanager = new socialprofilemanager(); var twitternetwork = allprofiles.firstordefault(x => x.networkname == "twitter"); if (twitternetwork.fields.count != 0) //dicitionary "fields" empty here { ... } i had similar situation trying retrieve fields , dealing 0 field count. take @ post: https://stackoverflow.com/a/30519345/4897782 specifically, issue resolved when passed false second parameter in base login method. default true parameter attempts update profile asynchronously, making unavailable during attempts doing. to able override parameter though, had deviate standard out of box login controls , implement own version of happens when click login. it's pretty simple though. take @ post , resolves issue.

.net - HashSet vs. List performance -

Image
it's clear search performance of generic hashset<t> class higher of generic list<t> class. compare hash-based key linear approach in list<t> class. however calculating hash key may take cpu cycles, small amount of items linear search can real alternative hashset<t> . my question: break-even? to simplify scenario (and fair) let's assume list<t> class uses element's equals() method identify item. a lot of people saying once size speed concern hashset<t> beat list<t> , depends on doing. let's have list<t> ever have on average 5 items in it. on large number of cycles, if single item added or removed each cycle, may better off using list<t> . i did test on machine, and, well, has very small advantage list<t> . list of short strings, advantage went away after size 5, objects after size 20. 1 item list strs time: 617ms 1 item hashset strs time: 1332ms 2 item list strs time: 781ms 2 it...