Posts

Showing posts from March, 2013

Logical operators in graph database (neo4j) -

Image
edit: possible duplicate of: neo4j logic gate simulation, how to? i have neo4j database contains options, optionvalues, configurations, products , logicalnodes. in concrete, configuration collection of selected optionvalues, 1 each option. logicalnodes on other hand try link combinations of optionvalues point 1 (or multiple) specific products. here have example: you can see in graph there 3 options, 2 2 optionvalues , 1 1 optionvalue. every optionvalue linked product through 1 or more logicalnodes. logicalnodes can linked 1 , there 3 types of logicalnodes (and, or, not (not shown)). now question, know how products related given configuration, not taking logicalnodes account, using cypher: match p = (:configuration {id:"conf1id"})-[r1*]->(pi:productinstance) return pi however, fail come query uses logicalnodes filter out invalid paths. invalid (sub)path when: a logicalnode type equals "and" has more incoming :has_logic relations there in path. a

sql - SQLZoo Hard Questions: Get results that share an ID on the same row -

http://sqlzoo.net/wiki/adventureworks_hard_questions question 11 states: for every customer 'main office' in dallas show addressline1 of 'main office' , addressline1 of 'shipping' address - if there no shipping address leave blank. use 1 row per customer. relevant tables/ids are: customer customeraddress address customer id customerid addressid addressid addressline1 addresstype city my current code select ca.customerid, case when ca.addresstype = 'main office' a.addressline1 else "" end, . case when ca.addresstype = 'shipping' a2.addressline1 else "" end address join customeraddress ca on a.addressid = ca.addressid join address a2 on a.addressid = a2.addressid a.city = 'dallas' there's 5 total main offices in dallas, , 1 has shipping address. when tried &quo

javascript - how can i define iframe to have null content? -

i have code , want after every click content of iframe null , later <div id="code" contenteditable></div> <iframe id="output"></iframe> <button onclick="update()">run</button> <script> function update() { var frame = document.getelementbyid("output"); var framedoc = frame.contentdocument || frame.contentwindow.document; var w = document.getelementbyid("code").textcontent; //************************************ //here want change frame.contentwindow === null; frame.contentwindow.document.write(w); //************************************ } </script> <style> #code{ width:47%; height:81.8%; border:1px solid; } #output{ width:47%; height:80%; border:1px solid; position:absolute; right:0px; top:0px; } </style> thank (-; p.s.- try make editor you need frame.contentwindow.document.close(); after each write, next write clear it. also why not use framedoc have

r - Add a column by row names for the different length -

i have found 2 post here, has partial solution of problem. first here , second here . i have little bit different situation. have list of data frames different length, want join 1 data frame regarding row names. if, row name not in data frame, column should have nan value. for example have next 3 data frames: mylist[1] -> df1: num 1 b 1 mylist[2] -> df2: num 1 b 2 c 3 d 1 mylist[3] -> df3: num c 1 d 1 what want have next dataframe: num1 num2 num3 1 1 nan b 1 2 nan c nan 3 1 d nan 1 1 it means, nan values on right place , not @ bottom of column, in first example. length of dataframes different , not same in second example. i in 2 steps: 1) add id-column containing rownames: mylist <- lapply(mylist, function(x) transform(x, id = row.names(x))) 2) merge data.frame's id-column: reduce(function(...) merge(..., = "id", all=true), mylist) # id num.x

google api php client - Any way to get more details about "internal failure" errors reading gmail from googleapi? -

i've run lot of cases google's api yields less-than-descriptive error message. now i'm getting this: google_service_exception object ( [errors:protected] => [message:protected] => { "error": "internal_failure", "error_description": "backend error" } i'm reading batches of 100 messages @ time php googleapi client listusersmessages function call. interestingly, notice if ask batch that's not round mod 100 number, result list rounded 100. example ask batch size of 156 (just test) , 100. that's side note. real problem works fine, until large number, 8500, or 15000, , internal_failure error. one thing did notice, exception object php client fantastically huge. printed log file, it's 272162 lines long. there's lot of repetition. there's many iterations of 85 array entries this... [sorted:guzzlehttp\event\emitter:private] => array ( [before] => array (

exception handling - System.TypeInitializationException in a match constructor -

i trying discriminated union type string in f# (4.0, vs2015). code looks this: type fooorbar =foo | bar let fooorbarfromstring str = match str | "foo" -> foo | "bar" -> bar | _ -> raise (system.argumentexception("invalid input")) the problem is, if default condition triggered, , exception raised, argument exception wrapped in system.typeinitializationexception. ex: [<entrypoint>] let main argv = let result = fooorbarfromstring "baz" unhandled exception of type 'system.typeinitializationexception' occurred in project.exe further complicating things, vs2015 debugger chokes , shows "source not available". inspecting inner exception in locals view can see going on. is there better way of setting errors in input data don't make debugging massive pain?

javascript - Enable/Disable a button using dojo toolkit -

i have declared button in html , want dynamically enable/disable using javascript , dojo toolkit. i have made following code, should minimal working example: <html> <head> <script language="javascript" type="text/javascript"> require(["dojo/dom", "dojo/on", "dojo/request", "dojo/domready!"], function(dom, on, request){ on(dom.byid("password"), "keyup", function(evt){ request.get("/passwordchecker", { query: { user: document.getelementbyid("username").value, pass: document.getelementbyid("password").value } }).then( function(response){ if(strength === "strong") { dijit.byi

sql - Table subsets comparison -

i using adventureworks database , sql server 2012 t-sql recipes book , got myself trouble on following example : i have check salesquota in both 2007 , 2008 sales.salespersonquotahistory. select sp.businessentityid , sum(s2008.salesquota) '2008' , sum(s2007.salesquota) '2007' sales.salesperson sp left outer join sales.salespersonquotahistory s2008 on sp.businessentityid = s2008.businessentityid , year(s2008.quotadate) = 2008 left outer join sales.salespersonquotahistory s2007 on sp.businessentityid = s2007.businessentityid , year(s2007.quotadate) = 2007 group sp.businessentityid first results are: businessentityid 2008 2007 ---------------- --------------------- --------------------- 274 1084000.00 1088000.00 275 6872000.00 9432000.00 276 8072000.00 9364000.00 277 6644000.00 8700000.00 just book says. but try 2008 salesqu

javascript - Remysharp's js Inview plugin fired velocity transition twice -

i'm using remysharp in view plugin determine when element in view. when in view, use velocity show element in. reason, inside of in view call, animation triggers twice. outside of in view call, works should. why firing twice? $(".xslideupin").one('inview', function (event, visible) { if (visible == true) { $(".xslideupin").velocity('transition.slideupin', { stagger: 700 }).delay(1000) } else { // element has gone out of viewport } }); try with $(".xslideupin").one('inview', function (event, visible) { if (visible == true) { settimeout(function() { $(".xslideupin").velocity('transition.slideupin', { stagger: 700 }).delay(1000) }, 0); } else { // element has gone out of viewport } });

Shadows in three.js : r71 vs r76 -

i'm building 3d environment using three.js , r76 . can't seem shadows right. in r71 , pretty happy result, doesn't work same in r76 . a fiddle illustrate problem: r71 : https://jsfiddle.net/sq2w15xy/ r76 : https://jsfiddle.net/9uuq6s56/ as can see, shadow black , pixelated in newest revision. changed since then? can same smooth shadow in r71 ? i suppose light's shadow.mapsize must set first it's otherwise set ( 512, 512) default. spotlight.shadow.mapsize.width = 2048; spotlight.shadow.mapsize.height = 2048;

swift - NSTableView cuts off content -

i'm building in content inside of nstableview, when compile , run, cuts off top half of content within nstableview. i'm brand new swift language quite lost here. can provide further examples necessary. there simple missing first or more specific use case? i can give few directions go looking help. firstly apple documentation it. https://developer.apple.com/library/mac/documentation/cocoa/conceptual/tableview/populatingview-tablesprogrammatically/populatingview-tablesprogrammatically.html you may note there 2 ways of populating table view, programmatically implementing methods of nstableviewdatasource , nstableviewdelegate protocols. , using cocoa bindings. recommend, beginner, use first option , @ either example code or videos use these protocols. secondly, may ui issue in storyboard, make sure constraints set properly. may have weird behavior going on here other views. unfortunately, cannot give more without code snippets or more information

vb.net - VB2008 event works like the Onchange or Afterchange events? -

i'm trying display information of sale bill depending on it's barcode after writing barcode press enter other information should loaded ... problem event use enter barcode! i tried textchanged,enter,keydown-up-press , tooo many events, useless because not give me chance complete writing full barcode !! start checking data every single key press, work if paste barcode on textbox, not me need write barcode not paste :( i did searches couldn't solve problem :( plz :( private sub barcode_textchanged(byval sender object, byval e system.eventargs) dim cnn new oledb.oledbconnection dim rst new oledb.oledbdataadapter dim sql string dim dt new datatable dim lsp new oledb.oledbcommand cnn.connectionstring = "provider=microsoft.jet.oledb.4.0; data source=" & application.startuppath & "\database9.mdb" cnn.open() sql = "select materialname store code='" & barcode.text & "'"

javascript - Getting Grunt.js to run node.js module -

i have written node.js module can run either file using 'require' or running node copyright.update() terminal. i'm happy functionality , works in both cases. want able run gruntfile.js. currently grunt file looks this: module.exports = function(grunt) { grunt.initconfig({ "update-copyright": { "run": true } }); grunt.task.loadtasks('./runner'); }; and script in runner directory looks this: var copyright = require('./update-copyright'); module.exports = function(grunt) { grunt.registermultitask('update-copyright', 'update copyright headers', function() { var done = this.async(); copyright.update(done); }); }; when run 'grunt update-copright' usual done, without errors nothing has been executed. i'm sure i'm missing simple. appreciated! thanks comment igor raush got run with: var copyright = require('./update

javascript - Should CSS code go with the plugin or in a child theme? -

i making extension existing plugin (so in essence guess i'm writing plugin code). want modify layout/ui of existing plugin. should writing code in plugin's css/js? or need make child theme? the purpose of plugin is theme independent. should enqueue boilerplate css , js plugin itself. tricky because have support multiple grid systems etc. allow theme overrides woocommerce allows. experience, effective approach.

flask - How to check if Celery/Supervisor is running using Python -

how write script in python outputs if celery running on machine (ubuntu)? my use-case. have simple python file tasks. i'm not using django or flask. use supervisor run task queue. example, tasks.py from celery import celery, task app = celery('tasks') @app.task() def add_together(a, b): return + b supervisor: [program:celery_worker] directory = /var/app/ command=celery -a tasks worker info this works, want have page checks if celery/supervisor process running. i.e. maybe using flask allowing me host page giving 200 status allowing me load balance. for example... check_status.py from flask import flask app = flask(__name__) @app.route('/') def status_check(): #check supervisor running if supervisor: return render_template('up.html') else: return render_template('down.html') if __name__ == '__main__': app.run() you can run celery status command via code importing celery.b

windows - Print layout is not covered whole layout of the xaml page? -

Image
i working on windows universal app. have issue regarding print functionality in uwp.in issue when click on print button prints invoice page dynamic designed print not covered whole page layout. i putting xaml code. <grid background="white"> <grid name="gridpopup" visibility="visible" background="white"> <grid.rowdefinitions> <rowdefinition height="50"></rowdefinition> <rowdefinition height="200"></rowdefinition> <rowdefinition height="*"></rowdefinition> <rowdefinition height="78"></rowdefinition> <rowdefinition height="150"></rowdefinition> </grid.rowdefinitions> <stackpanel orientation="horizontal" margin="10,10,0,0" grid.row="0">

asp.net - Using Server.TransferRequest to force download of file to browser -

i intend use asp.net server.transferrequest send file browser without browser knowing actual path of file being downloaded. example, address download.aspx?id=123 should result in browsers save dialog popping up. when use server.transferrequest "redirect" to, say, pdf file, contents of pdf file sent browser; however, content shown in browser window - not surprisingly - unintelligible text. i think there should headers attached response force browser download file, "content-disposition" header doesn't trick. any ideas on how this?

jquery - Bootstrap Make Divs Float Next to Each Other in Columns -

Image
i'm trying reproduce divs floating next each other similar masonry jquery plugin, native bootstrap/css if it's possible. when tried following code output seen below, column on right seems work fine, other 2 don't. i've not added code last column, how can make others float page remove space? html code, generated php: $output .= "<div class='container-fluid'>"; $output .= "<div class='row' class='article-index-areas'>"; while ($stmt -> fetch()) // prints out white boxes { $output .= " <div class='col-sm-6 col-md-4'> <div class='thumbnail' style='height:" . rand(100,300) . "px;'> </div> </div> "; } $output .= "</div>"; $output .= "</div>"; i met same requirement in project,you need give position:absolute , set top,left,width,height of each , every elements

javascript - How to validate read and secure documents in CouchDB? -

in 10 common misconceptions couchdb , joan touzet asked (30:16) if couchdb have way secure/validate reads on specific documents and/or specific fields of document. joan says if has access database, he/she can access documents in database. so says there few ways accomplish that: (30:55) cloudant working on field level security access. have implemented yet? open-sourced? (32:10) should create separate document in separate database. (32:20) filtered replications. mentions slows 'things' down. means filter slows replication, correct? also, according rcouch wiki ( https://github.com/rcouch/rcouch/wiki/validate-documents-on-read ), implements validate_doc_read function (i haven't tested it, though). couchdb has it? as far can see, best approach model database according problem (one database this, that, 1 person, person) , filtered replications when necessary. suggestions?

php - Facebook Graph API call returns false -

i'm amateur programmer trying fetch facebook page likes webpage since not want facebooks standard plugin. after lot of research , testing found out right call make is: https://graph.facebook.com/ {page_id}?access_token={app_id}|{app_secret}&fields=fan_count using in web browser works great , fan count in json. my problem when try make call using either curl or file_get_contents inside php script dont seem back. after doing var_dump bool(false) back. , after doing print_r nothing. is facebook somehow blocking calls or wrong? have tried multiple ways found online , none works. 1 of examples: <?php $json_url = "https://graph.facebook.com/xxxxxxxxxxx?access_token=xxxxxxxxxxxxx&fields=fan_count"; $json = file_get_contents($json_url); $json = json_decode($json, true); print_r($json); echo "number of likes : ". $json[0]->fan_count; ?> this another: <?php $ch = curl_init("https://graph.facebook.co

c# - Message Box won't show, and no errors are found. What am I doing wrong? -

i'm trying make application when 2 selections 2 different list boxes match. test put in "messagebox.show("it works!!!"), , although no syntax errors logically it's not working properly. using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.windows.forms; namespace distance_converter { public partial class form1 : form { public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { if (inputlistbox.selectedindex == 0 && outputlistbox.selectedindex == 1) messagebox.show("it works!!!"); } } } what doing wrong here? i've made sure names correct, can't work. you're code looks good, must not hooked correctly. 2 posible issues can thi

c# - How to secure wcf rest services based on OAuth -

i need secure wcf services based on oauth. in case java application passing me token need validate based on oauth in .net layer , if token passed need call wcf services. i have checked several examples based on oauth not got idea achieve . please me how achieve based on oauth in .net. finally solved below implementation var authheader = weboperationcontext.current.incomingrequest.headers.getvalues("authorization"); if (authheader == null || authheader.length == 0) { throw new webfaultexception(httpstatuscode.unauthorized); } namevaluecollection outgoingquerystring = httputility.parsequerystring(string.empty); var parts = authheader[0].split(' '); if (parts[0] == "bearer") { string token = parts[1]; outgoingquerystring.add("token", token); by

I keep getting this error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28 -

this code : import java.util.scanner; public class main { public static void main(string[] args) { scanner scan = new scanner(system.in); string tweet = scan.nextline(); int link = 0; int tag = 0; int @ = 0; int c = 0; int l = tweet.length(); if (l <= 140) { while (c < tweet.length()) { char let = tweet.charat(c); if (let == '#') { tag++; string hash = tweet.substring(c, c + 2); if (hash.equals("# ")) { tag--; } } else if (let == '@') { at++; string = tweet.substring(c, c + 2); if (to.equals("@ ")) { at--; } } else if (let == 'h') { string http = tweet.substrin

javascript - Angular JSON Display Single Result without Ng-repeat Filter -

i'm still develop app show news update api json. now, load of data json. filter ng-repeat. problem because when load data, it's slow. many data. i want make in controller, 1 row selected. so, can easyly load detail page. i want order news desc. i've use | orderby. works. must load of data in 1 time. make apps slow. want make swipe refresh show 8 posts @ first time. but, load data when swipe (like twitter). controller.php .controller('mediactrl', function($scope, $http) { $http.get('http://api.pemiluapi.org/rekam-jejak-media/api/rekam_jejak?apikey=c6a0237499f3e4197546b5551a3a864f') .then(function(res){ $scope.medias = res.data; //alert(res.data); }); }) .controller('mediadetailctrl', function($scope, $stateparams, $http) { $http.get('http://api.pemiluapi.org/rekam-jejak-media/api/rekam_jejak?apikey=c6a0237499f3e4197546b5551a3a864f') .then(function(res){ $s

c - double free or corruption (faststop) after malloc() call -

i have small program dynamically allocate array of pointer user can enter array of character many time want. created struct flexible array of pointer. problem when try free(arrayptr) , free(arrayptr -> str[i]) malloc call. gives me error double free or corruption (faststop) . when take them out. program works fine still don't understand why. happened behind scene? not supposed use free() in case? #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdbool.h> /* num */ char *getnum() { char *_new, *num, c; int i; num = malloc(sizeof(char)); (i = 0; (c = getchar()) != eof && c != '\n'; i++) { _new = realloc(num, + 2); num = _new; num[i] = c; } if (c == '\n') num[i] = '\0'; num[i] = '\0'; return num; } struct strholder { int size; char *str[]; }; // main int main() {

choice - Constrained multinomial logistic regression in R using mlogit -

i add constraints multinomial logistic regression model using mlogit in r. example negative values during coefficient estimation. apparently model doesn't have such capabilities. wondering if there way add constraints or boundaries mlogit or other packages can used multinomial logistic regression. here code: proc_mdc3 <- function(x){ fm <- mformula(decision ~ term_f1yc + term_f2yc + eff_rate2 + term_special2 + peak -1 ) fit <- mlogit(fm, x) out2<-fit$coefficients return( out2) } coeff4<-data.frame(do.call("rbind", by(mdc3, mdc3$seg, proc_mdc3))) i want negative values eff_rate2 coefficients code gives me both negative , positive values. i appreciate in advance.

windows phone 8.1 - Include Cordova/PhoneGap to a WP8.1 Solution -

i have app complete made using wp8.1 apis. language visualbasic (and xaml) , want add push notification using plugin called "device push notification" (dpn) it's available cordova/phonegap cli. the documentation of dpn says windows phone supported using phonegap, started learn cordova/phonegap, thing can't find information how include phonegap app part of app. want add phonegap's app plugin of actual app. need plugin in special? or have write app again using cordova/phonegap api? you traditionally build entire app in phonegap/cordova. however, if create new blank phonegap/cordova application, , add plugin application, can see source code of buried underneath plugins folder, , can maybe give starting point utilizing logic push notification plugin does.

sql server - C# SqlGeometry DataTable.WriteXml -

i have table in sql server column of type sqlgeometry . loading datatable , i'm executing datatable.writexml . unfortunately, data column of type sqlgeometry not written out. datatable dt = new datatable(); string tabela = string.empty; tabela = "x.yz"; string sqlconstring = @"server=xxx.xxx.xxx.xxx\sqlexpress2012;database=xxx;user id=xx;password =xx; "; string sqlquery = string.format("select * {0}",tabela); using (sqlconnection sqlcon = new sqlconnection(sqlconstring)) { sqlcommand sqlcmd = new sqlcommand(sqlquery, sqlcon); try { sqlcon.open(); sqldatareader dr = sqlcmd.executereader(); dt.load(dr); } catch (exception e) { console.writeline(e.message); } } dt.tablename = "123"; dt.writexml(@"j:\tmp\3.xml

event schedule php MySQL keeping track of upcoming events -

i have been working on event schedule php , mysql goal able have background of website change each event such halloween christmas , on have come 1 work month needing workout day ignoring year <?php $con = mysql_connect(mysql_host,mysql_username,mysql_password); mysql_select_db(mysql_database, $con); $result = mysql_query('select * event_schedule month(start) <= month(now()) , month(end) >= month(now())') or die('query failed: ' . mysql_error()); $edit_theme_row = mysql_fetch_array($result) ?> i have tried adding day in code $result = mysql_query('select * event_schedule (month(start) <= month(now()) , day(start) <= day(now())) , (month(end) >= month(now()) , day(end) >= day(now()))') or die('query failed: ' . mysql_error()); $edit_theme_row = mysql_fetch_array($result) ?> but seem ignore event using template date in mysql example 2015-10-28 2015-11-02 halloween 2015-12-01 2015-12-26 christmas igno

javascript - Multi Serving Classes in HTML 5 depending on screen size -

is possible multi serve classes based on screen sizes? example, have class nested inside class, want nested class run if size of device bigger x. <div class="pure-container" data-effect="pure-effect-push"> <input type="checkbox" id="pure-toggle-left" class="pure-toggle" data-toggle="left"/> <label class="pure-toggle-label" for="pure-toggle-left" data-toggle-label="left"><span class="pure-toggle-icon"></span></label> <nav class="pure-drawer" data-position="left"><br><br><br> <p style="padding: 10px 20px; margin: 0;"> <div class="f-unit expert"> <?php include_once 'helper/block_news_list.php'; ?> </div> </p> </nav> </div> so here have "f-unit

Java recurrence relation with for loop -

public int algo(int n) { if (n == 1) { return 1; } algo(n/2); (int = 0; < 4; i++) { system.out.print(i); } return 0; } i know recursive call mean t(n/2) how loop affect recurrence relation? edit: attempt. i think loop run log n times because run every time algo(int n) run. , algo run log n times because n keeps on being divided 2. also, loop runs 4 iterations. think add 4 log n recurrence o(n) = t(n/2) + 4 log n. since loop constant time , , not vary n . should not affect time complexity.

c# - this operation is not supported in the wcf test client because it uses type system.object[] error using WCF and Entity Framework -

i trying create wcf generic methods going received ilist of different objects, once ilist comes in string tell type of object, them method validate , call function accordingly. when "build" wcf project, completes successfully. testing wcf built in wcf test client, cannot test because each method set published, showing "this operation not supported in wcf test client because uses type system.object[]" error this contract code: namespace wcf_rentacar { [servicecontract] public interface irentacar { [operationcontract] void insert(string tobjeto, ilist objet); [operationcontract] void update(string tobjet, int id, ilist objet); } } then methods set way: namespace wcf_rentacar { {

objective c - EXC_BAD_ACCESS on alloc -

if issue has been posted before, can't find it. i'm attempting allocate , initialize instance of nsstring in initialization method of subclass of nsoperation (for use nsoperationqueue). nsstring pointer ivar (not property). the program crashes "exc_bad_access (code=exc_i386_gpflt)". to isolate problem, i've separated alloc , init functions. main thread crashing on: m_mystring = [nsstring alloc]; the code in "if" block: if (somecondition) { m_mystring = [nsstring alloc]; m_mystring = [m_mystring initwithcstring:acharpointer encoding:nsasciistringencoding]; } else { m_mystring = [nsstring alloc]; m_mystring = [m_mystring initwitcstring:adifferentcharpointer encoding:nsasciistringencoding]; } examining thread shows it's crashing on objc_release. don't understand why release called on object in allocation method , seems case... it's worth mentioning alloc , init instance variable nsstring in same method before if bl

javascript - Use jQuery to scroll to display element which was loaded in via AJAX -

i have script gets images via ajax , displays them on page in div called #media-area, has fixed height , overflow: scroll; . this, user's can select image. on pages, image selected. in case want div scroll selected image positioned along top. $.ajax({ url: 'index.php?c=media&m=media_ajax', success: function (res) { (var index in res) { var me = res[index]; var html = '<div class="col-md-3"><input type="radio" name="medialibrary" id="medialibrary' + me.id + '" value="' + me.id + '">'; html += '<label for="medialibrary' + me.id + '">'; html += '<img src="/image.php?image=' + me.image + '&thumbnail=122,122" alt="' + me.name + '" id="img_medialibrary' + me.id + '" width="122" height="122">';

ruby - Why is my block only executed once? -

why that: array = (1..20).to_a array.index.each_slice(5) |slice| puts slice.inspect end returns: [1, 2, 3, 4, 5] [6, 7, 8, 9, 10] [11, 12, 13, 14, 15] [16, 17, 18, 19, 20] while: other_array = [] array = (1..20).to_a array.index.each_slice(5) |slice| puts slice.inspect other_array.push(1) end returns only: [1, 2, 3, 4, 5] how other_array.push(1) breaks execution of block? obvious conclusion cannot access variables not in scope of block, why that? i found solution in array documentation. wondered why used index function array when seems want iterate on array. can use array.each_slice without invoking index. index says following: http://ruby-doc.org/core-2.2.0/array.html#method-i-index returns index of first object in ary such object == obj. if block given instead of argument, returns index of first object block returns true. returns nil if no match found so code evaluates block , checks if result true . in first example puts returns n

go - Golang: CSS files are being sent with Content-Type: text/plain -

i have looked around , haven't found specific after. building api using go's standard library. when serving resource files, css files sent text/plain when wanting send text/css . the console throws info message @ me saying: resource interpreted stylesheet transferred mime type text/plain: "http://localhost:3000/css/app.css". main.go package main import ( "bufio" "log" "net/http" "os" "strings" "text/template" ) func main() { templates := populatetemplates() http.handlefunc("/", func(w http.responsewriter, req *http.request) { requestedfile := req.url.path[1:] template := templates.lookup(requestedfile + ".html") if template != nil { template.execute(w, nil) } else { w.writeheader(404) } }) http.handlefunc("/img/", server

javascript - Jquery : animate function not supports for 2D transform -

i using below code, not working. <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script> $(document).ready(function(){ $('#translate').mouseover(function(){ $(this).animate({'transform':'translate(50px,0px)'},'slow');// not working //$(this).css("transform","translate(50px,0px)"); //works fine }); }); </script> my jsfiddle : https://jsfiddle.net/jsnagaraj37/0xr3aqkm/5/ example : http://www.w3schools.com/css/css3_2dtransforms.asp - ( 2d rotate on mouseover)

selenium - is it possible to know if we are already inside a iframe -

in application of elements inside iframe . so pom (page object model) methods start switching frame , code performing actions..am able perform action switching frame. below example of code: public void method 1() { driver.switchto().frame(0); // code perform actions.... method 2(); driver.switchto().defaultcontent(); } public void method 2() { driver.switchto().frame(0); // code perform actions.... } as per above example, 2nd method called 1st method the driver frame method 1, when method 2 called again tried switch frame 0, hardcoded frame index, thought work fine (i.e driver on same frame), giving error "no such frame exception." is possible know current frame ? if know frame can add condition , decide switch or not switch, please guide. you achieve creating global variable current switched frame below approach :- string currentframe = null; //make currentframe global variable public void switchtoframe(string frame) {

React Native developer menu not responding -

when open developer menu (either cmd+d or cdm+ctr+z) none of buttons work. can't close developer menu. seem close after minute or so, don't think it's freezing or crashing, in app frozen out minute , have reset few times. i tried downgrading react , react-native 15.1 , 0.28 15.0.2 , 0.26, respectively. xcode date. i think had same problem few weeks ago. menus slow , and facebook login/logout took forever making me thing froze. turns out had accidentally turned on "slow animations" (cmd + t). check if it's not same problem. slow animations

machine learning - How should zero standard deviation in one of the features be handled in multi-variate gaussian distribution -

Image
i using multi-variate guassian distribution analyze abnormality. how training set looks 19-04-16 05:30:31 1 0 0 377816 305172 5567044 0 0 0 14 62 75 0 0 100 0 0 <date> <time> <--------------------------- ------- features ---------------------------> lets 1 of above features not change, remain zero. calculation mean = mu mu = mean(x)' calculating sigma2 as sigma2 = ((1/m) * (sum((x - mu') .^ 2)))' probability of individual feature in each data set calculated using standard gaussian formula as for particular feature, if values come out zero, mean (mu) zero. subsequently sigma2 zero. thereby when calculate probability through gaussian distribution, "device zero" problem. however, in test sets, feature value can fluctuate , term abnormality. how, should handled? dont want ignore such feature. so - problem occurs every time when have variable constant. approximating normal distri

c# - Accessing the first item in a CollectionViewSource containing multithreaded ObservableCollections -

as part of attempt fix my other problem regarding odd disabling , tried updating bound observablecollection instead of replacing whole thing every few seconds. gives error since event can't modify it. so, created multithreaded 1 based on this link . public class mtobservablecollection<t> : observablecollection<t> { public override event notifycollectionchangedeventhandler collectionchanged; protected override void oncollectionchanged(notifycollectionchangedeventargs e) { var eh = collectionchanged; if (eh != null) { dispatcher dispatcher = (from notifycollectionchangedeventhandler nh in eh.getinvocationlist() let dpo = nh.target dispatcherobject dpo != null select dpo.dispatcher).firstordefault(); if (dispatcher != null && dispatcher.checkaccess() == false) { dispatcher.invoke(dispatcherpriority.databin

javascript - Dynamic form using input type number and onchange event -

Image
i have form on picture, , want "numero de cuartos" field append same amount of inputs of "numero de personas adultas" , "numero de niños", additionally, "numero de niños" input needs append same amount of "edad de niños" inputs. i have this: <!--input type number of numero de cuartos--> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>numero de cuartos</label> <input required type="number" id="cuartos" name="cuartos" onchange="insertarcampos();" class="form-control" min="0"/> </div> </div> <!--place append--> <div id="contenidopersonas"> </div> <!-- form appended depending on number of "numero de cuartos" input --> <div id="rooms" style="display:none;"> <d

python - Cython memoryviews error: Invalid index for memoryview specified -

i'm trying implement standard quicksort in cython using memoryviews. here code: def quicksort_cython(double[:] l): _quicksort(l, 0, len(l) - 1) cdef void _quicksort(double[:] l, double start, double stop): cdef double pivot, left, right, tmp if stop - start > 0: pivot = l[start] left = start right = stop while left <= right: while l[left] < pivot: left += 1 while l[right] > pivot: right -= 1 if left <= right: tmp = l[left] l[left] = l[right] l[right] = tmp left += 1 right -= 1 _quicksort(l, start, right) _quicksort(l, left, stop) however, during compilation standard setup.py file , python setup.py build_ext --inplace command multiple errors regarding memoryview access: error compiling cython file: ----------------------------------------------------

java - Using LongAdder to calculate a max value for a statistical counter? -

we collect statistics using atomiclongs. users seeing contention on these , have suggested using longadder instead. see no way calculate maximum value doing atomic: atomiclong _current, _total, _max; ... void add(long delta) { long current = _current.addandget(delta); if (delta>0) { _total.addandget(delta); long max = _max.get(); while (current > max) { if (_max.compareandset(max, current)) break; max = _max.get(); } } so think can replace _total enough longadder , because _current.addandget(delta) not work longadder , nor can cas operation `_max' value. are there algorithms collecting such statistics based on longadder or similar scalable lock free constructs? actually, whiles i'm asking, our stats typically update 6 10 atomiclongs. if seeing contention anyway, possibly better grab lock , update 6 10 normal longs? you don't want longadder , longaccumulator here: want new longaccumulator(

google maps - Unable to get current location problems (android, permission) -

i've dev first application , make simple map activity, latitude , longitude 0. (when start activity cursor should set in device location). set permission in manifest , google-services.json file, still have error: e/gmpm: googleservice failed initialize, status: 10, missing expected resource: 'r.string.google_app_id' initializing google services. possible causes missing google-services.json or com.google.gms.google-services gradle plugin. i think why cant correct longitude , latitude. activity code: public class ********activity extends fragmentactivity implements onmapreadycallback,googleapiclient.connectioncallbacks, googleapiclient.onconnectionfailedlistener { private googlemap mmap; double latitude, longitude; googleapiclient mgoogleapiclient; location mlastlocation; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_locate_match); buildgoogleapiclient();