Posts

Showing posts from May, 2014

c++ - How to get string data back using pointer? -

i can not string data using pointer char array. give me explanation doing wrong please. #include "stdafx.h" #include <conio.h> #include <string> using namespace std; string getstring() { return string("255"); } int _tmain(int argc, _tchar* argv[]) { char* str_p = const_cast<char*>(getstring().c_str()); printf("pointer : %s\n", str_p); string str; str = str_p[0]; str += str_p[1]; str += str_p[2]; printf("constructed : %s\n", str.c_str()); _getch(); return 0; } the console output : pointer : constructed : there lot wrong line: char* str_p = const_cast<char*>(getstring().c_str()); getstring() returns temporary string . gets destroyed @ end of line. end dangling pointer internal data deallocated. furthermore, const_cast should ever using if really really need - editing data directly asking trouble. if want pointer string, right thing is: string old = get...

java - Will Proguard or the Compiler Precalculate TimeUnit.Minutes.toMillis(120) -

currently have class following effectively constant field. private static final long activity_timeout_ms = 1 * 60 * 1000; this fine, still not readable code in world. i'd rather use following: private static final long activity_timeout_ms = timeunit.minutes.tomillis(1); which states want time 1 minute field milliseconds. my question either compiler or perhaps proguard fix there no performance hit? if there performance hit, can expect 1 time hit per instance of class? yes, one-time hit on class loading, , such tiny fraction of class loading it's not measurable against overhead of loading class in first place. no, compiler can't figure out, , surprised if proguard could, doesn't matter.

c# - Kendo UI TreeListDataSource Read() only works when running locally -

Image
i have kendo treelist datasource defined as var ds = new kendo.data.treelistdatasource({ transport: { read: { url: "/home/read/", type: "post", datatype: "json" }}, schema:... } my controller's read method is: [httppost] public string read() { log.info("start read()"); var vm = vmhelper.getclientorglistviewmodel(); var json = new javascriptserializer().serialize(vm.facilitylist); log.debugformat("json read returned: {0}", json); return json; } everything works great long run locally through vs once deploy our staging server, read() transport code never gets executed. 500 error. pressing f-12 view requests in ie shows 500 error any ideas or suggestions on why works locally not on server , how resolve is...

xsd - How to prevent service on Oracle Service Bus (OSB) from changing xmlns prefix/aliases to random things? -

we have requirement send specific namespace alias client , must use osb. proxy service changes name space aliases of exposed wsdl crafted. cannot find option prevent osb doing so. for example for namespace http://schemas.xmlsoap.org/wsdl/ , original wsdl start has <soap:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/"/> but osb exposes wsdl this <wl5g3n0:definitions xmlns:wl5g3n0="http://schemas.xmlsoap.org/wsdl/"/> the original alias "soap" automatically changed "wl5g3n0" osb , causing problem. same type of renaming happening many of referenced xsd files. how prevent renaming of aliases in osb? i got answer oracle community forum and closing this . seems knowledgeable osb said there no known way him turn auto renaming off. it seems answer "no, cannot turn off automatic renaming of xmlns prefix in osb"

How to dynamically set the local maven repo for a jenkins job -

i'm trying create jenkins job using jenkins remote access api[1]. want achieve is, want specify local maven repository job(instead of using global repository), using job configuration(config.xml) send create job api. how can achieve that? xml attributes should have added(or changed)? [1] https://wiki.jenkins-ci.org/display/jenkins/remote+access+api according api that: curl -x post -h "content-type:application/xml" -d @config.xml "http://jenkins_host/createitem?name=some_job_name"

Assigning variables in loop Python -

i have piece of: as, bs, cs, ds, es = ([] in range(5)) line in infile: line = line.rstrip() a, b, c, d, e = line.split('\t') += [a] bs += [b] cs += [c] ds += [d] es += [e] since have many more 5, want loop takes less lines of code writing of out. like: as, bs, cs, ds, es = ([] in range(5)) dynamic_variable_list = [as, bs, cs, ds, es] line in infile: line = line.rstrip() in range(len(line.split('\t'))): dynamic_variable_list[i] += line.split('\t')[i] which in case stores individual characters in list, whereas: dynamic_variable_list[i] += line.split('\t') stores tab delimited entries each of variables of dynamic_variable_list . need store of tab delimited entries in separate variables top example shows. dynamic_variable_list[i] += line.split('\t')[i] can rewritten as as += rather than as += [a] either surround in brackets before, or use append . or rat...

ember.js - Rendering models from an ember-data store, using a http-mock server and RESTAdapter fails -

i'm having issued hooking ember-data http-mock using simple model. want load api containing properties, , render them list on page. when navigating /properties/ route described below, error being thrown: error: not found @ ember$data$lib$system$adapter$$adapter.extend.ajaxerror (rest-adapter.js:714) @ ember$data$lib$system$adapter$$adapter.extend.ajax.ember.rsvp.promise.hash.error (rest-adapter.js:789) @ jquery.callbacks.fire (jquery.js:3143) @ object.jquery.callbacks.self.firewith [as rejectwith] (jquery.js:3255) @ done (jquery.js:9311) @ xmlhttprequest.jquery.ajaxtransport.send.callback (jquery.js:9713) and template doesn't render. here's i've done: added property model: import ds 'ember-data'; export default ds.model.extend({ title: ds.attr('string'), date_added: ds.attr('date') }); added 'routes/properties.js' looks this: import ember 'ember'; export default embe...

xcode - Could not load NIB in bundle using storyboard -

with last version of ios 8.3, error when run 1 of app: terminating app due uncaught exception 'nsinternalinconsistencyexception', reason: 'could not load nib in bundle: 'nsbundle the app has 2 storyboards, 1 iphone (working normally) , other ipad (crashing). i've tried suggestions of topic no results: xcode 6.3: not load nib in bundle in case i'm using storyboards , i've no flag on "use size classes". until ios 8.2 app worked fine. is ios 8.3 bugs? founded solution? thank you! edit: if use ipad storyboard on iphone , iphone storyboard on ipad work! tried rename storyboards, nothing change. edit 2: splitviewcontroller initial view controller causes crash! if move initial view controller view controller app works! edit 3: news: problem caused masterviewcontroller of splitviewcontroller. i'm using tabbarcontroller masterviewcontroller , crash ios 8.3. if change masterviewcontroller view, app works. if have done progra...

c# - Struggling with EF CodeFirst 1 to Many relationship -

i able tag movie category . public class movie { public virtual observablecollection<category> categories { get; set; } public void addcategory(string name) { using (var dbcontext = new mydbcontext()) { var category = dbcontext.categories.singleordefault(x => x.name == name) ?? new category(name, dbcontext); categories.add(category); dbcontext.savechanges(); } } } public class category() { public category(string name, dbcontext dbcontext) { name = name; dbcontext.categories.add(this); dbcontext.savechanges(); } } if category not exist, created , dbcontext.categories.add(this) called inside category c'tor. there no errors, new category not saved movie.categories . i guessing because movie class belongs different context? unsure how structure this. edit: if using database first approach, result movie_categories table has movie_id , category_id . why di...

excel - Changing VBA that creates Multiple PDFs to Single PDF -

the code below working great create pdfs worksheet 3 worksheet named "post" while ignoring hidden sheets. creates individual pdf each of these worksheets. linked shape users click , prompted select folder save pdfs. i'm trying alter code below exact same thing except create single pdf each visible worksheet between sheet 3 , "post". i've been massaging code around while , wondering if knows best way accomplish this? sub saveallpdf() dim integer dim fname string dim tabcount long tabcount = sheets("post").index 'set tabcount last cell want pdf dim dialog filedialog dim path string set dialog = application.filedialog(msofiledialogfolderpicker) dialog.allowmultiselect = false if dialog.show = -1 path = dialog.selecteditems(1) ' begin loop. = 3 tabcount 'set = number of first sheet want pdf in order left right tabcount if sheets(i).visible <> xlsheetvisible else sheets(i) ...

javascript - Trying to instantiate an animation class, getting "object is not a function" -

i'm trying instantiate class : var drawcrash = new drawcrash; but i'm getting typeerror: object not function. i've defined class - var drawcrash = { //private variables canvas : ge1doot.canvas(), particles: "", nbrparticles : 160, speed : 6, strength : .4, radius : 4, perspective : 0.5, ang : null, cosorsin1 : null, cosorsin2 : null, enum : { wobble : "wobble", twirl : "twirl" }, setdrawing : function (type) { if (type === this.enum.twirl){ blah blah blah this.cosorsin2 = math.sin; } else if (type === this.enun.wobble){ blah blah blah } else {alert("wrong enum drawcrash");} }, startdrawing : function () { blah blah blah } } is there wrong syntax? that not how instanciate object in javascript. a "class" in world function: function drawcrash() { //private variables var canvas = ge1doot.can...

php mysql edit table form revert the table's fields to it's original values -

i have form editing table in database, when edit table using forms nothing , give no errors. when edit phpmyadmin works, if edit using php form reverts fields values it's original values gave in add form. i'm using pdo class connect mysql database. here php code edit table, it's kinda miss know :/, note store form values in arrays because have loop in creating form give fields each employee , of course change name of fields using prefix: <?php if((isset($_get['action'])) , ($_get['action'] == 'edit')){ //get employees info $employees = pdo_fetchall("select * employees"); //echo "<script>alert('aa');</script>"; //initial values $official_days_e = array(); $official_vacations_e = array(); $attendance_days_e = array(); $present_days_e = array(); $vacations_e = array(); $vacations_record_e = array(); $table_namee = $_pos...

javascript - jQuery does not send Cookie to server -

cross-domain problem. http same domain https. server requires x-requested-with header set in jquery ajax options: 'headers': {'x-requested-with': 'xmlhttprequest'} jquery sends option then: options /my/test/ http/1.1 host: www.my.dev origin: http://www.my.dev access-control-request-method: post access-control-request-headers: x-requested-with server responds: http/1.1 200 ok access-control-allow-origin: * access-control-allow-methods: get, post access-control-allow-headers: x-requested-with access-control-allow-credentials: true then jquery sends "actual" request: post /my/test/ http/1.1 host: www.test.dev x-requested-with: xmlhttprequest origin: http://www.test.dev cookie header missing! server responds with: http/1.1 403 forbidden content-type: application/json set-cookie: sessid=3tg8svt3lrv97v155uv2kqr3o2; expires=sat, 25-apr-2015 17:35:13 gmt; max-age=259200; path=/ adding 'xhrfields': { 'withc...

bash - how to use alternate vt100 character sets -

according http://www.in-ulm.de/~mascheck/various/alternate_charset/ esc + ) + 0 make g0 set sequence table used or something. http://www.vt100.net/docs/vt100-ug/table3-9.html seems provide description of characters should appear when "table" in use. eg. <?php echo "\x1b)0" . chr(0147) ...should result in ± appearing on console understand it. no ± appearing. instead what's appearing g . so it's not entirely clear me how use in cli environment make ± appear. any ideas? try ( instead of ) : <?php echo "\x1b(0" . chr(0147) ?> ( sets charset used in default "g0" slot, whereas ) effects "g1" slot. shift-in/shift-out escape sequences switch between 2 slots. in mean time, recommend forget legacy stuff , use proper stateless utf-8 , ± sign.

Not able to parse the remainder in django template -

<html> <head> <title>{{ songname }}</title> <meta charset="utf-8"> {% load static %} </head> <body> <center><h1>muosic</h1></center> <hr> <audio controls> <source src="{% static {{ songname }} %}" type="audio/mpeg"> </audio> <hr> </body> here songname name of song want play.all static files in static directory.from view function above template called using render_to_response function.so please can explain reason problem. you can't nest template variables that. assuming songname actual name of file , file in root of static_root , do: {% static songname %}

Android-L issue: onBackpressed when using FLAG_ACTIVITY_REORDER_TO_FRONT to launch previous activity & freezes app for sometime -

my application has strange behaviour i proved issue following steps on android l o.s. devices nexus 7 or moto g. the app starts activity a, shows button called "launch b". press button -- executes startactivity(flag_activity_reorder_to_front, activityb.class) . activity b becomes active, ui , backhand loading operation on ui thread. after pressing activity b, onbackpressed of activity b, executes startactivity(flag_activity_reorder_to_front, activitya.class). activity a's onresume() called expected , looks fine (i can see activity content again). press device's key , app freezes around 10 seconds or more , comes out of application. without calling onpause(), ondestroy(). (so may anr logs) sometime or may repeating same above step 4-5 times unfortunately force close googlequicksearchbox after looking @ system logs: found important logs: e/activitymanager( 958): reason: input dispatching timed out (waiting because no window has focus there focu...

How to view Nginx request string? -

i'm not sure how view request string in nginx, example get/post request. in context; if wanted block mysql injection attacks: if($query_string ~ /(\%27)|(\')|(\-\-)|(\%23)|(#)/ix) { return 403; } does know how to/the variable it's under?

java - Whats faster? Get a null record or check existence? -

i have timeseries lookup. building , requesting corresponding keys if don't exist (getting null record) in span of time. there better way it? checking existence of key, prior example? thanks just records need. my rule of thumb this: "if need know if key exists, check that. however, if first thing you're going key exists value, values." in order check if exists, has lookup on key. difference between , returning value retrieving value. "get" operation have same lookup. if value none, there no additional overhead required return value, except couple bytes store "null" instead of false . however, if need know key exists, there's no reason return whole contents if does.

haskell - What does exactly Identity functor do? -

it may trivial, don't understand following mean. instance functor identity fmap = coerce so, can try define similar: prelude control.lens data.functor.identity> :t fmap fmap :: functor f => (a -> b) -> f -> f b prelude control.lens data.functor.identity> let z f g = coerce f g prelude control.lens data.functor.identity> :t z z :: contravariant ((->) t) => (t -> a) -> t -> b but, mean in simpler terms? the use of coerce new in ghc 7.10 , done efficiency. "real" definition is fmap :: (a -> b) -> (identity -> identity b) fmap f (identity a) = identity (f a) the wrapping/unwrapping of identity constructor should optimized away @ compile time, seems base devs had reason ensure there no performance penalty using coerce . the reason can use coerce identity a isomorphic (the same as) a , can coerce a -> b identity -> identity b happens definition of fmap specialized identity !

javascript - Try to add wookmark layout in angularjs app -

i trying add wookmark layout in angular js app .if there no infinity scroll fine when added angularjs infinity scroll wookmark layout not working means when scroll layout not apply . my infinity scroll function code - $scope.onload = function() { $scope.paramurl = $location.url(); $scope.apiurl = $scope.apiurl+$scope.paramurl; if ($scope.paramurl) { $http({method: 'get',url:$scope.apiurl}).success(function(data) { $scope.productdata = data.deals; $scope.qitem = data; }); } else { $http({method: 'get', url: $scope.url}).success(function(data) { $scope.productdata = data.deals; }); } }; and jquery wookmark code - $(window).load(function() { settimeout(function() { (function ($){ var handler = $('#tiles li'); handler.wookmark({ autoresize: true, container: $('#main_pro_content'), offset: 11, outeroffset: 0, itemwidth: 200, ...

c++ - How to prevent double slot invocation when showing a QMessageBox? -

i've connected editingfinished signal of qlineedit slot in application showing qmessagebox if input in way unexpected. strangely enough message box shown twice, put breakpoint executed , had @ stack trace. there qmessagebox.exec() calls qapplication::processevents() seems somehow forward , process same event again. my stack trace first time looks sth this: myapp::myslot() qlineedit::editingfinished() qguiapplicationprivate::processmouseevent() qeventloop::processevents() qapplication::exec() and 2nd time this: myapp::myslot() qlineedit::editingfinished() qguiapplicationprivate::processwindowsystemevent() qeventloop::processevents() qdialog::exec() // stack trace of run #1 here // [...] i've checked double signal connections or different events being connected slot doesn't seem problem. can explain happens here , how prevent it? it qt bug editingfinished emitted twice, can read here: https://forum.qt.io/topic/39141/qlineedit-editingfinished-signal-is...

java - How do I make the AlertDialog box appear outside the app? -

@override public void run() { //create thread can alter ui alarmpage.this.runonuithread(new runnable() { public void run() { cal = calendar.getinstance(); //see if current time matches set alarm time if((cal.get(calendar.hour_of_day) == alarmtime.getcurrenthour()) && (cal.get(calendar.minute) == alarmtime.getcurrentminute())){ //if sound playing, stop , rewind if(sound.isplaying()){ showdialog(); alarmtimer.cancel(); alarmtask.cancel(); alarmtask = new playsoundtask(); alarmtimer = new timer(); alarmtimer.schedule(alarmtask, sound.getduration(), sound.getduration()); } sound.start(); } } }); } public void showdialog() { final alertdialog.builder alertdialog = new alertdialog.builder(thi...

Runtime error (crashes on input) in MIPS (using MARS) -

i having trouble code. getting runtime error on line 28: runtime exception @ 0x00400044: address out of range 0x00000001. the program supposed take input , return in descending order. main: move $s0,$gp #get intial point save array addi $t0,$0,1 # $t0 = 1 add $t1,$zero,$zero # add $t2,$zero,$zero # add $t3,$zero,$zero # add $t6,$zero,$zero add $t4,$zero,$zero sub $t7,$zero,1 # terminate li $v0,4 # system call put string la $a0,msg1 # syscall # add $s1,$s0,$zero # copy pointer array in $s1 entervalues: li $v0,5 # value in v0 syscall # beq $v0,$t7,bubblesort # end of string run bubblesort lb $v0,0($s1) # **here error** addi $s1,$0,1 # move $s1 pointer 1 add $t5,$s1,$zero # $t5 stores end value j entervalues bubblesort: add $t4,$s0,$zero addi $t6,$0,1 ...

html - “A” tag wrapping “IMG” seems incorrect size. (32 * 32px is shown as 38 * 21px) -

Image
the following issued codes ( http://jsfiddle.net/dz754deg/1/ ). a{ text-decoration: none; } <a href="#"> <img src="http://lorempixel.com/32/32/"/> </a> <a href="#"> <img src="http://lorempixel.com/32/32/"/> </a> the result isn’t strange seemingly. if check browser’s built-in developer tools, a tag has incorrect size. in chrome (latest version), img tag normal (32 * 32px). a tag odd (38 * 21px or 32 * 21px). this image might help: firefox has same issue. think isn’t browser-specific. how can fix gracefully? these 2 styles make blocks appear correctly: a{ display:inline-block; } img{ display:block; } it’s because of how inline , block level elements rendered. can still click on inline link wrapped around image everywhere image looks if couldn’t. jsfiddle demo screenshots rendered in firefox:

xml - XSLT1 Transformation -

i need transform input xml: <log1> <connection user="peter" host="computer01" port="22"/> <connection user="peter" host="computer02" port="22"/> <connection user="peter" host="computer02" port="80"/> <connection user="david" host="computer01" port="8080"/> <connection user="david" host="computer01" port="8080"/> <connection user="david" host="computer01" port="8080"/> <connection user="david" host="computer03" port="22"/> <connection user="david" host="computer04" port="21"/> </log1> into output xml: <log2> <event name="david" target="computer01|computer03|computer04"/> <event name="peter" target=...

linux - Creating a nested for loop in bash script -

i trying create nested loop count 1 10 , second or nested loop count 1 5. for ((i=1;i<11;i++)); ((a=1;a<6;a++)); echo $i:$a done done what though output of loop going was: 1:1 2:2 3:3 4:4 5:5 6:1 7:2 8:3 9:4 10:5 but instead output was 1:1 1:2 1:3 1:4 1:5 2:1 ... 2:5 3:1 ... , same thing till 10:5 how can modify loop result want! thanks your logic wrong. don't want nested loop @ all. try this: for ((i=1;i<11;++i)); echo "$i:$((i-5*((i-1)/5)))" done this uses integer division subtract right number of multiples of 5 value of $i : when $i between 1 , 5, (i-1)/5 0 , nothing subtracted when $i between 6 , 10, (i-1)/5 1 , 5 subtracted etc.

html - Padding have a effect on ::after -

i want create list item, 1 class. but have effect on ::after , ::before. how can prevent that? for example, force ::after stand still , increase padding of class? .magic { width: 100%; height: 30px; background: #57ab27; color: white; font-size: 20px; padding-top: 6px; text-align: center; font-family: "arial", arial, sans-serif; } .magic::before { content: "\f067"; font-family: fontawesome; font-style: normal; font-weight: normal; text-decoration: inherit; /*--adjust necessary--*/ display: block; color: #fff; font-size: 18px; padding-right: 0.5em; position: absolute; top: 17px; left: 20px; } .magic::after { content: ""; display: block; width: 5px; height: 36px; background: white; position: relative; left: 40px; top: -29px; } http://codepen.io/loose...

Closing or opening an Excel or Word file in Selenium IDE -

testing website has links various forms. pdf forms work fine long use “gobackandwait” command. if document word or excel document, clicking link opens document in new window (not pop window). using “close” command closes main window , not document window. how close or open excel or word file using selenium ide , go page. note selenium ide cannot interact embedded objects default. i can offer alternative. instead of opening window, recommend check url of links clicking, , href points appropriate document extension. pseudo: validatepresent | css=#doclink[href$='.docx']

pivot - Dynamically pivoting a table Oracle -

i have table looks this: c_id p_id key value null null key1 value1 null null key2 value2 null null key3 value3 2 2 key4 value4 2 3 key5 value5 i want result table/view: c_id p_id key1 key2 key3 key4 key5 null null value1 value2 value3 null null 2 2 null null null value4 null 2 3 null null null null value5 has idea how achieve this? have tried with: select * (select c_id, p_id, r_key, r_value s_projectroles) pivot (max(r_value) r_key in (any)); i got error: ora-00936: ausdruck fehlt 00936. 00000 - "missing expression" this can done dynamically following way. first, here static version of query can see final sql: select c_id, p_id, max(case when r_key= 'key1' r_value end) key1, max(case when r_key= 'key2' r_value end) key2, max(case when r_key= 'key3' r_value end) key3, max(case when r_key...

android - How to show enable location dialog like Google maps? -

Image
i use latest version of google play services (7.0) , followed steps given in guide , enabled location dialog below, has "never" button. app mandatorily needs location don't want show never user, because once user clicks "never", i'm unable location or request location again @ all. where google maps has yes , no button without never button, idea how achieve same? my app's image google map's image locationsettingsrequest.builder has method setalwaysshow(boolean show) . while document indicates it's doing nothing (updated 2015-07-05: updated google documentation has removed wording), setting builder.setalwaysshow(true); enable google maps behavior: here's code got working: if (googleapiclient == null) { googleapiclient = new googleapiclient.builder(getactivity()) .addapi(locationservices.api) .addconnectioncallbacks(this) .addonconnectionfailedlistener(this).bu...

mysql - Create a new table in SQuirreL SQL through the GUI? -

is possible create new table in squirrel sql through gui? i can't seem find way on ui. 1 of basic piece of functionality db visual tool should have surprised if cannot , have create tables via scripts. any great. thanks. no, squirrel sql not have functionality (as of version 3.6). squirrel sql not "db visual tool", "universal sql client" (as self-advertised) that... (...) allow view structure of jdbc compliant database, browse data in tables, issue sql commands etc. 1 it happens comes graphical user interface.

r - Select matrix first row based on 1st, 8th and 9th column value with awk or sed -

i have rows 1st, 8th , 9th columns same. total number of rows on 60k. want simplify keeping first rows 1st,8th , 9th column same. input file: chr exon_start exon_end cnv tumor_doc control_doc rationormalized_after_smoothing cnv_start cnv_end seg_mean chr1 762097 762270 3 821 717 1.456610215 762097 6706109 1.297328502 chr1 861281 861490 3 101 117 1.29744744 762097 6706109 1.297328502 chr1 7868860 7869039 2 78 119 1.123385189 7796356 8921423 1.088752407 chr1 7869841 7870041 2 140 169 1.123385189 7796356 8921423 1.088752407 chr1 7870411 7870596 2 83 163 1.123385189 7796356 8921423 1.088752407 chr1 7879297 7879467 2 290 360 1.024742732 7796356 8921423 1.088752407 chr1 21012415 21012609 3 89 135 1.230421209 19536504 21054539 1.247494175 chr1 21013924 21014512 3 234 219 1.359224182 19536504 21054539 1.247494175 chr1 21016588 21016803 3 172 179 1.230421209 19536504 21054539 1.247494175 c...

How to list only certain files in R? -

i have thousands of different files (having same extension .img ) in folder called data . if use : dir<- list.files ("c:\\users\\data", "*.img", full.names = true) it list files have in folder data . what need list files named as: file_yyyymmdd_data.img (in yyyymmdd varies 10 years) any idea or hint appreciated! try this files.new = list.files(directory.path, recursive = true, pattern=".img") where, "directory.path" path directory containing files need read edited to more appropriate files.new = list.files(directory.path, recursive = true, pattern="file_[0-9]{8}_data[.]img$")

Spark - Naive Bayes classifier value error -

i have following issue when training naive bayes classifier. i'm getting error: file "/home/juande/desktop/spark-1.3.0-bin-hadoop2.4/python/pyspark/mllib /classification.py", line 372, in train return naivebayesmodel(labels.toarray(), pi.toarray(), numpy.array(theta)) valueerror: invalid __array_struct__ when training model using line dataframe = dataframe.map(lambda x: labeledpoint(sections_to_number[x[4]], tf.transform([x[0], x[1], x[2], x[3]]))) model = naivebayes.train(dataframe, 1.0) where sections_to_number dictionary maps value strings float numbers, example sports -> 0, weather -> 1 , on. however, if train using number instead of using mapping sections_to_number, not error. dataframe = dataframe.map(lambda x: labeledpoint(10.0, tf.transform([x[0], x[1], x[2], x[3]]))) model = naivebayes.train(dataframe, 1.0) am missing something? thanks naivebayes in spark ml package expects dataframe in form of 2 columns label,feature lable co...

xStation: Trying to connect SSL server via PHP Socket client -

i having problem in establishing ssl connection remote server using php socket client. connecting simple socket server easy ssl connection keeping live , doesn't respond anything, please @ code below , guide me mistake doing in following code. page keep loading doesn't respond anything. // command array $command = array( 'command' => 'login', 'arguments' => array( 'userid' => 'xxxxxx', 'password' => 'xxxxxx', 'appid' => 'test', 'appname' => 'test', ), ); $fp = stream_socket_client("ssl://xapia.x-station.eu:5124", $errno, $errstr, 30); if (!$fp) { die("unable connect: $errstr ($errno)"); } /* turn on encryption login phase */ fwrite($fp, json_encode($command)); while ($motd = fgets($fp)) { echo $motd; echo '<hr />'; } fclose($fp);

angularjs - Can't get Bootstrap 3's Scrollspy to work -

i trying scrollspy work, not moving page view items in list. using data-toggle instead of href . when click list item firing off of switching active class in developer console, page not move proper item html <div class="panel-body"> <div class="row col-sm-7" style="position:fixed; background:white"> <div id="myscrollspy"> <ul class="nav navbar-nav" style="border:none"> <li class="active"><a data-toggle="tab" data-target="#java-clients-section-1">section one</a></li> <li><a data-toggle="tab" data-target="#java-clients-section-2">section two</a></li> <li><a data-toggle="tab" data-target="#java-clients-section-3">section three</a></li> </ul> </div> </div> <div class="informationdiv...

ios - Why does the title of a UITabBarItem become "Item" when it's properly set in the storyboard? -

i have tab bar app 4 views. 1 of views (notes) uitableview embedded in uinavigationcontroller (since "note" uiviewcontroller can show , edit cell details) i have built of in layout editor avoid assumptions segues , controllers. have added title , image attributes relevant uiviewcontrollers (and in case of uitableview uinavigationcontroller.) the image , title of "notes" tab shows in layout editor, , other 3 tabs show fine when app runs, when app runs title note tab replaced string "item". odd thing image shows fine. if segue straight uitableviewcontroller works - of course need navigationcontroller tableview - that's no help. here's relevant xib code: <!--notes navigation--> <scene sceneid="gso-qg-y5n"> <objects> <navigationcontroller id="q9r-oo-lqa" userlabel="notes navigation" scenememberid="viewcontroller"> <tabbaritem k...

Transcription with Java -

does know if there possibility how can example transcribe russian input latin? there framework supports that? searching charset doesn't support case thx in advance. map<character, string> translit = new hashmap<>(); static { translit.put('а', "a"); translit.put('б', "b"); translit.put('в', "v"); // ... translit.put('ж', "zh"); // , on } public string transliterate(string input) { char[] c = input.tochararray(); stringbuilder output = new stringbuilder(); (char ch : c) { output.append(translit.contains(ch) ? translit.get(ch) : string.valueof(ch)); } return output.tostring(); }

neural network - Why L1 regularization works in machine Learning -

well, in machine learning, 1 way prevent overfitting add l2 regularization, , says l1 regularization better, why that? know l1 used ensure sparsity of data, theoretical support result? l1 regularization used sparsity. can beneficial if dealing big data l1 can generate more compressed models l2 regularization. due regularization parameter increases there bigger chance optima @ 0. l2 regularization punishes big number more due squaring. of course, l2 more 'elegant' in smoothness manner. you should check this webpage p.s. a more mathematically comprehensive explanation may not fit website, can try other stack exchange websites example

php - How to implement a token based authentication? -

i have implement token based authentication. users have username , password. use sha512 method encrypt password before inserting database. retrieving data server, making queries , other simple actions, need know asking data , if person authenticated. want use token. during registration server creates token user , saves in person table database, username , encrypted password. now, when user wants data server, can use token. is there way in server can understand user using token, or need pass username too? how can know when token expires without adding field in person table? i'm not sure have understand proper use of token, , have no idea on how implement it. use php implementing communications between server/database , android application. as said, it's better provide username , token each time send request backend. can know if token expired or not. let service/backend support http basic authentication requires caller set specific header contains username:pas...

javascript - Clone last column and add it to the same table - jquery -

i want create new column in html table @ end different header name , empty cells. table haa alternate rows colored. i trying : <!doctype html> <html> <head> <title>testing</title> <script type="text/javascript" src="jquery-1.11.2.js"></script> <script type="text/javascript"> function add() { $('#tableid tr').clone().appendto('#tableid'); } </script> </head> <body> <table id="tableid"> <tr> <th>one</th> <th>two</th> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table> <button onclick="add()">add</b...

javascript - Regular expression to not allow 2/3/4 consecutive zeros in string -

i want validate textfield: not want allow below entries in textbox: 100123456- 2 repeating zeros max length 9 120005689- 3 repeating zeros max length 9 100005689- 4 repeating zeros max length 9 i have tried below regex: /^(?!.*(.)\1)(^[1-9][0-9]{8}$)/ it works, not allow repeating other numbers. eg: 114564568- because 1 repeating i want zeros. if there consecutive zeros show error. please help. thanks in advance you can use following regex disallow 2 consecutive 0 s: ^(?!.*00.*)([1-9][0-9]{8})$ or more elegant version: ^(?!.*0{2}.*)([1-9][0-9]{8})$ any 9-digit number starting digit other 0 , , not have 00 pass. actually, if not allow 2 consecutive zeros, won't allow 3 , 4 consecutive zeros @ same time. see demo .

angularjs - Javascript inheritance dependency on constructor parameter -

i implement prototypal inheritance in angular base type defined angular value. problem setting child type prototype. suppose simplified example: file 1 angular.module("test") .value("basecontroller", basecontroller); basecontroller.$inject = [...]; function basecontroller(...) { ... } basecontroller.prototype.func = function () { ... }; file 2 angular.module("test") .controller("childcontroller", childcontroller); childcontroller.$inject = ["basecontroller", ...]; function childcontroller(basecontroller, ...) { basecontroller.call(this, ...); // save reference later childcontroller.base = basecontroller; ... } // error - why childcontroller.prototype = object.create(basecontroller.prototype); // error - instance properties aren't available on level childcontroller.prototype = object.create(childcontroller.base.prototype); inheritance the problem prototype being generated ...

ruby on rails - I18n to call different Model Attribute depending on Locale? -

so building on-line shop , want 2 language options, english , spanish. i using i18n static text , headings ect. but, have products model can have new products created listing on site. has fields :name_en , :name_es, :description_en , :description_es ect. when admin uploads new product need add english , spanish text. because have 2 locales think call like <%= product.name_"#{i18n.locale.downcase}" %> but not work. how can i, or can i, interpolate method or attribute? have missed obvious here , going wrong way or there way along lines of thinking? any massively appreciated. thanks you can use send method. try like: <%= product.send("name_#{i18n.locale.downcase}") %> just word of explanation, following equal: string = "hello" string.upcase # => "hello" string.send("upcase") # => "hello" hope puts in proper direction! good luck!

java - Functionality for automatic retry after exception -

i have made abstract class automatically retry network calls if exception thrown. i take care not retry after interruptedexception & unknownhostexception . i retry 5 times. after each failure perform exponential off, starting 300ms going upto 1500ms. public abstract class autoretry { private object datatoreturn = null; public object getdatatoreturn() { return this.datatoreturn; } public autoretry() { short retry = -1; while (retry++ < staticdata.network_retry) { try { thread.sleep(retry * staticdata.network_call_wait); this.datatoreturn = dowork(); break; } catch (interruptedexception | unknownhostexception e) { e.printstacktrace(); this.datatoreturn = null; return; } catch (ioexception e) { e.printstacktrace(); } } } protected abstract object dowork() throws ioexception; } i use follows : final object dataafterwork = new autoretry() { @overrid...

perl - Setenv $PATH not functioning properly -

i wrote shell script sets $path variable directory contains shell , perl script. i able run shell script current working directory set random directory, perl script different. is there difference between running two? the error thrown is can't open perl script "script.pl" : no such file or directory though file exists in same folder shell script. when run script "perl script.pl", system use path environment locate perl interpreter not script. script name being passed interpreter arg. if script not in cwd, you'll need include path. just running "script" shows permissions denied , running "script.pl" shows command not found. that tells me 2 things. 1) script's name doesn't include .pl ext , 2) when called without ext, find script within path permissions aren't set correctly execute it. as has been stated others, need assign correct permissions allow execute script.

linux - Findout address of shellcode dynamically, placed on stack -

i using shellcode spawn shell,i curious findout starting address of shellcode dynamically,which placed on stack , not hard code address in shellcode kindly share ideas ? have gone through smashing stack fun , profit ,however curious know how codered worm or morris worm figures out address of shellcode dynamically you can find gadgets you. if find set of gadgets result in 1 of registers containing starting address of shellcode, need 'jmp eax'(assuming address in eax) execute shellcode. you'll have overwrite saved eip address of first gadget though. hope helped

dynamics crm 2011 - The given key is not present in the dictionary -

hi trying fetch accounts crm 2011. fetching data in entitycollection . when trying read or access data entitycollection displayed first record throwing error after record. kindly have below code , suggest me. string fetch2 = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='accounttype' operator='eq' value='01' /> </filter> </entity> </fetch>"; try ...

Android - Obtaining view for Activity title and attaching click listener -

i trying crazy here. attach click listener title of activity. either need title view's id or view itself. keep in mind, not defining custom view title. set title in manifest appropriate activity. attach click listener title. how can achieved? direction or solution appreciated. thanks. place on oncreate of activity final int abtitleid = getresources().getidentifier("action_bar_title", "id", "android"); findviewbyid(abtitleid).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { //do } });

javascript - How to change the thead's html of the dataTables -

i need add 2 <span> (clear , check all) thead cell(except frist one). i add fndrawcallback $("#authmanageuserlisttable thead tr th").each(function(){ console.log($(this).html()); $(this).html(".....");//change here, not }); i use same method tbody , work. @ html dom , found th within #authmanageuserlisttable not have text(html), instead, has aria-label . how should add 2 button thead can manipulate data @ column very hard tell you're trying explanation.. something https://jsfiddle.net/yo68wrgb/ maybe? $(function() { $( "th:nth-child(2)" ).append( "<span><input type='checkbox'></input> check all</span>" ); });

arrays - How would I remove a specific item from a combo box in Java? -

i'm using string array populate combo box items. after item has been selected , submitted on button press want remove item combo box. attempt remove selected item string array first, remove items combo box , repopulate string array. choice string array, cbochoice combobox, strchoice item getting removed for(int = 0; < choice.length; i++) { if(choice[i].equals(strchoice)) { choice[i] = null; cbochoice.removeallitems(); cbochoice.additem(choice); } } this far i've got, don't know if there simpler method of doing can't seem working. since have string array , jcombobox have same items in same order, can use jcombobox.getselectedindex() retrieve index location of selected item , remove jcombobox , you're array. as suggestion, make string array arraylist, it's "smarter" dynamic array , can stay better in synch jcombobox. make sure remove array first, before removing jcombobox, ...

c# - 'System.UriFormatException' for 'WebAuthenticationBroker.GetCurrentApplicationCallbackUri()' when authorizing SharpBox in Windows Phone 8 -

i want open web let user allow app access files. code here: config = cloudstorage.getcloudconfigurationeasy(nsupportedcloudconfigurations.dropbox) dropboxconfiguration; requesttoken = dropboxstorageprovidertools.getdropboxrequesttoken(config, "xxxxxxxx", "yyyyyyyyy"); authorizationurl = dropboxstorageprovidertools.getdropboxauthorizationurl(config, requesttoken); uri requesturi = new uri(authorizationurl); debug.writeline("done requesturi"); uri callbackuri = webauthenticationbroker.getcurrentapplicationcallbackuri(); debug.writeline("done callbackuri"); webauthenticationresult result = await webauthenticationbroker.authenticateasync(webauthenticationoptions.none, requesturi, callbackuri); if (result.responsestatus == webauthenticationstatus.success) { icloudstorageaccesstoken accesstoken = dropboxstorageprovidertools.exchangedropboxrequesttokenintoaccesstoken(config, "7nu03leznnz6x74...

java - How to get MavenProject in maven3 -

i want automate part of our build system in java. need calculate dependency tree of sources existent in given file tree. so, want crawl on set of directories , find pom.xml files existent there. works fine. want parse files instances of mavenproject can call getparent() , getdependencies() , such on it. so, question is: how populated mavenproject maven3 libraries? acceptable me include third party library if necessary prefer solution consists of maven natives. i have read get mavenproject pom.xml - pom parser? answers there don't work me (the mavenproject not not populated correctly) my code in java, want have contents of method this: private mavenproject makeprojectfrompom(file pomxml) { // here don't know. } so can in program: public list<mavenproject> getallmavenprojectswithparent(file rootdir, mavenproject parent) { list<file> allpoms = findallpoms(rootdir); list<mavenproject> result = new arraylist<>(); for(file...