Posts

Showing posts from March, 2012

java - Shuffle cost in Spark -

i have run various spark jobs these last months , have done performance analysis not in depth (not as have liked). have noticed drop of performance added per core when add more , more cores, expected because spark must have constant cost (or @ least not parallelizable) operations, amdhal's law applies. however, not enough explain i'm seeing. i trying reason in abstract way cost of shuffling data on network depending on number m of machines in cluster. reasoning following : hypothesis the total data size in bytes d there n >= m partitions the data randomly (in terms of partitioning function) equally (same amount d/m of data) distributed before shuffle the partitioning function balanced (=> each partition represents 1/n of data) each machine must end same number of partitions n/m on optimize distribution of data reasoning since data randomly distributed, each machine contains 1/m of each partition before shuffling. since each machine must have n/...

github - work flow for using git 2.5 for multiple work directories using 'git worktree' -

being new git, i'm trying overview of how use multiple work directories different branches off 1 github project. in particular want/need work on 2 branches - 1 'master' other 1 maintenance release, maintenance/project1. plan run work under linux/mint 17.2. well, make use of latest git worktree features introduced in 2.5. assuming have github account, have forked own fork off main project , have cloned fork local machine in ~/user/myproject. as things stand now, don't expect contribute code via git push, results of work & testing passed on others possible fixes via e-mail - doing via git might nice down road, won't necessary start. what see steps need corresponding set of git commands are: creating 2 work tree switching between these trees keeping both trees up-to-date upstream master any other cautions/ special considerations working way. creating 2 work trees git clone https://github.com/someone/someproject.git (this give dir...

bash - Python script calling shell script with Image Magick -

i have bash script has calls "convert" command in imagemagick. script works fine when execute in terminal manually. have path 'convert' command added system path. when try execute using script(written in python) , run error 'convert' not found. here simple example reproduce issue. on osx maverick. shell script: convert_svg_to_png.sh #!/bin/bash filename in *.svg; convert "$filename" "`basename $filename .svg`.png" done python script: runme.py import subprocess subprocess.call('./convert_svg_to_png.sh') error: ./convert_svg_to_png.sh: line 5: convert: command not found any idea why error? edit: when bash script modified include whole path convert function. new error pops up: dyld: library not loaded: /imagemagick-6.8.9/lib/libmagickcore-6.q16.2.dylib referenced from: %fullpath%convert reason: image not found the shell being called python /bin/bash. same in terminal. a few things.....

angularjs - Ratchet websocket responses do not change -

i using ratchet websockets connect wamp autobahn front-end. everything works when change topic code, responses not change! i running in docker, when restart containers updates responses sent if change again nothing happens! your questions doesn't have many details think happening running php websocket server. changing php code , expect server automatically update. isn't how works, have restart websocket code changes take effect. if want have dynamic response without restarting socket suggest using database or other data store can dynamically change , php can fetch from

twitter bootstrap - how can i Get proportional gray color? -

here list have: $gray-base: #000 !default; $gray-darker: lighten($gray-base, 13.5%) !default; // #222 $gray: lighten($gray-base, 46.7%) !default; // #777 $gray-light: lighten($gray-base, 65%) !default; // #a6a6a6 $gray-lighter: lighten($gray-base, 93.5%) !default; // #eee but want make #dddddd in proportional style above other color are.how can done.thanks $gray-medium: lighten($gray-base, 86.5%) !default; // #dddddd you can test here: http://fiddlesalad.com/less/ html: <div style="width:100px; height:100px;" class="graymedium"></div> less: @gray-base: #000; @gray-medium: lighten(@gray-base, 86.5%); .graymedium{ background: @gray-medium; } in source css window should see: .graymedium { background: #dddddd; }

c++ - Are nameless parameters in main() strictly conforming? -

c++ allows following 2 definitions of main: int main() { } int main(int argc, char* argv[]) { } it allows char*[] char** , argc , argv named whatever programmer wishes. however, allow: int main(int, char*[]) { } is identical above examples? strictly conforming? note, don't care if compiles in favorite compiler, i'm asking standards only. yes, stated @captain obvlious, c++ cares type of parameters. c++ standard committee papers publicly available here reference. 3.6.1 main function an implementation shall not predefine main function. function shall not overloaded. shall have return type of type int, otherwise type implementation-defined. all implementations shall allow both — function of () returning int and — function of (int, pointer pointer char) returning int

hadoop - How to convert NaN values into zeroes in Pig -

i trying convert nan zeroes using pig scripting below keep getting error message. can share thoughts on how handle nan's in pig.any insights appreciated. thank you. my input field xyz::abcd has null,not null,nan values in it. need convert nan's zeroes. xyz::abcd <> 'nan' (part of code) one approach read field chararray , have a x = foreach xyz generate (abcd == 'nan' ? '0.0' : abcd); then can convert chararray float or int or whatever.

c# - Object reference is required for non-static TextBox -

Image
c# n00b here. can't figure out why error on textbox.text saying: on googling error, seems it's textbox being static..? can please explain means? how make non-static? have background in java, obj-c, python , swift if can draw similarities there. code: namespace wpfapplication2 { /// <summary> /// interaction logic mainwindow.xaml /// </summary> public partial class mainwindow : window { public mainwindow() { initializecomponent(); } private void button(object sender, routedeventargs e) { // create openfiledialog microsoft.win32.openfiledialog dlg = new microsoft.win32.openfiledialog(); // set filter file extension , default file extension dlg.defaultext = ".txt"; dlg.filter = "text files (*.txt)|*.text"; // display openfiledialog calling showdialog method nullable<bool...

How to tell cmake to look in /usr/local/zlib/lib instead of /usr/lib? -

i trying compile apitrace, however, when run cmake, got following message -- not find zlib: found unsuitable version "1.2.5", required @ least "1.2.6" (found /usr/lib/libz.dylib) i have installed recent version of zlib in /usr/local/zlib , how can tell cmake in path? tried cmake -dcmake_prefix_path=/usr/local/zlib/ didn't work. i erased files within build directory , run again cmake variable -dcmake_prefix_path set zlib , found it.

android - Responsive design - not showing my tablet design on tablet -

i have responsive site built media queries: mobile, tablet, , desktop. when view site on 7 inch samsung galaxy tab 2 vertically mobile view, , when view horizontally appears desktop view. so questions is, happening because of device's display , set break point? or have wrong meta? or maybe different altogether? meta tag <meta name="viewport" content="width=device-width, initial-scale=1"> example of media query @media , (min-width: 670px) thank you. the samsung galaxy tab 2 has resolution of 1024x600px. therefore, styles set within media query you've provided not applied when tablet in portrait mode, since viewport width 600px.

jinja2 encoding error in python -

so trying use jinja2 simple html template keep getting error when call render() : warning: ironpythonevaluator.evaluateironpythonscript operation failed. traceback (most recent call last): file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\loaders.py", line 125, in load file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\environment.py", line 551, in compile file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\environment.py", line 470, in _parse file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\parser.py", line 31, in __init__ file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\environment.py", line 501, in _tokenize file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\environment.py", line 494, in preprocess file "<string>", line 21, in <module> file "c:\program files (x86)\ironpython 2.7\lib\jinja2\jinja2\environment.py", lin...

How to use GET in PHP with OneNote API? -

i've got onenote api php sample (thanks jamescro!) working post examples, there's no example , haven't managed put code of own works. here's i've tried without success: // use page id returned post $pageid = '/0-1bf269c43a694dd3aaa7229631469712!93-240bd74c83900c17!600'; $initurl = url . $pageid; $cookievalues = parsequerystring(@$_cookie['wl_auth']); $encodedaccesstoken = rawurlencode(@$cookievalues['access_token']); $ch = curl_init($initurl); curl_setopt($ch, curlopt_url, $initurl); // set url download curl_setopt($ch, curlopt_returntransfer, true); $response = curl_exec($ch); if (! $response === false) { curl_close($ch); echo '<i>response</i>: '. htmlspecialchars($response); } else { $info = curl_getinfo($ch); curl_close($ch); echo '<i>error</i>: '; echo var_export($info); } it returns 'error' info dump. doing wrong? without information on specific...

Database Connectivity with oracle database using c# -

while trying connect oracle database getting following error "a network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. (provider: named pipes provider, error: 40 - not open connection sql server)"} problem may silly 1 first time database need help: my code is: static void main(string[] args) { using (sqlconnection conn = new sqlconnection()) { conn.connectionstring = "data source=orcl_boa; database=boanewdoc;user id=boanewdoc;password=boanewdoc;trusted_connection=true"; conn.open(); //code } you may need reference oracle.manageddataaccess.dll on odtwithodac121012.zip can download oracle site. not use system.data.oracleclient obsolete. var connection = new oracleconnection(yourconnectionstring); try ...

jQuery ajax data retrieve and append -

dead stackoverflow community, i working on comment system project. use jquery ajax call data, using pdo in php database scripting. able store comments database, , when refresh page, can see comments listed out fine. thing can't "append" comment right after clikcing post comments, in console, stats "uncaught error: syntax error, unrecognized expression: sqlstate[hy000]: general error <div class="comment"> <p class="name"><--the user has commented--></p><p class="comment"><--their comment--></p> " i know close, can plase me out? have been struggling 2 days now. following 3 pieces of codes: index page form: <form id="form" method="post' "class="comment"> <input type="hidden" name="post_id" value="<?php echo $post_id ?>" /> <input type="hidden" name=...

node.js - Buffer Octet Stream in NodeJs -

i novice in nodejs , have read buffer not clear. some examples:- 1) var buffer = new buffer(12); 2) var buffer = new buffer([12,54,89]); 3) var buffer = new buffer("confusing buffer", "utf-8"); here queries are, what buffer , way define/implement. what meaning of above examples. in javascript, strings not binary safe. there characters illegal in strings. this of course makes difficult process binary data such images or mp3 files since i/o in javascript deal strings. the solution node developers implemented buffers. think of buffers strings binary data (and remember, text subset of binary data). as specific questions, answer second question answers first question: the example code posted examples of how define buffers .

XFile Sharing: I am not able to install xfile sharing free version on my Linux server -

i have download xfile sharing free script , try install according installation file. not able run script. i have downloaded demo version https://sibsoft.net/xfilesharing.html try changing permisions of install.cgi 755 & try installing again. regards

sql - Indexing mysql table for selects -

i'm looking add mysql indexes database table. of queries selects. best create separate index each column, or add index province , province , number , , name . make sense index province since there dozen options? select * employees province = 'ab' , number = 'v45g'; select * employees province = 'ab'; if usage changed more inserts should remove indexes except number ? an index data structure maps values of column fast searchable tree. tree contains index of rows db can use find rows fast. 1 thing know, db engines read plus or minus bunch of rows take advantage of disk read ahead. may read 50 or 100 rows per index read, , not one. hence, if access 30% of table through index, may wind reading table data multiple times. rule of thumb: - index more unique values, tree 2 branches , half of table on either side not useful narrowing down search - use few index possible - use real world examples numbers as possible. performance can change dynamic...

ios - How to bring a subview's subview to top? -

Image
the following print screen shows layout: i have main view , top view , picture. when press on picture, want semi transaprent black screen appearing on entire view: let scrennrect = uiscreen.mainscreen().bounds let coverview = uiview(frame: scrennrect) coverview.backgroundcolor = uicolor.blackcolor().colorwithalphacomponent(0.3) self.view.addsubview(coverview) but want picture stay on top of coverview ? there way can bring picture in front of coverview ? the problem coverview , imageview have different super views. that's why cannot bring imageview front. in order bring imageview front need move outside of top view view contains top view , imageview. then, can add coverview main view, , bring imageview front. another solution: place image view inside coverview @ exact same position.

r - igraph 1.0 cannot plot trees in mode "in" -

Image
the tree layout of igraph (1.0.1) doesn't work when trees "in" instead of "out". instance, these trees plotted if no layout used: library(igraph) # create tree graph. vertex 1 root. tree <- graph.empty(15) tree <- tree + path(5,4,3,2,1) tree <- tree + path(8,7,6,5) tree <- tree + path(15,14,13,12,11,10,9,5) # make_tree new in igraph 1.0 tree.in <- make_tree(20, 3, mode="in") tree.out <- make_tree(20, 3, mode="out") par(mfrow=c(1,3)) ### no layout plot(tree, vertex.label=na, vertex.size=6, edge.arrow.size=0.1) title("tree") plot(tree.in, vertex.label=na, vertex.size=6, edge.arrow.size=0.1) title("tree.in") plot(tree.out, vertex.label=na, vertex.size=6, edge.arrow.size=0.1) title("tree.out") however, if tree reingold-tilford layout called, can plot tree.out ### tree layout plot(tree, vertex.label=na, vertex.size=6, edge.arrow.size=0.1, layout=layout....

javascript - Jquery slider attach with Mouse event -

i using jquery slider working fine in chrome browser but when run same code in firefox event attach mouse , when move either left or right auto slide scroll. so want functionality chrome. can 1 please me how can stop hover effect firefox i using samve version of jquery-min.js , jquery-ui.js 1.11.1 , jquery-ui.css version 1.9.1 . any one's thought or review appreciated i paste complete code below , set fiddle link <html> <head> <title>slider problem</title> <link href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script> </head> <body> <div id="" class="span12 sliderspecific ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corne...

algorithm - Combining Overlapping Date Ranges - Java -

i have task class looks following (using java 8 time api). class task { localdatetime start; localdatetime end; set<string> actionitems; } i have 2 sorted (first start, end) lists containing such task instances, lets list<task> taskslist1 , list<task> taskslist2 . want combine overlapping tasks (by breaking tasks if needed, , adding actionitems other tasks overlapping single new task object). for example, assume have task called t1 starts on 01/01/2015 , ends on 01/31/2015, contains action items , b. user creates new task t2 starts on 01/15/2015 , ends on 02/15/2015 , adds action item c it. when combine, should 3 task objects follows. task x - 01/01/2015 01/15/2015, contains action items a, b task y - 01/15/2015 01/31/2015, contains items a,b , c task z - 01/31/2015 02/15/2015, contains item c to visualize, if task object 2 lists following in timeline: > [-----] [-----] [----] [-----------------] > [-----...

How to move community or collection logo in DSpace xmlui? -

i move community or collection logo current position under search within community/collection: form. put logo above <div id="aspect_artifactbrowser_collectionviewer_div_collection-home" class="ds-static-div primary repository collection"> below community/collection name or right of <div id="aspect_artifactbrowser_collectionviewer_div_collection-search-browse" class="ds-static-div secondary search-browse"> . don't know template use or how override it. i tried template: <xsl:template match="dri:div[@id='aspect.artifactbrowser.collectionviewer.div.collection-search-browse']"> <xsl:apply-templates select="./mets:filesec/mets:filegrp[@use='logo']"/> </xsl:template> the template match above removed browse by buttons , search form. your template removes behaviour happen dri:div[@id='aspect.artifactbrowser.collectionviewer.div.collection-search-browse...

java - Writing a parser for a binary message format -

i need develop parser binary message exchange format i.e., message parser parses binary message java object representation. ask useful patterns used implement parser in flexible way. describe in nutshell or provide resources read? since youre trying read binary data , transform java object, there many approaches, first thing first, must know structure/protocol of binary. the pattern show bellow style (if you) use scenario. make sure have input stream stream out binary data. if have byte array, make bytearrayinputstream. in objects graph, each node/object should implement parsein(inputstream s) method. public class parent extends arraylist<child> { int age; // ... more code here public void parsein(inputstream is) throws ioexception { // .. logic read stream instance. datainputstream dis = new datainputstream(is); this.age = dis.readint(); // .. if necessary child c = new child(); c.parsein(inputstre...

java - JDBC with MySQL really slow, why -

i have problem slow connection between java code , mysql remote database when use multiple query. this code arraylist<server_log> ar =server_log_utilities.getby2dates(cmb_date.getselecteditem() + "", cmb_date2.getselecteditem() + ""); (int c = 0; c < ar.size(); c++) { server_log sl = ar.get(c); string username = user_utilities.getusername(sl.getuser() + ""); string row[] = {sl.getdate(), sl.gettime(), username, sl.getreff(), sl.getdescription()}; } but user code data load fast arraylist<server_log> ar =server_log_utilities.getby2dates(cmb_date.getselecteditem() + "", cmb_date2.getselecteditem() + ""); (int c = 0; c < ar.size(); c++) { server_log sl = ar.get(c); string row[] = {sl.getdate(), sl.gettime(), sl.getreff(), sl.getdescription()}; } this user_utilities.getusername(sl.getuser() + ""); method public static string getusername(string id) { ...

android - Rotate image left/right as we can do in gallery and save -

i trying rotate image left/right can in gallery , saving it, problem losing quality , when open gallery, thumbnail of rotated image show original(not rotated) , when open image see original image (not rotated) , after seconds gallery loads rotated image. ideally how should happen, can check in gallery, try rotated image, can see thumbnail rotated properly. in short want rotate image left/right see in gallery. please needful. i tried many solutions what have done when user clicks rotate left/right icon in app execute code private void writerotatedbitmap(float angle) { try { file file = new file(sheetpaths.get(count)); bitmap bmp = bitmapfactory.decodefile(sheetpaths.get(count)); matrix matrix = new matrix(); matrix.postrotate(angle); bmp = bitmap.createbitmap(bmp, 0, 0, bmp.getwidth(), bmp.getheight(), matrix, true); fileoutputstream out; out = new fileoutputstream(file); bmp.compress(bitmap.compre...

linux - How smartphones get the right APN Settings? -

i wonder how smartphones right apn settings. when in other country. for example: not possible dial in in netherlands apn when in austria. everytime smartphone finds local apn´s able connect them. how if dont know right apn settings? i have modem connected raspberry pi , have tried put several sim cards different countries in want use when not in austria. every single connection must give dial program (wvdial) right apn settings make connect. isn´t possible search apn´s in reach , automatically connect them? greets there called config-sms witch hidden sms provider sends smartphone.

cordova - Javascript Code security -

i have created web application cross platform application development using javascript sdk of parse.com. should secure code, entire code, api keys, client keys gets visible once view page source. this back-end can come play, make ajax requests backend has api/client keys backend source code not visible. far not revealing source code, recommend javascript minifier.

spring - Void means(V is capital) -

getjdbctemplate().query(getfilecontentsql, new rowmapper<void>() { public void maprow(resultset rs, int rownum) throws sqlexception { oraclelobhandler lobhandler = new oraclelobhandler(); inputstream inputstream = lobhandler.getblobasbinarystream(rs, "file_content"); exlimporter importer = new exlbomimporter(inputstream); importer.process(); } }, fileid); please tell me void ? note : v capital. form javadoc : the void class uninstantiable placeholder class hold reference class object representing java keyword void.

Spring Batch : Job start/restart from any of the multiple steps included -

i using spring batch 3.0.3. have job named jbabc, inlcudes 3 steps. possible, can run user defined steps while invoking jbabc. roles might need start/restart job abc1, whereas other roles need start/restart abc2 , other group might need start/restart abc3. looking run job based on custom/user defined step parameter. <job id="jbabc" xmlns="http://www.springframework.org/schema/batch"> <step id="abc1" next="abc2" > <tasklet ref="abc1tasklet"></tasklet> </step> <step id="abc2" next ="abc3"> <tasklet ref="abc2tasklet"></tasklet> </step> <step id="abc3"> <tasklet ref="abc3tasklet"></tasklet> </step> </job> have @ http://docs.spring.io/spring-batch/trunk/reference/html/configurestep.html chapter 5.3.2. you can implement first step, whicht retur...

ios - NSDate throwing BAD_EXCESS for what? -

Image
i have below. @interface myviewcontroller () { nsdate *mycurrentdate; } @implementation myviewcontroller -(void)viewdidload { [super viewdidload]; mycurrentdate = [nsdate date]; } - (ibaction) prevaction:(id)sender { nslog(@"mycurrentdate===%@", mycurrentdate); // here says mycurrentdate = [mycurrentdate datebyaddingtimeinterval:60*60*24*-1]; [self formatdateandpostonbutton]; } when try print current date below, crash saying bad_excess nslog(@"mycurrentdate===%@", mycurrentdate); below screenshot same. i'm not using arc in project. any idea going wrong? since not using arc, easiest way retain objects use generated setters/getters. instead of: @interface myviewcontroller () { nsdate *mycurrentdate; } make @interface myviewcontroller () @property(nonatomic, retain) nsdate* mycurrentdate; @end so keep nsdate retained. right nsdate gets deallocated when auto-release pool drained. you need us...

smalltalk - How do I ask the user for a file name? -

searching call of filedialog i ask user file name in pharo 4.0 through spotter found class filedialogwindow with method answerfilename looking senders of #answerfilename class uitheme where called in method choosefilenamein: athemedmorph title: title extensions: exts path: path preview: preview and there come class teasilythemed with method choosefilename: title extensions: exts path: path preview: preview from there class widgetexamples class >> exampledialogs and have call widgetexamples examplebuilder choosefilename: 'pick file name' extensions: nil path: nil preview: nil. however print it of expression not give file name. question what regular way of calling file dialog? supplementary question after answers two classes mentioned providing service. uimanager uitheme uimanager comment uimanager dispatcher various ui requests. uitheme comment common superclass user interface themes. pro...

ruby on rails - required: true on text_field_tag does not work -

i have text field tag , reason cannot use html5 validations = text_field_tag :email, params[:email], required: true, placeholder: "search user" the html output field shows required="required" it's there can still submit search form emtpy field. what doing wrong?

python - pycharm exercise "Character Escaping": task completed but wrong syntax -

i'm following built-in tutorial in pycharm edu edition , i'm stuck on strings - character escaping. in exercise i'm asked print following: name of ice-cream "sweeet'n'tasty" using character escaping, , here's code: print("the name of ice-cream \"sweeet\'n\'tasty\"") and still gives me "sorry wrong string printed". don't think printed wrong string. help? you have escape " because use in print ' not need protected. printing "\'n" , "'n" output same line escape, if not visible, generate read exercise controller. try removing \ before ' print("the name of ice-cream \"sweeet'n'tasty\"") another solution string containing " or ' use triple " this: print("""the name of ice-cream "sweeet'n'tasty\"""") in case, fact sentence terminated " force protect again,...

javascript - TinyMCE spellchecker request error 404 -

i have searched in many ways solution of problem not found working solution. i have visited many questions on platform not found working solution. i know can use browser checker not case. have use editor's spellchecker. problem when click spellcheck option under tools did not work , shows error spellchecker request error : 404 i have following code initiate plugin. <script> tinymce.init({ selector: "textarea", theme: "modern", extended_valid_elements : "script[charset|defer|language|src|type|width|height]", relative_urls : false, plugins: [ "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker,jbimages", "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking", "save table contextmenu directionality emoticons template paste textcolor" ], content_css: "css/conte...

c - Calloc does not initialize entire memory block to zero -

while playing implementation of hashmap toy example (for fun) i've found strange behaviour, calloc not initialize entire memory block want zero, supposed do. following code should produce no output if entire memory block zeroed: #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #define dict_initial_capacity 50 typedef struct dictionary_item { char* ptr_key; void* ptr_value; } dict_item; typedef struct dictionary { dict_item* items; uint16_t size, max_capacity; } dict; dict* dict_new() { dict *my_dict = calloc(1, sizeof *my_dict); my_dict->items = calloc(dict_initial_capacity, sizeof my_dict->items); my_dict->size = 0; my_dict->max_capacity = dict_initial_capacity; (int j = 0; j < my_dict->max_capacity; j++) { int key_null = 1; int value_null = 1; if ((my_dict->items + j)->ptr_key != null) key_null = 0; if ((my_d...

entity framework - Stop empty strings at the database level with EF code first -

consider following poco entity entity framework code first: public class foo { public int id { get; set; } [required, stringlength(100)] public string name { get; set; } } which generate following table: create table [dbo].[foo] ( [id] int identity (1, 1) not null, [name] nvarchar (100) not null, constraint [pk_dbo.foo] primary key clustered ([id] asc) ); now, understand default behavior of ef convert empty strings null. if explicitly feed empty string validation exception, which perfect . following code throw dbentityvalidationexception : var f = new foo { name = "" }; context.foos.add(f); context.savechanges(); but, problem if have external application accesses database directly, can perform following query and succeeds : insert dbo.foo(name) values ('') the best solution arguably not allow connect directly database , force them through business layer. in reality may not possible. if, say, myself im...

Making dictionary construction shorter in Python using defaultdict? -

is there anyway can make code-block shorter? seems written more efficiently: combs = defaultdict(list) zf in zipfiles: chunks = zf.split('_') combs[chunks[0] + '_' + chunks[1]].append(zf) maybe searching this: combs = defaultdict(list) zf in zipfiles: combs["_".join(zip.split("_")[0:2]].append(zf)

android - NPE while using createBitmap -

i got npe line: bitmap bm = bitmap.createbitmap(base64encodedecode.decodebase64(taskitems.get("task_image"))); logcat: caused by: java.lang.nullpointerexception: attempt invoke virtual method 'int android.graphics.bitmap.getwidth()' on null object reference the problem taskitems.get("task_image") includes 4 spaces instead of decoded base64 string . how can check if base64 string correct string . i tried like: string taskimage = taskitems.get("task_image"); if (taskimage.trim().length() > 10) but, if there 200 of times 'a' token. what can check if bitmap string bitmap string ? bm null, calling getwidth() on throws nullpointerexception . problem bitmap.createbitmap() returns null. your npe comes line doing: "attempt invoke virtual method 'int android.graphics.bitmap.getwidth()' on null object reference". check return value of bitmap.createbitmap() , base64encodedecode.decodebase6...

php - Issue getting $_POST from multiple checkboxes -

i made form multiple checkboxes in it, follows: <form action="" method="post"> <div class="row"> <div class="col-sm-9"> <div class="form-group"> <label>choose rooms:</label> <ul id="scegli_camere"> <li><input type="checkbox" name="rooms[]" value="101" > camera 101</li> <li><input type="checkbox" name="rooms[]" value="102" > camera 102</li> </ul> </div> </div> </div><!-- /.row --> <div class="row"> <div class="col-lg-6"> <button type="submit" class="btn btn-primary" id="btn_submit"><i class="fa fa...

c# - Azure Elastic DB - Modify schema in each shard -

i'm new elastic db feature azure , looks awesome. not find how can update schema of shards. if have multiple shards , want add/remove column, table or add/remove stored procedure. well shards databases access , modify 1 one there no way publish schema changes multiple shards @ once? if don't mind playing preview, have @ sql database elastic jobs allow execute scripts across sql databases.

java - Remove elements with same date from JSONArray -

so, have sort jsonarray contains jsonobject. strucuture of json following: [ { "id": 582, "istransaction": false, "todate": "2015-08-26 16:12:00.0", "fromdate": "2015-08-24 15:11:00.0", "status": "request_accepted_by_both_sides" }, { "id": 602, "istransaction": false, "todate": "2015-08-21 21:52:00.0", "fromdate": "2015-08-20 23:53:00.0", "status": "request_accepted_by_both_sides" }, { "carfk": 1, "endmileage": 1455, "ownername": "celien", "model": "335i", "status": "driver_set_odometer", "ownerid": 1, "todate": "2015-08-26 16:12:00.0", "startmileage": 455, "id": 421, "fromdate": "2015-08-2...

unit testing - Android: Test running failed: Instrumentation run failed due to 'java.lang.IncompatibleClassChangeError' -

i have projects several unit tests. when try execute tests in android studio or terminal using gradle clean connectedcheck got following error: test running failed: instrumentation run failed due 'java.lang.incompatibleclasschangeerror' reproduced on android 5.x devices, on 4.x no errors happen. if try run separate tests package, suite, class or test in android studio, tests going well. i don't understand why. need execute tests terminal build.gradle file: apply plugin: 'com.android.application' android { compilesdkversion 18 buildtoolsversion "22.0.1" defaultconfig { applicationid "com.xxx.yyy" minsdkversion 9 targetsdkversion 18 testapplicationid "com.xxx.zzz.tests" testinstrumentationrunner "android.test.instrumentationtestrunner" } packagingoptions { exclude 'meta-inf/license.txt' exclude 'meta-inf/notice.txt' ...

javascript - panel header change colour on click of button -

i have button changes colour of site, (text etc etc) i'm wanting change background colour of panel header. currently button works on afo. heres stylesheet it .afo { background-color: #fff;} .afo h1 { color: #00159d; } .afo h2 { color: #00159d; } .afo h3 { color: #00159d; } .afo h4 { color: #00159d; } .afo h5 { color: #00159d; } .afo h6 { color: #00159d; } .afo p { color: #00159d; } .afo th { background-color: #c3cced; color: #00159d;} .afo panel-header { background-image:-webkit-linear-gradient(top, #c3cced, #00159d ) !important; color: #00159d !important;} the html <div class="panel-heading orange ct-orange" ng-class="colorscheme">details</div> i have button working, i'd show javascript cant find :( when inspect element afo gets added onto end of class, quite persistant in staying orange (its original colour) so far, way have been able change panel colour via changing top line in css .afo { background-color: #fff; background-imag...

c# - What is the difference between task and thread? -

in c# 4.0, have task in system.threading.tasks namespace. true difference between thread , task . did sample program(help taken msdn) own sake of learning parallel.invoke parallel.for parallel.foreach but have many doubts idea not clear. i have searched in stackoverflow similar type of question may question title not able same. if knows same type of question being posted here earlier, kindly give reference of link. a task want done. a thread 1 of many possible workers performs task. in .net 4.0 terms, task represents asynchronous operation. thread(s) used complete operation breaking work chunks , assigning separate threads.

Django Rest Framework: Access item detail by slug instead of ID -

is possible use object's slug (or other field) access details of item, instead of using id? for example, if have item slug "lorem" , id 1. default url http://localhost:9999/items/1/ . want access via http://localhost:9999/items/lorem/ instead. adding lookup_field in serializer's meta class did nothing change automatically generated url nor did allow me access item manually writing slug instead of id in url. models.py class item(models.model): slug = models.charfield(max_length=100, unique=true) title = models.charfield(max_length=100, blank=true, default='') # arbitrary, user provided, url item_url = models.urlfield(unique=true) serializers.py class classitemserializer(serializers.hyperlinkedmodelserializer): class meta: model = item fields = ('url', 'slug', 'title', 'item_url') views.py class itemviewset(viewsets.modelviewset): queryset = item.objects.all() seri...

symfony - Symfomy2 get url parameter in routing condition -

i trying set following route /** * @route( * "/api/list/{setname}/{order}", * condition= "request.get('order') == 'something' " * * ) */ but can produce 404s because condition never true although pass in order argument. guess "request.get('order')" part wrong, how it? try condition= "request.query.get('order') == 'something' " instead of condition= "request.get('order') == 'something' " check more here , here

powerbuilder - Composite datawindow get Clicked Row -

i have composite datawindow in nested datawindow label type datawindow. have created userobject using composite datawindow. in double click event of datawindow want able find out clicked row of nested datawindow. every time double click row variable 1 , getrow() 0. i doing following: datawindowchild idw_child idw_compsite.getchild('dw_child', idw_child) idw_child.settransobject(sqlca) idw_child.getrow() //this returns 0 //another try //this returns band row# tabbed separator //however 2nd page row# returns 0. string ls_band_row ls_band_row = idw_child.getbandatpointer()

ios - Monitor the count of a mutable array in swift. -

hi want monitor count of mutable array in swift. whenever add/remove objects array, need notification regarding count. kvo helps here?, if not other possible solutions. appreciated. you should able use kvo in swift using dynamic keyword. however, particular problem—why not try using property observer : var mutablearray: [anyobject]? { didset { println("count changed \(oldvalue.count) \(newvalue.count)") } }

android - Update Textclock when changing locale -

i'm using textclock widget in app layout. must support different languages, , add dateformat must full date "eeee, dd mmmm yyyy hh:mm:ss a". problem days name , months stays default locale. when change locale programatically not change. any suggestion? shouldn't handled automatically? try using public void settextlocale (locale locale) : resources res = context.getresources(); // change locale settings in app. displaymetrics dm = res.getdisplaymetrics(); android.content.res.configuration conf = res.getconfiguration(); conf.locale = new locale(language_code.tolowercase()); yourtextclock.settextlocale(conf.locale); res.updateconfiguration(conf, dm);

android - How to use activity instead of fragment in default navigation drawer? -

i using default navigation drawer on android studio ... want make case 0 in onnavigationdraweritemselected(int position) method switch activity instead of fragment navigation drawer still exist on left side of screen what have newactivity can start normaly can't use navigation drawer more @override public void onnavigationdraweritemselected(int position) { // update main content replacing fragments fragment objfragment = null; switch (position){ case 0: startactivity(new intent(this, newactivity.class)); break; } } please need help if still need navigation drawer in activity, makes no sense start new activity, use fragment instead. maybe provide more info regarding why want activity receive more accurate answer.

javascript - Can an extension close a tab? -

this in continuation of: script close current tab in chrome i'm trying in extension instead of tampermonkey script, have "matches" : ["*://*.youtube.com/*", "*://youtube.com/*"], in manifest file, , js script chrome.tabs.remove(tab.id); or window.close(); both don't close youtube.com page open. could it's impossible close tab extension? chrome.tabs not available content scripts, if that's in code, fails exception. window.close has caveat: this method allowed called windows opened script using window.open() method. if window not opened script, following error appears in javascript console: scripts may not close windows not opened script. i'm not sure if applies content scripts - suppose does. you can make work adding background script (that has access chrome.tabs ) , either detect navigation there, or message background script context script it. messaging background: // content script chrome.runtim...

spring - Handle UserRedirectRequiredException (A redirect is required to get the users approval) -

introduction one week ago, began development of application using oauth2 framework (with spring boot v1.3.0.m4). brand new experience me. try make simple possible understand better. using spring security oauth2 , facing difficulties use correctly. what want do authenticate user when 1 authorize application. actually, don't want him register on application can freely use without having fill boring forms register. problem encountered i can't find way handle userredirectrequired exception. because don't it, user never redirected authorization page , exception thrown (and unhandled). my application standardcontroller.java package org.test.oauth.web; import java.security.principal; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.restcontroller; @restcontroller public class standardcontroller { @requestmapping(value = ...