Posts

Showing posts from July, 2012

r - Warning when downcasting in Rcpp? -

i have rcpp function should take integervector input (as toint ). want use on vector of integers, on vector of doubles integers (e.g. 1:4 of type integer 1:4 + 1 of type double ). yet, when used on real floating point numbers (e.g. 1.5 ), return warning or error instead of silently rounding values (to make them integers). #include <rcpp.h> using namespace rcpp; // [[rcpp::export]] integervector toint(robject x) { return as<integervector>(x); } > toint(c(1.5, 2.4)) # warning [1] 1 2 > toint(1:2 + 1) # no need of warning [1] 2 3 rcpp sugar has need. here 1 possible implementation: #include <rcpp.h> using namespace rcpp; // [[rcpp::export]] integervector fprive(const robject & x) { numericvector nv(x); integervector iv(x); if (is_true(any(nv != numericvector(iv)))) warning("uh-oh"); return(iv); } /*** r fprive(c(1.5, 2)) fprive(c(1l, 2l)) */ its output follows: r> rcpp::sourcecpp('/tmp/f...

java - Add HttpCookie to CookieStore -

i need add few cookies authorize on website. cookies added successfully, missing when making request: import java.io.*; import java.net.*; public class main { static public void main(string[] args) throws exception { cookiemanager cookiemanager = new cookiemanager(null, cookiepolicy.accept_all); cookiestore cookiejar = cookiemanager.getcookiestore(); cookiehandler.setdefault(cookiemanager); httpcookie cookie = new httpcookie("name123", "value123"); cookiejar.add(new uri("http://httpbin.org"), cookie); httpurlconnection connection = (httpurlconnection) new url("http://httpbin.org/cookies").openconnection(); connection.setrequestmethod("get"); connection.connect(); bufferedreader in; stringbuilder response = new stringbuilder(); string inputline; in = new bufferedreader(new inputstreamreader(connection.getinputstream())); ...

r - conditional sum with dates in column names -

Image
want calculate conditional sum based on specified dates in r. sample df start_date = c("7/24/2017", "7/1/2017", "7/25/2017") end_date = c("7/27/2017", "7/4/2017", "7/28/2017") `7/23/2017` = c(1,5,1) `7/24/2017` = c(2,0,2) `7/25/2017` = c(0,0,10) `7/26/2017` = c(2,2,2) `7/27/2017` = c(0,0,0) df = data.frame(start_date,end_date,`7/23/2017`,`7/24/2017`,`7/25/2017`,`7/26/2017`,`7/27/2017`) in excel looks like: i want perform calculations specified in column h conditional sum of columns c through g based on dates specified in columns , b . apparently, excel allows columns dates not r. you achieve follows: # number of trailing columns without numeric values c = 2 # create separate vector dates dates = as.date(gsub("x","",tail(colnames(df),-c)),format="%m.%d.%y") # convert date columns in dataframe df$start_date = as.date(df$start_date,format="%m/%d/%y") df$end_d...

r - Panel data models: Duplicate couples error when there are no duplicate couples -

i have panel data set individual (dyad_id), integer, , time (year_month) date variable. try running following code: df.fe <- plm(deaths_civilians ~ deaths_a_lag + deaths_b_lag, data = rebel, index = c("dyad_id", "year_month"), model = "within", effect = "individual") but keep getting following error message: error in pdim.default(index[[1]], index[[2]]) : duplicate couples (id-time) in addition: warning messages: 1: in pdata.frame(data, index) : duplicate couples (id-time) in resulting pdata.frame find out which, use e.g. table(index(your_pdataframe), usena = "ifany") 2: in is.pbalanced.default(index[[1]], index[[2]]) : duplicate couples (id-time) 3: in is.pbalanced.default(index[[1]], index[[2]]) : duplicate couples (id-time) all previous answers question because have more 1 observation same id same time per...

python - IP address must be specified? -

heres code running in python 2.7 on windows 10 import os open('test.txt') f: line in f: response = os.system("ping -c 1" + line) if response == 0: print(line, "is up!") else: print(line, "is down!") the test.txt file contains random ip's, code runs when give out message the ip address must specified. problem don't know how within script. when use regular command promt , ping -c 1 google.com runs through reading text file above python script same google.com needs specified. q1: mean have ip specified , how it? q2: should write code in diffrent manner importing different module? import os open('test.txt') f: line in f: response = os.system("ping -c 1 " + line.strip()) if response == 0: print(line, "is up!") else: print(line, "is down!") strip newline off end of records file , add space in ping comm...

javascript - Return variable by socket client -

i have following question. how can return new value sockets, js file? app.js io.on('connection', function (socket) { socket.currentroomid = 0; socket.currentroomname = "loading..."; socket.currentroomowner = 1; socket.currentroomentry = 1.1; }); roommanager.js adapter.query(sql, function(err, rows) { rows.foreach( (row) => { socket.currentroomid = parseint(row.id); socket.currentroomname = row.room_name; socket.currentroomowner = row.room_owner; socket.currentroomentry = row.room_entry; }); }); greetings. you have emit , listen this, roommanager.js adapter.query(sql, function(err, rows) { rows.foreach( (row) => { // emit setcurrentdata row data socket.emit('setcurrentdata', { data: row }); }); }); app.js io.on('connection', function (socket) { socket.currentroomid = 0; socket.currentroomname = "loading..."; socket.cur...

r - Value label for variable -

i want attach value label variables (0 = "male" , 1 = "female") in data frame. i tried this: cb$gender <- factor(cb$gender, levels = c(0,1), labels = c("male", "female")) but result: [1] female male male male female female male female female male male male male male [15] male female female male female female male male male female male female male male [29] male female female male any idea? i don't quite know wrong splitting apart seemed work gender<-c("male","female","male","female") gender <- as.factor(gender) levels(gender)<-c(0,1) of course, pay attention fact used own made data. so try subset data first gender<-cb$gender and apply above. best of luck!

mongodb - Keyword item in monger vector is converted to string -

using monger, writing document contains vector keyword item collection like (monger.collection/insert-and-return db "test-coll" {:_id 1 :some-vector [:a-keyword]}) which returns expected {:_id 1, :some-vector [:a-keyword]} but if fetch particular document like (monger.collection/find-map-by-id db "test-coll" 1) the keyword has been changed string {:_id 1, :some-vector ["a-keyword"]} is expected behaviour , if why? this expected behaviour mongo database store doesn't support keywords; json . http://clojuremongodb.info/articles/inserting.html#serialization_of_clojure_data_types_to_dbobject_and_dblist you have manually convert values keywords using monger.conversion/from-db-object .

reactjs - React Hot Reload with React-hot-loader 3, React-router 4, and Webpack-hot-middleware -

i trying make react-hot-loader 3 work react-hot-loader 3, react-router 4 , webpack-hot-middleware (last version, 2.18.2). here server.js : const express = require('express'); const bodyparser = require('body-parser'); const cookiesmiddleware = require('universal-cookie-express'); /* eslint-disable import/no-extraneous-dependencies */ const webpack = require('webpack'); const webpackdevmiddleware = require('webpack-dev-middleware'); const webpackhotmiddleware = require('webpack-hot-middleware'); const webpackhotservermiddleware = require('webpack-hot-server-middleware'); /* eslint-enable import/no-extraneous-dependencies */ const clientconfig = require('./webpack.config.dev.client'); const serverconfig = require('./webpack.config.dev.server'); const port_number = process.env.port || 3000; const app = express(); app.use(bodyparser.urlencoded({ extended: true })); app.use(cookiesmiddleware()); app.use(expres...

python - Output error is 0x03BB7390 -

def fastmaxval(w, v, i, aw): global numcalls numcalls += 1 try: return m[(i, aw)] except keyerror: if == 0: if w[i] <= aw: m[(i, aw)] = v[i] return v[i] else: m[(i, aw)] = 0 return 0 without_i = fastmaxval(w, v, i-1, aw) if w[i] > aw: m[(i, aw)] = without_i return without_i else: with_i = v[i] + fastmaxval(w, v, i-1, aw - w[i]) res = max(with_i, without_i) m[(i, aw)] = res return res def maxval0(w, v, i, aw): m = {} return fastmaxval weights = [1, 1, 5, 5, 3, 3, 4, 4] vals = [15, 15, 10, 10, 9, 9, 5, 5] numcalls = 0 res = maxval0(weights, vals, len(vals) - 1, 8) print ('max val =', res, 'number of calls =', numcalls) the program 01knapsack problem. use decision tree solve problem. however, ran program , got following result. max val = function fastmax...

javascript - How to add a class to parent element using on click event listener? -

i'm trying add is-selected class each widget user clicks on. js , widgets have following structure: const widgets = document.getelementsbyclassname('widget'); array.from(widgets, wgt => wgt.addeventlistener('click', function(event) { // handlers here event.target.classlist.add('is-selected'); // more handlers here })); <div class="my-list"> <div class="widget" id="widget-#"> <div> <h1>title</h1> <h2>unique #</h2> </div> </div> </div> but whenever click on widget, is-selected added onto 1 of children (supposedly 1 clicked). doing wrong? want is-selected added widget , not of child elements.

python - Django CMS Auto-Publishing Draft -

i have django cms based site , thought publishing dates in menu answer question, unfortunately hitting snags. it appears publishing dates choice make page on or off. i have existing published page needs queued during week , have changes served @ midnight on weekend. page needs show current content until update happens , auto publish on weekend new content. is possible django-cms? know of add-ons may issue?

python 3.x - Error in last layer of neural network -

#10-fold split seed = 7 kfold = stratifiedkfold(n_splits=10, shuffle=true, random_state=seed) np.random.seed(seed) cvscores = [] act = 'relu' train, test in kfold.split(x, y): model = sequential() model.add(dense(43, input_shape=(8,))) model.add(activation(act)) model.add(dense(500)) model.add(activation(act)) #model.add(dropout(0.4)) model.add(dense(1000)) model.add(activation(act)) #model.add(dropout(0.4)) model.add(dense(1500)) model.add(activation(act)) #model.add(dropout(0.4)) model.add(dense(2)) model.add(activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) hist = model.fit(x[train], y[train], epochs=500, shuffle=true, batch_size=100, validation_data=(x[test], y[test]), v...

scala - how can I inject a keep-alive into a websocket handler in akka-http? -

i've written code communicate browser on websockets using akka-http 10.0.9. works nicely, except connection times out. although we're sending constant stream of data client, client isn't requesting long periods of time. i know solution inject keep-alive messages incoming websocket source, this: val s = source(list(data....)).keepalive(15.seconds, () => strict.textmessage("heart beat")) however, akka-http api calls flow handle connection: path("query") { parameter('session, 'package) { (session,packageid) => val sg = getgraphmanager(session) sg match { case left(error) => complete(statuscodes.badrequest -> tserror(msg=error)) case right(gm) => val tsflow = new tsflow(ksource, session) handlewebsocketmessages(flow.fromgraph(tsflow.flowgraph)) } } } consequently, never see incoming source, there...

shell - How to extract string between two regexes passed as variables to awk? -

i'm trying extract text in passage between 2 strings being saved in variables. wrong following way? input: module dft ( a, b, c, clk, z, test_si, test_se ); input [7:0] a; dft_dw_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) ); endmodule output: input [7:0] a; dft_dw_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) ); using following code: try="module dft"; awk '/$try/{flag=1; next} /endmodule/{flag=0} flag' dft_syn.v but doesn't recognize $try variable. you can use awk this: sm="module dft" em="endmodule" awk -v sm="$sm" -v em="$em" '$0 ~ em{p=0} p; $0 ~ sm{p=1}' file ...which property emits output: input [7:0] a; dft_dw_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) ); use -v var="value" pass command line variables shell awk set , reset variable p when encounter start or end tags

opencl - use of basic blocks in extracting features from llvm bitcode file -

i'm new llvm , clang , working on extracting opencl kernel features bitcode file generated using clang , libclc. info on this . this extracts number of operations in kernel file, first converted bitcode file , parsed. works if there no loops in kernel file or if number of iterations of loop less 25. iterations less 25, number of basic blocks detected 1 , correct number of operations detected, if more 25, number of basic blocks increase , number of operations counted wrong. i'm struggling understand basic blocks , what's going on here. the opencl kernel file use quite simple 1 kernel: __kernel void func(__global float *a, __global float *b, __global float *c){ int = get_global_id(0); float temp = a[i]; for(int i=0; i<26; i++){ temp *= b[i]; } c[i] = a[i] + temp; } would appreciate on this. thanks.

PHP return a mp4 video file -

i have following php script $file_name = 'videos/'.$_get['filename'].'.mp4'; $file_size = (string)(filesize($file_name)); header('content-type: video/mp4'); header('accept-ranges: bytes'); header('content-length: '.$file_size); header("content-disposition: inline;"); header("content-range: bytes .$file_size"); header("content-transfer-encoding: binary\n"); header('connection: close'); readfile($file_name); interestingly works serving video files not others recorded different bit-rate. furthermore, if video-files access directly chrome browser display video without problem. missing header? actually found out problem appache server. had increase memory in php.ini not problem bitrates size of files. memory_limit=1280m

raspberry pi - Can this Python script cause an R Pi freeze? -

the python script below seems cause raspberry pi 3 freeze after few hours when running in background. might file operations in while loop cause memory leak? i'm starting script via line below in /etc/rc.local (sleep 10;nohup python3.4 -u /home/pi/soundserve.py /home/pi/soundserve.output.txt 2>&1) & thanks in advance help! marc script: import os.path import pygame import time def getparam(name): f = open("/home/pi/"+name,"r") lines = f.readlines() f.close() if lines: f = open("/home/pi/"+name,"w") f.write("") f.close() print (lines[0]) return lines[0] else: return("none") def loopsound(n,name): global lines x in range(0, n): pygame.mixer.init() pygame.mixer.music.load("/home/pi/sounds/"+name+".mp3") pygame.mixer.music.play(0) while pygame.mixer.music.get_busy() == true...

Load balance with thrift and nginx -

i have following thrift server (socket), listening connections on specific host/port. final tprotocolfactory factory = new tbinaryprotocol.factory(); tnonblockingservertransport servertransport = new tnonblockingserversocket(serverport); final signatureservice.processor theprocessor = new signatureservice.processor(new signatureservicefacade()); tserver server = new thshaserver(new thshaserver.args(servertransport).processor(theprocessor). protocolfactory(factory). minworkerthreads(minthreads). maxworkerthreads(maxthreads)); and following client connection: clienttransport = new tframedtransport(new tsocket(signaturehost, signatureport)); final tprotocol theprotocol = new tbinaryprotocol(clienttransport); client = new signatureservice.client(theprotocol); clienttransport.open(); //call business specific method client.dostuff(param1, param2, param3); as can see in code above need provide host , port in order open co...

ui-bootstrap columns break in AngularJS -

i'm new angularjs, , guess default i'm new ui-bootstrap. however, i'm no stranger official vanilla bootstrap, i'm bit confused why columns not aligning. reason, size of columns behave rows unless add "pull-left" or "pull-right" classes, default breaks down. have no idea why it's behaving this, i've seen other bits of sample code not having problems columns in format. i've read docs find associated ui-bootstrap, there's no mention of regarding bootstrap grid. here's plunker: https://embed.plnkr.co/txdqsqhqlrmhrps0wyl9/ (i'm aware menu doesn't work here, that's fixed on local version of project.) and... should work, right? <div class="container-fluid"> <div class="row"> <div class="col-lg-4 col-md-4 col-4-sm col-4-xs" style="background-color: pink;">first col </div> <div class="col-lg-4 col-md-4 col-4-sm col-4-xs" style="ba...

javascript - WebPack replace vendor require call with global variable -

having trouble webpack. have vendor library (saying childvendor ), implements requirejs , commonjs compatibility, so, need require in webpack project var lib = require('./childvendor'); . childvendor library has dependency (saying supervendor ), , both of them requirejs- , commonjs-adapted, so, heading of childvendor.js looks like: (function(root, factory) { if (typeof define === 'function' && define.amd) { define(["supervendor"], factory); } else if (typeof exports === 'object') { module.exports = factory(require('supervendor')); } else { root.shepherd = factory(root.supervendor); } }(this, function(supervendor) { /*...*/ })); the main problem need include supervendor library globally on html-file manually (so, initialized window.supervendor), because should used other third-party libraries. to solve this, have tried webpack.provideplugin , like plugins: [ new webpack.provideplugin({ '...

excel - Split comma separated entries to new rows -

Image
i have data in sheet col col b 1 angry birds, gaming 2 nirvana,rock,band what want split comma separated entries in second column , insert in new rows below: col col b 1 angry birds 1 gaming 2 nirvana 2 rock 2 band i sure can done vba couldn't figure out myself. you better off using variant arrays rather cell loops - quicker code wise once data sets meaningful. thoug code longer :) this sample below dumps column c , d can see orginal data. change [c1].resize(lngcnt, 2).value2 = application.transpose(y) [a1].resize(lngcnt, 2).value2 = application.transpose(y) dump on original data [updated regexp remove blanks after , ie ", band" becomes "band"] sub slicendice() dim objregex object dim x dim y dim lngrow long dim lngcnt long dim temparr() string dim strarr set objregex = createobject("vbscript.regexp") objregex.pattern = "^\s+(.+?)$" 'define range analysed x = range([a1], c...

javascript - How to create grid and place elements randomly inside column? -

i have responsive grid created js , css. inside each column in grid want place elements (the red squares), squares should placed randomly , inside of columns. there 50 columns, let's want place 20 squares randomly inside columns squares can't overlap. how achieve in best way? js var grid = document.getelementbyid("grid"); for(var = 0; < 50; i++) { var square = document.createelement("div"); square.classname = 'square'; grid.appendchild(square); var child = document.createelement("div"); child.classname = 'child'; square.appendchild(child); } fiddle first add id each square, idea generate random number between 0 , 49 able access squares. each time add square, have store index check whether has been added. stop until 20 squares added. var field = document.getelementbyid("field"); (var = 0; < 50; i++) { var square = document.createelement("div"); squa...

java - How to detect screen orientation change? - JavaFX on Microsoft Surface -

i writing javafx application microsoft surface , looking way detect screen orientation change when rotating device portrait landscape , vice versa. current method using detect screen orientation follows: window.widthproperty().addlistener((obs, oldval, newval) -> { if((double) newval < window.getheight()) { setportraitmode(); } else { setlandscapemode(); } }); this method works fine manual window resizing. however, orientation change (device rotation) not trigger window resize event, method change layout not fire automatically. what proper way detect screen orientation change without listening resizing event? the solution issue check change in aspect ratio. condition used: if((double) newval < window.getheight() || ((double) newval/visualbounds.getheight() < 1.5)

python - Getting non-unique values from a django query -

i'm writing script want every occurrence of value, visited sites. first sites visited: sd = sessiondata.objects.filter(session_id__mlsession__platform__exact=int('2')) result = sd.values('last_page') i values i'm expecting: [{'last_page': 10l}, {'last_page': 4l}, {'last_page': 10l}] with that, want page 10l id have double weight of 4l, since it's appearing 2 times. i try values list: worddata = keyworddata.objects.filter(page_id__in=result) but unique values: [<keyworddata: 23>, <keyworddata: 24>, <keyworddata: 8>] where wanted outcome be: [<keyworddata: 23>, <keyworddata: 24>, <keyworddata: 8>, <keyworddata: 23>, <keyworddata: 24>] the way i've managed not unique list iterating through for-loop isn't option since data i'm dealing has millions of entries. is "__in" filter in django made return unique entries? there way can right output...

ios - jquery autocomplete on safari trigered twice -

we use jquery autocomplete on our website , works fine in ie or chrome, safari think triggers twice. this code autocomplete: $("#" + targetelementid).autocomplete({ minlength: 0, delay: 0, source: sourceurl }); and when try write in textbox on safari see call url value in textbox , call value wrote. , because of 2 calls, first 1 gets aborted , nice "abort (0) dismiss" text on page... idea why autocomplete triggered twice?

wso2is - wso2 - mapping claim to AD attribute error "values provided are incompatible for user" -

we trying configure wso2 identity server password policy authenticator addon. when try map claim uri http://wso2.org/claims/lastpasswordchangedtimestamp active directory attribute msds-userpasswordexpirytimecomputed, can see value being pulled in through "update profile" screen users. not able change value pressing update. receive error "error is: 1 or more attribute values provided incompatible user". has experienced when mapping claims? there step missing when setting these custom claims? thanks! tony

sql - drillthrough on text (not cell) -

just want know if possible, before drive myself insane in google-searches. i know how drillthrough rapport when user clicks on cell. if cell has multiple values, e.g. server-names (comma-seperated), , want pass servername user clicked? as see can pass values of whole cell or what? using reporting services 2012 r2 report builder 3.0. thanks i don't think can directly but... you create subreport accepts comma separated list of servers it's parameter. subreport split these separate cells , have action on cell take drill through report. done similar in past , it's work quite nicely. need make subreport nice , small it'll fit in existing cell. it wanted keep them on single line subreport have matrix column group grouped servername. won't compact comma separated list columns have wide enough fit longest name works. if need more i'll provide more more detailed solution going.

mongoose - What use in default tag for to get all mongodb values? -

how use in default tag values? const querydefaults = { 'tag': ??????????, 'sort': 'createdat', 'limit': 30, 'skip': 0, }; articleschema.statics.list = function ({tag, sort, limit, skip}) { console.log(tag); return this.find({'tags.label': tag}) .sort({sort: -1}) .skip(skip) .limit(limit) .exec(); };

php - to redirect a page according to the selected option value -

i want redirect page according selected option value if select 1 option tag redirect google.com page else selected option redirect on gmail.com page.i write these code redirect same value if select option solution these. <?php $package = isset($_get['package_select']); if ($package == 'one') { header("location: http://google.com"); } else if ($package == 'two') { header("location: http://youtube.com"); } ?> <html> <body> <form action="#" method="get" id="packageform" > <select name="package_select"> <option value="">select package</option> <option value="one">one listing</option> <option value="two">two listings</option> </select> <input id="submitbutton" type="submit" value="submit" /> </form> </body> </ht...

sql - When and why does the TRUNC(DATE, [FORMAT]) used in the real world -

i getting oracle database. came across trunc(date, [fmt]) function. not clear on except seems return beginning value of sort? can educate me on it? when or used @ work, or why might want use function? another thing useful time component of current day. use expression time: select sysdate - trunc(sysdate) todaystime dual because system date stored in decimal format (e.g. sysdate = 42651.2426897456 ) , integer value corresponds midnight, can use above statement decimal portion (e.g. todaystime = 0.2426897456 , or before 6 am). there may easier ways this, in applications has been easiest need work day's time component.

c# - Deserializing a string with escape characters using JsonConvert -

i have string this: "[ { \"someproperty\": 22 } ]" i'm trying deserialize list of known types: string toprocess = $@"[{text}]".replace("\n", ","); toprocess = regex.unescape(toprocess); list<knowntype> objectlist = jsonconvert.deserializeobject<list<knowntype>>(toprocess); however see it's attempting deserialize string containing \" characters, , it's failing cannot deserialize current json object . how deserialize this? you don't need string toprocess = $@"[{text}]".replace("\n", ","); string text = @"[ { \""someproperty\"": 22 } ]"; text = regex.unescape(text); var objectlist = jsonconvert.deserializeobject<list<knowntype>>(text); console.writeline(objectlist[0].someproperty);//22 this code works expected.

javascript - my form is not responmsive on ipad mini 4 view -

website screen shot on ipad mini4 view my form not responsive on view. have added view port , have set body size 100%. properties complete source of properties buying or renting rent sale --> sale  to rent </form>

css - Change hr style in HTML page -

this question has answer here: changing color of hr element 24 answers i tried changing <hr> tag css using: hr { color:whitesmoke} but doesn't affect html @ all. there way change horizontal line's color different color default 1 using css? performance purposes, don't want use img (horizontal line in color want max-width: 100% ) css rule. the appearance of <hr> in browser based on border styles , not dictated color property. therefore, try using border-color instead: hr { border: none; border-top: 1px solid whitesmoke; } <hr>

php - Error in search terms -

i help. site, when searching something, not match , says: notice: trying property of non-object in /customers/3/a/2/**********ia.com/httpd.www/wp-content/themes.../assets.php on line 741 on line is: if ( $is_product || is_post_type_archive( 'nitro-gallery' ) || is_singular( 'nitro-gallery' ) || ( is_single() && 'gallery' == $format ) || is_tax( 'gallery_cat' ) || has_shortcode( $post->post_content, 'product_page' ) ) { wp_enqueue_style( 'nivo-lightbox' ); wp_enqueue_script( 'nivo-lightbox' ); } add below line before if statement : global $post;

java - Why do i see empty files in Intent.ACTION_PICK? -

when start new intent this: intent intent = new intent(intent.action_pick, mediastore.images.media.external_content_uri); startactivityforresult(intent, request_code_load_main_image); i see empty files deleted before using method: public static void deleterecursive(documentfile fileordirectory) { if (fileordirectory.isdirectory()) { (documentfile child : fileordirectory.listfiles()) { deleterecursive(child); } } fileordirectory.delete(); } i can't see them in normal file manager, in intent. files dissapear when reboot phone. normal or should remove files way? thank you.

html - Flexbox - 5 columns in first row and 6 columns in second row -

Image
i have layout that's using flexbox , trying figure out how break 11 elements 2 rows. place i'm having issues breaking out elements 2 rows first row has 5 columns , second row has 6 columns 11 elements same width. this: here's have far: .container { display:flex; flex-wrap:wrap; justify-content:space-around; } .ele { flex-grow:1; height:100px; width:calc(100% * (1/6) - 2px); border:1px solid black; } <div class="container"> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> <div class="ele">element</div> ...

json - React "Cannot read property map of undefined" -

trying render errors coming ajax (axios) call in react app modal. i've tried many variations, end same error title. know have array of json objects, i'm not sure i'm going wrong. also, using redux in project, don't think that's issue, i'm noob react. in advance. the class in question: import react, {component} 'react'; import {modal, row, col, button} 'react-bootstrap'; class errormodal extends component { closemodal = () => { this.props.handlemodal('errormodal', false) } render() { var erroritems = this.props.data.error.map(function(item){ return ( <div>{item.property} {item.message}</div> ) }) return( <modal id="errormodal" bssize="lg" show={this.props.data.errormodal} onhide={this.closemodal}> <modal.header> <modal.title classname="text-center">validation errors</modal.title> ...

javascript - Access / process (nested) objects, arrays or JSON -

i have (nested) data structure containing objects , arrays. how can extract information, i.e. access specific or multiple values (or keys)? for example: var data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; how access name of second item in items ? preliminaries javascript has 1 data type can contain multiple values: object . array special form of object. (plain) objects have form {key: value, key: value, ...} arrays have form [value, value, ...] both arrays , objects expose key -> value structure. keys in array must numeric, whereas string can used key in objects. key-value pairs called "properties" . properties can accessed either using dot notation const value = obj.someproperty; or bracket notation , if property name not valid javascript identifier name [spec] , or name value of variable: // space not valid character in identifier names ...

postgresql - Postgres casting field before applying index -

i have table ~10mln rpws querying date constraint. there's column dt of type date ( format yyyy-mm-dd ). have created index on it: create index dt_dx on table table(dt) . run explain analyze on returned this: index scan using dt_idx on entities (cost=0.56..74175.26 rows=218 width=64) (actual time=0.069..0.069 rows=0 loops=1) index cond: ((dt)::text = '2017-07-26'::text) does mean postgres casting column's data text before comparing values query parameters?

c - Unable to find determinant using partial pivoting -

whats problem. executes doesnt show correct answer. gets compiled well. i've used calling function in many places. assumed matrix square , give input througgh terminal. ex=3 random 3x3 matrix value seems incorrect #include<stdio.h> #include<math.h> #include<stdlib.h> void row(int r1,int r2,int n,float a[n][n]){ int c; float temp[n][n]; for(c=0;c<n;c++){ temp[r1][c]=a[r1][c]; a[r1][c]=a[r2][c]; a[r2][c]=temp[r1][c]; } } void maximum(int i, int n,float a[n][n]){ int j; float max=fabs(a[i][i]); for(j=i+1;j<n;j++){ if(fabs(a[j][i])>max){ max=fabs(a[j][i]); row(i,j,n,a); } } } void op(int k, int n,float a[n][n]){ int i,j; float f;f for(i=1;i<n-1-k;i++){ f=-(a[k+i][k]/a[k][k]); for(j=0;j<n-1-k;j++){ a[k+i][k+j]=a[k+i][k+j]+f*(a[k][k+j]); } } } int main(){ int i,j,n; printf("enter order of matrix:"); scanf("%d",&n); float a[n][n]; for(i=0;i<n;i++){ for(j=0;j<n;j...

service - Cast Exception When Using Foreach on Microsoft.SharePoint.Client.ListCollection -

i have exhausted resources on issue. i'm hoping can assist me. i have agent polling microsoft o365 list collections in order walk through lists in given site. here code: microsoft.sharepoint.client = csom listcollection lists = csom.web.lists; clientcontext.load(lists); clientcontext.executequery(); try { foreach(csom.list list in lists { do.stuff() } } catch(excetion ex) { // excetpion in log @ csom.list after 'in lists' read. /*system.invalidcastexception: unable cast object of type 'system.collections.generic.dictionary`2[system.string,system.object]' type 'microsoft.sharepoint.client.list'.*/ } when in debug , tracing through code ex appears 'null', still excetion in debug logs when write ex.tostring() log file. using .net 4.6. code has worked before, during dev tests, wont work running in service. can't find namespace issues. o365 account amusing has 2fa disabled , has admin rights. thoughts helpful...

mysql - Sql vs nosql for a realtime messaging app? -

i creating messaging app. have users stored in mysql database , messages stored in google datastore nosql database. wondering drawbacks of having messages in mysql database since fetching message , user simultaneously. is there performance drawbacks? generally, different database usage cannot affect if backend architecture well-defined. database stores data manipulate. think authentication use mysql , store data in google datastore. performance drawbacks coming bandwidth of server. i propose must use same database store data, more stable , easy manage.

ios - How to detect when UIWebView starts loading when Webview is inside a Collection View cell? -

i loading collection view of cells containing uiwebview s. there's time gap between when uicollectionview 's activity indicator stops spinning , uiwebview loads. trying reference when loading starts (and when stops) in order add activity indicator ui. i'm not sure how here though since uiwebview in collectionviewcell , not collectionview , in other words can't use delegate methods , set myself delegate in collectionview s vdl? collectionviewcell code: import uikit import webkit class searchcollectionviewcell: uicollectionviewcell { @iboutlet weak var webview: uiwebview! @iboutlet weak var spinner: uiactivityindicatorview! func webviewdidstartload(_ webview: uiwebview) { print("we're loading") } } you need implement uiwebviewdelegate in cell , set cell delegate in method webviewdidstartload notified import uikit import webkit class searchcollectionviewcell: uicollectionviewcell { @iboutlet ...

android - How can I change the color of the selected spinner item using XML not Java? -

Image
i have android spinner , dropdown colors working ok can't change text color of selected item using xml, not java. i've tried think of. below code: <android.support.v7.widget.appcompatspinner android:layout_width="368dp" android:layout_height="wrap_content" android:entries="@array/test" style="@style/dropdown_text" tools:layout_editor_absolutey="0dp" tools:layout_editor_absolutex="8dp"></android.support.v7.widget.appcompatspinner> here things i've tried style: <style name="dropdown_text"> <item name="android:background">#000000</item> <item name="android:textcolor">#ffffff</item> <item name="android:textcolorprimary">#ffffff</item> <item name="android:textcolorsecondary">#ffffff</item> <item name="android:textappear...

python - Replacing only the captured group using re.sub and multiple replacements -

below simple example i've created. string = 'i love sleeping. love singing. love dancing.' pattern =re.compile(r'i love (\w+)\.') i want replace (\w+) portion re.sub. question in 2 parts: i want replace (\w+), without having resort groups capture rest of text. so don't want like: pattern =re.compile(r'(i) (love) (\w+)\.') re.sub(pattern, r'/1 /2 swimming', string) because may unreliable when working huge amounts of text , optional groups. second part: since have 3 matches, possible feed in list re.sub iterate through list each match , make sub accordingly. in words, want each item of list ['swimming, eating, jogging'] sync matches, (like method zip) , make substitution. so output should (even single total output fine: 'i love swimming' 'i love eating' 'i love jogging' you can use lookbehind , lookahead based regex , lambda function iterate through replacements words: >>...

c# - Page.Title set in child's Page_Init empty in parent's Page_PreRender -

there 2 files involved: childpage.aspx.cs class childpage : parentpage parentpage.cs class parentpage : system.web.ui.page childpage.aspx.cs has method protected page_init(object sender, eventargs e) { page.title = "abc"; } parentpage.cs has property , method public string mymodifiedtitle { { // adding 123 super important. return page.title + "123"; } } protected override void onprerender(eventargs e) { base.onprerender(e); // add open graph meta tag modified title. htmlmeta tag = new htmlmeta(); tag.attributes.add("property", "og:title"); tag.content = mymodifiedtitle; header.controls.add(tag); } page.title set "abc", og:title meta tag set "123" instead of "abc123". why page.title cleared out before onprerender?

ios - How to prevent status bar disappearing before UIImagePickerController covers the whole screen? -

Image
here's gif showing issue: when presenting uiimagepickercontroller this: self.present(imagepicker, animated: true, completion: nil) the status bar disappears before image picker full screen. the issue have status bar disappears in cloud of smoke, navigation bar jumps occupying void left status bar. when uiimagepickercontroller dismissed, status bar shows in rightful place. i'm not customizing status bar in way, default. is there way prevent uistatusbar disappearing, @ least until uiimagepickercontroller animation complete? if want status bar stay @ top of screen, should create custom window , apply animations manually. may help: var newwindow = uiwindow() let newcontroller = viewcontrollertopresent() var animationduration = 0.4 // or whatever want. // setting newcontroller root of new window. self.window.rootviewcontroller = newcontroller self.window.windowlevel = uiwindowlevelstatusbar self.window.backgroundcolor = .clear self.window.frame = cgr...

shell - How to convert the column to row data using bash script and create the csv file -

have data in text file (input data) want convert in csv file. how can create in below format in bash script? input data a=1 b=2 c=3 d=4 output data (csv file data) a,b,c,d 1,2,3,4 without array i=0 while ifs='=' read -r key value echo "$key" echo "$value" echo "$i" i=$((i+1)) done < "stats.txt" with array: i=0 j=0 while ifs='=' read -r key value echo arraykey[`$i`]="$key" echo arrayval[`$j`]="$value" i=`$((i+1))` j=`$((j+1))` done < status.txt in awk: $ awk ' # awk begin { fs="=";ofs=",";start=1 } # separators nr>=start && $0!="" { # define start line , remove empties # sub(/\r/,"",$nf) # uncomment remove windows line endings for(i=1;i<=nf;i++) # cols a[i]=a[i...

In R, extract files from a 7z files (ftp) and save -

i have 7.z file via ftp site: ftp://.../2009/file.7z extract(or unzip) files inside , save in directory "c:/myfiles" i can't this! help? edited i this, not work. zipf <- ftp://.../2009/file.7z outdir<-getwd() # define folder zip file should unzipped unzip(zipf,exdir=outdir) # unzip file warning message: in unzip(zipf, exdir = outdir) : error 1 in extracting zip file after this, directory empty.

No Brokers available when trying to connect to Kafka through Cloudera Data Science Workbench -

i trying implement github project ( https://github.com/tomatotomahto/cdh-sensor-analytics ) on our internal hadoop cluster via cloudera data science workbench. on running project on cloudera data science workbench, error "no brokers available" when trying connect kafka through python api kafkaproducer(bootstrap_servers='broker1:9092') [code can found in https://github.com/tomatotomahto/cdh-sensor-analytics/blob/master/datagenerator/kafkaconnection.py] . i have authenticated using kerberos. have tried giving broker node without port number, , list. but, nothing has worked far. below stack trace. nobrokersavailable: nobrokersavailable nobrokersavailable traceback (most recent call last) in engine ----> 1 dgen = datagenerator(config) /home/cdsw/datagenerator/datagenerator.py in __init__(self, config) 39 40 self._kudu = kuduconnection(self._config['kudu_master'], self._config['kudu_port'], spark) ...