Posts

Showing posts from July, 2011

c# - AspNet MVC - return RedirectToAction is not working with image upload (if file.SaveAs gets called) -

return redirecttoaction not working if imageupload.saveas(path); executed otherwise working (i mean if not select image not reach line imageupload.saveas(path); ). here code: [httppost] public actionresult createnewemployee(employee emplview, httppostedfilebase imageupload) { if (!modelstate.isvalid) { var mod = new personaldetailsviewmodel(emplview); return view("addemployee", mod); } if (imageupload != null && imageupload.contentlength > 0) { var filename = emplview.employeeid + "_" + path.getfilename(imageupload.filename); var path = path.combine(server.mappath("~/content/images/"), filename); imageupload.saveas(path); emplview.photograph = filename; } _dbcontext.employees.add(emplview); _dbcontext.savechanges(); return redirecttoaction("personaldetails", new { id = emplv

c# - Multiple UI threads for page (speed up slow individual controls) -

i writing kiosk style app in uwp (windows iot core), use on embedded devices (e.g. pi3, etc.). the device has several sensors, being output in real time various graphs/charts in single screen in app, i'm running performance problems. sensors being read in separate threads (using task.run() => {}), after analysis, doesn't seem cost cpu time @ all. seems updating graphs take time , isnt being distributed on cores, since there single ui thread. cpu usage doesnt past 25%, ui responsiveness gets slow. i tried several optimizations (e.g. reducing amount of data points, etc.), helps, not enough. maybe there faster chart components out there (currently using telerik uwp component), looking approach. so summary of question: there way have charts each render in separate ui threads (and distributed on other cores somewhat)? can't speak strictly uwp experience of wpf having multiple ui threads hassle should avoid if @ possible (not speak of limitations introduce)

python - How can I predict an image using a set of physically related images? -

Image
i'll explain question better figure: what i'd predict top left image 'depth' (actually map of real snow depths) using or of other images in figure. other images type of elevation-based product. can see figure, there strong link between landscape pattern , snow depth pattern. my hypothesis there mixture of other images can predict pattern in depth image @ least degree. i know i'll need extract scalar features images , perform type of regression. sort of algorithms or techniques might me started? thanks!

android - Toolbar transparent with navigation drawer -

Image
i trying make toolbar transparent navigation drawer. working fine til api<21, above api 21 toolbar not transparent. have added theme v-21 style folder well. adding theme image. <style name="apptheme.noactionbar"> <item name="windowactionbar">false</item> <item name="windownotitle">true</item> <item name="colorprimary">@android:color/transparent</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="drawerarrowstyle">@style/drawerarrowstyle</item> </style> <style name="drawerarrowstyle" parent="widget.appcompat.drawerarrowtoggle"> <item name="color">@color/colorprimary</item> </style> moreover, have created background selector toolbar in colors transparent xml <?xml version="1.0" encoding="utf-8"?> <android

Locking a file in Python -

i need lock file writing in python. accessed multiple python processes @ once. have found solutions online, fail purposes unix based or windows based. alright, ended going code wrote here, on website ( also available on github ). can use in following fashion: from filelock import filelock filelock("myfile.txt"): # work file locked print("lock acquired.")

xcode - Is it possible to edit IOS UI in text mode/non-gui -

i starting out learning ios development hobby in spare time - please patient if question seems dumb. but how edit ui without using xcode graphical user interface? there underlying xml definition android has in android studio? the reason ask if ever need change 1 dimension, means have manually go every single storyboard element, , change hand opposed editing them efficiently main config file dimens.xml if select storyboard in xcode, right click, , choose open -> source code, see xml. it's not simple work in form (in opinion), it's available.

javascript - Smooth jagged pixels -

Image
i've created pinch filter/effect on canvas using following algorithm: // iterate pixels (var = 0; < originalpixels.data.length; i+= 4) { // calculate pixel's position, distance, , angle var pixel = new pixel(affectedpixels, i, origin); // check if pixel in effect area if (pixel.dist < effectradius) { // initial method (flawed) // iterate original pixels , calculate new position of current pixel in affected pixels if (method.value == "org2aff") { var targetdist = ( pixel.dist - (1 - pixel.dist / effectradius) * (effectstrength * effectradius) ).clamp(0, effectradius); var targetpos = calcpos(origin, pixel.angle, targetdist); setpixel(affectedpixels, targetpos.x, targetpos.y, getpixel(originalpixels, pixel.pos.x, pixel.pos.y)); } else { // alternative method (better) // iterate affected pixels , calculate original position of current pixel in o

vb.net - Datagridview Row Post Paint infinite loop issue -

i programming in vb.net inside windows forms sql end. issue using 2 separate sql queries try , color multiple datagridview rows yellow, red, or green. problem each row, check row see if should yellow, , check same row see if should green. set rows red begin with. think problem if row set red, when change yellow, restarts the row post paint event. private sub datagridview1_rowpostpaint(sender object, e datagridviewrowpostpainteventargs) handles datagridview1.rowpostpaint datagridview1.defaultcellstyle.backcolor = color.red using conn1 new sqlconnection(connstring) conn1.open() using comm1 new sqlcommand("select * table1 orderno = @order , left(item, 10) = @part , [cut?] = 1", conn1) comm1.parameters .addwithvalue("@order", datagridview1.rows(e.rowindex).cells("orderno").value) .addwithvalue("@part", datagridview1.rows(e.rowindex).cells("part&qu

visual studio code - Typescript: Types are removed for a generic interface/function -

Image
i seem idiot, in vscode using typescript. when define interface, , attempt use interface in function intellisense seems removed. since it's little hard explain, added picture describe it. in first picture, can see able intellisense send function. in second (when attempt use it), can see both intellisense , type information has been removed. how resolve this? i believe running known typescript issue: https://github.com/microsoft/typescript/issues/14344 this bug of typescript 2.5. type checking should work properly, don't provide correct suggestions in case

networking - Understanding Android's Wifi State -

i need check if device connected wifi network. events occur confuse me. here steps reproduce: registerreceiver so registered receiver action wifimanager.network_state_changed_action) : private void registerreceiver() { log.v(tag, "registerreceiver"); final intentfilter intentfilter = new intentfilter(); intentfilter.addaction(wifimanager.network_state_changed_action); broadcastreceiver = new connectivitybroadcastreceiver(); context.registerreceiver(broadcastreceiver, intentfilter); } onreceive and how receive events. private class connectivitybroadcastreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { log.v("broadcast", "onreceive: " + intent.getaction()); final networkinfo networkinfo = intent.getparcelableextra(wifimanager.extra_network_info); if (networkinfo != null) { final networkinfo.state state = netw

c++ - How do I convert file path into a URI? -

how convert filepath "c:\whatever.txt" file uri "file:///c:/whatever.txt" qt? i've tried: qdebug() << qurl("c:/foo/baa/a.png").tolocalfile(); but output empty string.

php - Run when a post-type is saved run a function in wordpress -

i trying add_action in wordpress such when post of type 'fep_message' saved check '_fep_delete_by_' keys associated post_parent id , delete them wp_post_meta table. code built not working: add_action('publish_post', 'undelete_thread'); function undelete_thread($post_id, $post) { global $wpdb; if ($post->post_type = 'fep_message'){ $participants = fep_get_participants( $post->post_parent ); foreach( $participants $participant ) { $query ="select meta_id wp_postmeta post_id = %s , `meta_key` = '_fep_delete_by_%s'"; $queryp = $wpdb->prepare($query, array($post->post_parent, $participant)); if (!empty($queryp)) { delete_post_meta($queryp,'_fep_delete_by_' . $participant); } } } } what proper hook done? use save_post hook in wordpress. can find more info here https://codex.wordpress.org

c# - Adding System.IO.Compression Assembly Reference to Mono CentOS -

i trying make use of system.io.compression dll in c# application running on centos 7 mono 5.2.0.215. i able add assembly reference in visual studio, when try compile .cs, it's throwing error: program.cs(48,21): error cs0103: name `zipfile' not exist in current context compilation failed: 1 error(s), 0 warnings zipfile being class of assembly reference. any idea how make work? foreach(var file in piesziplist) { try { string extractionpath = file.substring(0, file.lastindexof('.') - 1); zipfile.extracttodirectory(file, extractionpath); piesunzippedlist.add(extractionpath); } catch(exception e) { console.writeline(e.tostring()); } }

c++11 - C++ Array type dependent on template type -

i have class has integral template parameter n . template<unsigned int n> class test { } now want have std::vector integral type small possible hold n bits. e.g. class test<8> { std::vector<uint8_t> data; } class test<9> { std::vector<uint16_t> data; } class test<10> { std::vector<uint16_t> data; } ... is there better way n=1 n=64 ? what using conditional? #include <vector> #include <cstdint> #include <iostream> #include <type_traits> template <std::size_t n> struct foo { static_assert( n < 65u, "foo 64 limit"); using vtype = typename std::conditional< (n < 9u), std::uint8_t, typename std::conditional< (n < 17u), std::uint16_t, typename std::conditional< (n < 33u), std::uint32_t, std::uint64_t >::type>::type>::type; std::vector<vtype> data; }; int main() { static_assert( 1u == sizeo

python 2.7 - Python27 to upload a file to google drive does not work when run as a windows scheduled task. Why? -

i had similar issue when python script called scheduled task on windows server tried access network shared drive. run idle on server not task. switched using local drive worked fine. script works if run console or idle on server , partially executes when run scheduled task. pulls data mssql database , creates local csv. works called task part upload file google drive not. have, did, before try other methods of calling outside of scheduled task ex powershell, bat file... same results. using google-api-python-client (1.6.2) , can't find anything. in advance! i found answer. in optional field of windows scheduled task action dialog, "start in" added path python scripts folder , script runs perfect.

python - Can't write to file but can write to text -

i created function convert() , turns pdf html , outputs html string. when : print(convert()) it works, when try write result file: f.write(convert()) i get: unicodeencodeerror: 'charmap' codec can't encode character '\ufb01' in position 978: character maps <undefined> in pycharm project encoder set utf-8, , have # -*- encoding: utf-8 -*- at beginning of file. ideas on why error? the python version makes difference. here's python 3.6: python 3.6.2 (v3.6.2:5fd33b5, jul 8 2017, 04:57:36) [msc v.1900 64 bit (amd64)] on win32 type "help", "copyright", "credits" or "license" more information. >>> print('\ufb01') fi >>> open('out.txt','w') f: ... f.write('\ufb01') ... traceback (most recent call last): file "<stdin>", line 2, in <module> file "d:\dev\python36\lib\encodings\cp1252.py", line 19, in encode

Youtube Video URL Access to X was denied -

i'm creating youtube downloader , have issues link. basically entered this song , program gave me this . i'm pretty sure missing in link because saying "access r6---sn-oxu8pnpvo-ua8z.googlevideo.com denied". i have tried other videos , every video giving access denied aswell. how can fix link? missing? ! youtube.cpp std::string decode_url(std::string str) { std::string ret; char ch; int i, ii, len = str.length(); (i=0; < len; i++){ if(str[i] != '%') { if(str[i] == '+') ret += ' '; else ret += str[i]; } else { sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii); ch = static_cast<char>(ii); ret += ch; = + 2; } } return ret; } youtube::youtube() { std::cout << "youtube url:"; std::cin >> youtube::link; youtube::id = youtube::link; youtube::get_id(); youtube::get_info(); youtube::read_video_

Script to backup and restore Azure Active Directory password hashes -

i looking powershell, azure cli, or other type of script or program allow me backup , restore user attributes including password hash . this azure cli command gives me of want, doesn't include password hashes: az ad user list --verbose the answer this question 3 years ago indicates can use powershell get-msoluser command, command seems return userprincipalname, displayname, , islicensed. not return password hash. this product quest indicates there way these password hashes. does know of way of user properties, including password hash using script or program? azure active directory not expose apis expose part of user's password, including password hash. i believe product referencing using "recycle bin" of azure active directory restore soft-deleted items. there tutorial on how through msol powershell module here . at no point gain access password hash of user through process.

ansible - Iterating over stdout -

i writing playbook locate string pattern in sequence of files. if run utility through command module generate 1 or more strings on stdout. run across number of systems run command with_items: - command: "findstring {{ item }}" with_items: - "string1" - "string2" register: found failed_when: found.rc >= 2 and iterate on result post process info: - name: print strings found debug: var: "{{ item }}" with_items: found.results is there equivalent loop.index can used "results" in task above? allow me {{ item[index].stdout }} strings generated. haven't been able find answer in official documentation thought post here see gurus think. if need iterate on every line commands, use: - debug: msg: "do smth line {{ item }}" with_items: "{{ found | json_query('results[].stdout_lines[]') }}" this take ever element found.results , every element every std

angular - Navigating to a DataURI in angular2 through a function -

i trying call function trigger file download in angular2. data stored in memory of angular2 app (not on server. based on i've read need create data uri here code this. downloaddata() { let data="bacon,goodness"; let uri = this._sanitizer.bypasssecuritytrusturl("data:text/csv;charset=utf-8," + encodeuricomponent(data)); this.download=uri; window.location.href = uri; } my issue cannot run command 'window.location.href=uri' it gives error 'safeurl' not assignable string there way navigate safeurl inside function i gave on using sanitize. way api allows use safeurl parameter [href]. apparently on purpose security. i now: window.location.href = "data:text/csv;charset=utf-8," + encodeuricomponent(data);

java - What is a NullPointerException, and how do I fix it? -

what null pointer exceptions ( java.lang.nullpointerexception ) , causes them? what methods/tools can used determine cause stop exception causing program terminate prematurely? when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int : int x; x = 10; in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x. but, when try declare reference type different happens. take following code: integer num; num = new integer(10); the first line declares variable named num , but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing". in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot

PHP - How to set a SMTP using office 365 -

since i've never done before , i'm looking educate myself on subject first. goal set smtp on php registration page can send verification email account activation. people work seems use office 365, if can adress me documentation on how set grateful. i'm doing own searches it's ask other sources ...

How to access libraries installed via NPM when running a Firebase app using 'firebase serve'? -

this index.html <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>welcome firebase hosting</title> <link type="text/css" href="node_modules/material-components-web/dist/material-components-web.css"> <script defer src="/__/firebase/4.3.1/firebase-app.js"></script> <script defer src="/__/firebase/4.3.1/firebase-auth.js"></script> <script defer src="/__/firebase/4.3.1/firebase-database.js"></script> <script defer src="/__/firebase/4.3.1/firebase-messaging.js"></script> <script defer src="/__/firebase/4.3.1/firebase-storage.js"></script> <script defer src="/__/firebase/init.js"></script> <script defer src="scripts/app.js"

javascript - Mixed Content warning on Chrome due to iframe src -

somewhere in code, on secure site, following snippet used: var iframe = document.createelement("iframe"); iframe.setattribute("src", "pugpig://onpageready"); document.documentelement.appendchild(iframe); iframe.parentnode.removechild(iframe); iframe = null; the iframe src attribute set here triggering callback it's causing chrome (version 54) complain "mixed content" src attribute interpreted non-https url on https:// domain , version of chrome not presenting users easy option allow mixed content load anyway (e.g. shield icon in address bar). changing chrome version / using different browser / starting chrome --allow-running-insecure-content switch not option reasons question is, there way make "pugpig://onpageready" part perceived https url? you can try this:- <meta http-equiv="content-security-policy" content="upgrade-insecure-requests" /> or <meta http-equiv="content-secu

node.js - Test dies after XHR Post request -

i testing web page need create teacher account , other treatment it. create teacher account created custom command sends post request service using js object , run other functions continue configuration of account. problem having once xhr command run, test hangs , doesn't else though have other steps after , don't have pauses in code. before used instead of hanging there test finish without running of following steps after xhr request , wouldn't give me errors. i think it's asyncronous nature of javascript , nightwatch js im not expert on insights on appreciated! here custom command: exports.command = function (client) { var stringutils = require("../utils/stringutils"); var data = client.globals; // var email = stringutils.createrandomstring() + '@mailinator.com'; var email = data.teacheraccountcreation.email; var userobj = {}; userobj["first-name"] = data.teacheraccountcreati

twitter bootstrap - Django Collectstatic Suspicious File operation -

i trying run collectstatic on heroku. when got error: remote: 'component ({})'.format(final_path, base_path)) remote: django.core.exceptions.suspiciousfileoperation: joined path (/tmp/build_4652acfe079723bc273763513a187201/fonts/glyphicons-halflings-regular.eot) located outside of base path component (/tmp/build_4652acfe079723bc273763513a187201/staticfiles) i thought perhaps had missed collectstatic on end, ran locally, , got exact same error. then went looking. found: /home/malikarumi/projects/aishah/jamf35/staticfiles/bootstrap/fonts/glyphicons-halflings-regular.eot and /home/malikarumi/projects/aishah/jamf35/static/bootstrap/fonts/glyphicons-halflings-regular.eot my settings: staticfiles_dirs = [ os.path.join(base_dir, 'static/bootstrap/fonts/'), there ticket out there, seems paths, , see nothing wrong paths, https://code.djangoproject.com/ticket/27201 1 deals files, , might closer issue, because has created tmp files, can't tell: ht

Include global sass with Angular 4 and webpack -

i have project built on angular 4 webpack hmr. not sure if matters using asp core 2 angular template. what trying have global/main scss file applied across components. wanted have scss file compile webpack delivered other styles in node_modules folder. i have tried implement no luck. main scss file named styles.global.scss , tried include following rule in webpack.config.js file { test: /\.global\.scss$/, exclude: /node_modules/, use: ['style-loader', 'css-loader', 'sass-loader'] } i don't errors when run application , run webpack command, however, not see styles being applied. resources in node_modules folder being applied @ least works. keep view encapsulation on angular components. prefer not have import main/global scss file each components scss file having include in each of stylesurl field in component.ts files. please let me know if need see additional code. in advance! edit: wanted include in question in case

visual c++ - Macro aliases for WPP tracing -

i started using wpp tracing in driver. defined macro dotracelevelmessage in order support log level (similar tracedrv sample code). tracing code looks this: dotracelevelmessage(trace_level_information, default_flag, "driver loaded"); this makes tracing lines little long, want use kind of aliases, example: #define log_info(msg,...) dotracelevelmessage(trace_level_information, default_flag, msg, __va_args__) so above code this: log_info("driver loaded"); i can't seem make work wpp. think wpp pre-processor runs before compiler pre-processor above macro doesn't expand expect. following compilation error: 1>test_driver.c(70): error c4013: 'wpp_call_test_driver_c70' undefined; assuming extern returning int 1>test_driver.c(70): error c2065: 'defualt_flag': undeclared identifier when use dotracelevelmessage macro, ok. idea how can define such aliases?

Error: 'complex' is not a member of 'std' compiling simple c++ program on linux with gcc -

here beginner's question. have following simple code trying compile on linux using gcc (v 4.8.5) #include <complex> int main(){ std::complex<double> hello; return 0; } the code above in file test.cpp. entering gcc test.cpp in terminal results in following output test.cpp: in function int main(): test.cpp:3:2: error: complex not member of std std::complex<double> hello; ^ test.cpp:3:15: error: expected primary-expression before double std::complex<double> hello; ^ test.cpp:3:15: error: expected ; before double any ideas?

ruby on rails - Skiping callbacks during my tests -

i have following callback before_action :forbid_logged_user, only: [:new, :create] prevent user access (new) login page , submit (create) log in credentials when he's logged in. def forbid_logged_user if logged_in? flash[:danger] = "you're logged in" redirect_to current_user end end however, have integration test execute post request (create) simulate log in. test "login without remembering" log_in_as(@user, remember_me: '1') log_in_as(@user, remember_me: '0') assert_empty cookies['remember_token'] end as can imagine, post request ignored because of call back, therefore returning false in test. indeed, test works when remove before_action callback create action, don't want to. how can skip callback during tests? thanks, you can check environment skip callback in test environment, example: if !rails.env.test? && logged_in? flash[:danger] = "you're logged in"

angularjs - Unable to get sparklines working with dynamic data in AngularJS4.x of SmartAdmin template -

Image
i using smartadmintemplate found in http://wrapbootstrap.com . trying have sparklines in dashboard showed in dashboard. sparkline works static data 2000,3000,1000,4000,5000 in place of sitetraffic given below ... <div class="col-xs-12 col-sm-5 col-md-5 col-lg-12" sasparklinecontainer> <ul id="sparks" class=""> <li class="sparks-info"> <h5> site traffic <span class="txt-color-blue">47,171</span></h5> <div class="sparkline txt-color-blue hidden-mobile hidden-md hidden-sm"> {{sitetraffic}} </div> </li> </ul> </div> issue when try use dynamic data in component.ts sitetraffic= [2000,4000,5000,1000,3000]; displays nothing ... please let me know how spraklines work dynamic data..

Tensorboard on Windows: 404 _traceDataUrl error -

on windows when execute: c:\python35\scripts\tensorboard --logdir=c:\users\kevin\documents\dev\deadpool\tensorflow-segnet\logs and web browse http://localhost:6006 first time redirected http://localhost:6006/[[_tracedataurl]] , command prompt messages: w0913 14:32:25.401402 reloader tf_logging.py:86] found more 1 graph event per run, or there metagraph containing graph_def, 1 or more graph events. overwriting graph newest event. w0913 14:32:25.417002 reloader tf_logging.py:86] found more 1 metagraph event per run. overwriting metagraph newest event. w0913 14:32:36.446222 thread-2 application.py:241] path /[[_tracedataurl]] not found, sending 404 when try http://localhost:6006 again, tensorboard takes long time presents 404 message again time displays blank web page. logs directory: checkpoint events.out.tfevents.1504911606.ltiip82 events.out.tfevents.1504912739.ltiip82 model.ckpt-194000.data-00000-of-00001 model.ckpt-194000.index model.ckpt-194000.meta why gettin

Tensorflow codes exceptionally exit when using thread in a loop -

i describe problem as possible receiving valuable answers. this, posting pseudocode below , pointing out further question: for _ in range(100): tf.reset_default_graph() read data queue build graph tf.session() sess: coord = tf.train.coordinator() threads = tf.train.start_queue_runners(sess, coord) try: in range(total_steps): if coord.should_stop(): work... except tf.errors.outofrangeerror: print('done') finally: coord.request_stop() coord.join(threads) in summary, put code in loop, , in each loop. graph reset, , use thread read data. i have used command "nohup python myscript.py >./log.txt &", while no exceptional or error messages in log.txt. now, thinking whether threads causing exceptional exit? not sure. many thanks!

Searching multiple fields in Django for loop -

this question has answer here: how test 1 variable against multiple values? 16 answers why `a == b or c or d` evaluate true? [duplicate] 1 answer i have couple form fields need format differently , trying use if statement find fields when rendered, doesn't seem working documentation suggests. i want format "country" , "state" differently, code doesn't i'm trying. {% field in customerfields %} {% if field.name != 'country' or 'state' %} {{ field.label.upper }} <div class="formrow"> {{ field }} </div> {% else %} <div class="formrow">

python - Efficient way to build a data set from fits image -

i have set of fits images: 32000 images resolution (256,256). dataset i've build matrix like, output shape (32000, 256*256). the simple solution for loop, samething like: #file_names list of paths samples=[] file_name in file_names: hdu=pyfits.open(file_name) samples.append(hdu[0].data.flatten()) hdu.close() #then can use numpy.concatenate have numpy ndarray this solution very, slow. best solution build big data set? this isn't intended main answer, felt long comment , relevant. i not python expert means, believe there few things can without adjusting code. python syntactical language , implemented in different ways. traditional implementation cpython, download website. however, there other implementations (see here ). long story short, try pypy runs faster "memory-hungry python" such yours. here nice reddit post advantages of each, use pypy, , more experienced me optimize code. additionally, have never used numpy post suggest

rxjs5 - RxJS 5, converting an observable to a BehaviorSubject(?) -

i have parent observable that, once has subscriber, lookup , emit single value, complete. i'd convert observable (or behavior subject or whatever works) following: once has @ least 1 subscriber, gets result parent observable (once). emits value of subscribers, , emits single value future subscribers, when subscribe. should continue behavior if subscriber count drops zero. it seems should easy. here didn't work: thevalue$: observable<boolean> = parent$ .take(1) .share() other things didn't work: publishreplay() , publish() . worked better: thevalue$ = new behaviorsubject<boolean>(false); parent$ .take(1) .subscribe( value => thevalue$.next(value)); there problem approach, though: parent$ subscribed before thevalue$ gets first subscriber. is there better way handle this? sharereplay should want: import 'rxjs/add/operator/sharereplay'; ... thevalue$: observable<boolean> = parent$.sharereplay(1); sharereplay add

ios - Loading UITableViewCells that are not in display -

i'm having issue uitableviewcells not loading unless scroll down reveal them, problem each custom cell has toggle switch in them , if it's on add cell's value calculation, calculation incomplete since missing of cells did not load (and load once scroll down). makes sense. on bluetooth connection app, , it's supposed refresh table every time receives new values. here's code load cells: //table loading / reloading functions: func numberofsections(in tableview: uitableview) -> int { return 1 } func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int{ return temperaturereadingarray.count //should return 1 or 9 depending on array received } func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecell(withidentifier: temperaturereading) as! temperaturereading cell.channellabel.text = channelnames[indexpath.row] cell.readingla

Weird SVG mask behaviour on Chrome -

i encountered weird behavior thought simple svg mask: <svg width="400" height="400"> <defs> <mask id="mask" x="0" y="0" width="400" height="400"> <rect x="0" y="100" width="400" height="100" fill="#fff"></rect> </mask> </defs> <g mask="url(#mask)"> <rect fill="#bbb" x="0" y="0" width="400" height="400"></rect> </g> </svg> on chrome renders 3 gray rectangles (two of reacts scroll), while believe should 1 rectangle (firefox , edge renders so) corresponding image (left: edge/firefox | right: chrome) codepen: https://codepen.io/zworek/pen/ggbgpl am defining wrong here or purely chrome's bug? if kind of bug: there workarounds? my chrome version 60.0.3112.113 x64 this bug seems hav

java - Is it possible to automate captcha code using selenium webdriver? -

i'm automating irctc site hands on selenium webdriver. it asking me captcha code along username , password. there anyway automate captcha code? you failed understand captcha is; from wikipedia : a captcha (a backronym "completely automated public turing test tell computers , humans apart") type of challenge-response test used in computing determine whether or not user human. as mentioned in other answers , comments, there several possible attacks defeat this. can links several other options same wikipedia page . note of these more of proof-of-concept, rather out-of-the-box solution. since tagged question selenium, possible may using in environment control , such test environment @ work. in such scenario, easiest solution ask developers introduce "test" flag non-production deployments. when flag active, predefined phrase pass captcha testing purposes. however, should still have full-pass test, turned on if real production.

How to pause for a measured time in Elm? -

i attempting create simple web page using elm involves displaying image measured amount of time, such second or millisecond. is there way "pause" in elm? display, pause, , remove image achieve effect. i noticed clock example appears update every time machine's clock triggers new second, whereas looking can pause update set time (such fraction of second) after starting time. you can create new msg value triggers url (of image) changes. , create subscription via timer.every . can add flag in model indicate whether keep updating image or not, if that's want. example: subscriptions : model -> sub msg subscriptions model = if model.keepupdating time.every (3 * second) (\x -> updateimage) else sub.none update : msg -> model -> ( model, cmd msg ) update msg model = case msg of updateimage -> ( { model | image_url = "http://to_new_image/..." }, cmd.none )

ember.js - Passing contextual components to child template though an outlet in EmberJS -

i've been having fun embers contextual components . i'd find out if there clean way have component "contexts" shared child templates through outlet. e.g. {{outlet foo='bar'}} in example below ht-window component controls 3 column layout; list, details & actions. navigate between users/view & users/edit last 2 columns should update. the functionality of these components requires pane components have reference parent window component. i know use service this, if possible using contextual components seems cleaner. here's code far, edit.hbs , view.hbs not have access window not work. in app/templates/users.hbs {{#ht-window |window|}} {{#window.header}} ...navigation {{/window.header}} {{#window.pane}} ...list {{/window.pane}} {{outlet window=window}} {{/ht-window}} in app/templates/users/view.hbs {{#window.pane}} ...view {{/window.pane}} {{#window.pane}} ...actions {{/window.pane}} in app/templates/

python - What's wrong with this async aiohttp code? -

for following code using aiohttp: async def send(self, msg, url): async aiohttp.clientsession() session: async session.post(url, data=msg) response: self._msg = response.read() async def recv(self): return await self._msg it works... of time, (frequently, actually) results in various exceptions - truncated responses, or connection being closed exception. by contrast, following works perfectly: async def send(self, msg, url): async aiohttp.clientsession() session: async session.post(url, data=msg) response: self._msg = await response.read() async def recv(self): return self._msg i know why, second version technically incorrect purposes , need fix it. (it incorrect because recv function might called before response has been read) with context manager, runs code before , after statements within it's block, bookkeeping usually. meaning, first recv function awaits on future references closed connection, o

C# save a DataGridView Directory Comparison to CSV with special filename for C# Windows App -

i created button allow user create csv based on directory comparison. compiled code, , looks ok. go run program, however, , "access denied" error. private void button1_click_1(object sender, eventargs e) { string csv = string.empty; folderbrowserdialog fbd = new folderbrowserdialog(); using (var sfd = new savefiledialog()) if (fbd.showdialog() == system.windows.forms.dialogresult.ok) { string folderpath = fbd.selectedpath; string filename = "dir_" + (datetime.now.toshortdatestring()) + ".csv"; file.writealltext(folderpath + "dir_" + (datetime.now.toshortdatestring()) + ".csv", csv); } is there way save datagridview csv file extension give in filename string? do have permission write on folder? try use file.writealllines : file.writealllines(folderpath + "dir_" + (datetime.now.toshortdatestring()) + ".csv"

Swift + Firebase: Date Cannot convert value of type '[AnyHashable : Any]' to expected argument type 'String' -

i trying use firebase server time create child node of uid date can store messages in time order. this how trying it: dbrootref.child(uid).child(servervalue.timestamp()) however error: cannot convert value of type '[anyhashable : any]' expected argument type 'string' this want uid -- 1505348420 ---- "message" : "here message time want save" any ideas how child node date in firebase?

julia lang - Different results for loops with decrement and increment -

i have come realize don't same result between iterations increment , decrement. slight difference when math expression n + (1/(i^4)) iterates , adds new value on 75+ times, being i number of iteration. under 75 iterations result each loop remains same. ideas of why happening? code running: y=0 in 1:75 y = y + (1/(i^4)) end print("final y value: ",y,"\n") x=0 in 75:-1:1 x = x + (1/(i^4)) end print("final x value: ",x,"\n") and got x , y: final y value: 1.0823224592496965 final x value: 1.0823224592496967 but if change loop limits 74 or less (74 in following example), same result both loop: final y value: 1.0823224276447583 final x value: 1.0823224276447583 that because of floating point rounding errors take place during addition, because of precision of float64. can use arbitrary precision floats (i.e. bigfloats) overcome issue if rounding errors important. y = bigfloat(0) #0.000000000000000000000000000000

mysql - script that checks and compares table structures from different databases and sends alarm if different -

just wanted ask, want create script check table structures 2 databases ( must same). if different send email alert. i have option of doing mysqldump , doing diff , databases huge. i've read maatkit, , other tools i'm not sure how proceed . can give direction , best tool. i'd recommend using mysqldbcompare mysql utilities. it's official part of mysql product line. can diff structure or data or both. read documentation details these options. you mention maatkit, toolkit replaced years ago percona toolkit (same people working on , same code, changed name). since then, mysql utilities have duplicated of tools in percona toolkit.

swift - SceneKit - how to get animations for a .dae model? -

ok, working arkit , scene kit here , having trouble looking @ other questions dealing scene kit trying have model in .dae format , load in various animations have model run - we're in ios11 seems solutions don't work. here how model - base .dae scene no animations applied. importing these maya - var modelscene = scnscene(named: "art.scnassets/ryderfinal3.dae")! if let d = modelscene.rootnode.childnodes.first { thedude.node = d thedude.setupnode() } then in dude class: func setupnode() { node.scale = scnvector3(x: modifier, y: modifier, z: modifier) center(node: node) } the scaling , centering of axes needing because model not @ origin. worked. different scene called "idle.dae" try load in animation later run on model: func animationfromscenenamed(path: string) -> caanimation? { let scene = scnscene(named: path) var animation:caanimation? scene?.rootnode.enumeratechildnodes({ child, stop in

c++ - Cannot sort command line arguments using strcpy -

i new c/c++ , learning command line arguments. trying sort command line arguments using strcpy, giving me bad output. e.g. i/p : o/p : ami i can me on doing wrong here ? please note: running program argc=3 , running code inputs (which sorted) listed in example above. have removed loops debugging. #include "iostream" #include "cstdlib" #include "cstring" using namespace std; int main (int argc, char **argv) { char temp[100]; //sorting command line arguments if(strcmp(argv[1],argv[2])>0) { strcpy(temp,argv[1]); strcpy(argv[1],argv[2]); strcpy(argv[2],temp); } cout<<argv[1]<<endl; cout<<argv[2]<<endl; return 0; } consider memory layout. when run $ ./a.out am , when program starts: a . o u t \0 \0 m \0 ^ ^ ^ argv[0] argv[1] argv[2] the write argv[1] in swapping procedure change this: a .

c++ - Boost.spirit (x3, boost 1.64): how to implement this recursive rule correctly, is it possible? -

the question easy formulate. have recursive rule, not know synthesized attribute type rule, have few more questions inner workings. it looks me return type variant<tuple<return_type_of_a, seq>, tuple<return_type_of_b, seq>> seq recursive rule , a , b terminals: rule<class myrule, ??> seq = >> seq | b >> seq; the following not accepted because rule recursive, , cannot figure out return type exactly: rule<class myrule, decltype (a>> seq | b >> seq)> seq = >> seq | b >> seq; must know return type of recursive rule? it looks there must type of type nesting, natural recursion, if not flattened impossible calculate return type @ compile-time. how type recursive rule calculated @ compile-time? there kind of flattening? what should synthesized of rule above? would refactor rule to: rule<class myrule, ??> seq = (a | b) >> seq; thanks help. about seq = >> seq | b >> s

winforms - C# Check if data exists in List View Windows Form -

what want getting set of data group identifier, this: 123456 123456 456789 456789 456789 135790 to name quantity 123456 2 456789 3 135790 1 what i've done far: foreach(string name in itemlist) //itemlist = 123456,123456... mentioned above { var listitems= lvtest.items.cast<listviewitem>; bool exists = listitems.where(item => item.text == name).any(); // check if item name exists in list view if (!exists) { listviewitem lvitem = new listviewitem(new string[] { name, "1" }); lvtest.items.add(lvitem); } else { listviewitem lvitem = lvtest.items.cast<listviewitem>.where(item => item.text == name).firstordefault(); int count = (int)lvitem.subitems[1].text; count = count + 1; lvitem.subitems[1].text = count.tostring(); } } but won't work due issue "cannot assign method group implicitly-typed local variable" in line of var listite

javascript - Custom HTML Tag -

i have 2 questions concerning custom html tags. when created custom html tag , tried custom html file (code below) in different browsers. wondering if can test in older versions of safari , see compatibility custom html tags. and need javascript stuff mentioned in these article? https://www.html5rocks.com/en/tutorials/webcomponents/customelements/ https://developers.google.com/web/fundamentals/architecture/building-components/customelements <style> custom-tag { background-color: red; padding: 100px; } </style> <custom-tag>this custom tag.</custom-tag> <script> alert(document.getelementsbytagname('custom-tag')[0].tagname) </script> the results of code in internet explorer... ie6 = js works not css ie7 = js works not css ie8 = js works not css ie9 = js works not css ie10+ = works according caniuse , custom elements supported in: chrome 33 , onwards opera 20 , onwards android 4.4.4 , onwards

ios - How long does URLSession dataTask cache my server's data? -

this first app , i'm wondering if have made mistake regards using urlsession.shared datatask because not seeing app new data updated. see new json instantly in browser when refresh, but, app apparently not see it. will ever new json data server without uninstalling app? there some similar question topics, such how disable caching nsurlsessiontask however, not want disable caching. instead, want know how default object behaves in scenario - how long going cache it? if indeed answer forever, or until update or reinstall app, want know how reproduce normal browser based cache behavior, using if-modified-since header, not question here. i call download() function below gratuitously after launch sequence. func download(_ ch: @escaping (_ data: data?, _ respone: urlresponse?, _ error: error?) -> (), completionhandler: @escaping (_ sessionerror: error?) -> ()) { let myfileurl: url? = getfileurl(filename: self.getfilename(self.jsontestname)) let mytesturl =