Posts

Showing posts from August, 2014

sql server - Formatting query of TSQL -

i have following tsql query attempting run results , attach email having issues formatting of query, can advise why not working? declare @query_attachment_filename varchar(100) = 'reconciliation-count-ending-' + convert(varchar(10), getdate(), 112) + '.csv'; exec msdb.dbo.sp_send_dbmail @profile_name = 'support', @recipients = 'johnpaul@energy.co.uk;martin@energy.co.uk', @subject = 'reconciliation count', @query = n'set ansi_warnings off;set nocount on;select * ( select a.new_messagetypecode new_marketmessagein createdon between dateadd(day, –1, getdate()) , getdate() ) src pivot (count(new_messagetypecode ) new_messagetypecode in ([014r], [101], [101p], [101r], [102], [102p], [102r], [105], [105l], [106d], [106e], [110], [111], [111a], [111l], [111r], [112], [112r], [112w], [114], [115], [115r], [116], [116a], [116n], [116r],[117d],[117r], [122], [122r], [130d], [130r], [131], [137r], [261], [300], [300s], [300w], [301], [...

python - Type hint that a function never returns -

python's new type hinting feature allows type hint function returns none ... def some_func() -> none: pass ... or leave return type unspecified, pep dictates should cause static analysers assume return type possible: any function without annotations should treated having general type possible however, how should type hint function never return? instance, correct way type hint return value of these 2 functions? def loop_forever(): while true: print('this function never returns because loops forever') def always_explode(): raise exception('this function never returns because raises') neither specifying -> none nor leaving return type unspecified seems correct in these cases. even though “ pep 484 — type hints ” standard mentioned both in question , in answer yet nobody quotes section: the noreturn type covers question. quote: the typing module provides special type noreturn annotate functions never r...

How to Trim a String in Swift based on a character -

i trim string, can extract filename, preceded "_" (underscore). best way this? https://s3.amazonaws.com/brewerydbapi/beer/rxi2ct/upload_ffapfl-icon.png i result ffapfl-icon.png you can use string method rangeofstring: let link = "https://s3.amazonaws.com/brewerydbapi/beer/rxi2ct/upload_ffapfl-icon.png" if let range = link.rangeofstring("_") { let filename = link.substringfromindex(range.endindex) print(filename) // "ffapfl-icon.png\n" } xcode 8 beta 3 • swift 3 if let range = link.range(of: "_") { let filename = link.substring(from: range.upperbound) print(filename) // "ffapfl-icon.png\n" }

rxjs - Angular 2 equivalent of Ember.Computed('Prop1','Prop2'...'prop n') -

i trying port ember application angular 2 , failed see how can create computed properties--properties observing other properties changes , reacting in angular 2. [(myvar)] && onmyvarchange= new eventmitter(); observes changes self , react. any help/directions great. update : solved using answer @nazim used typescript properties ts (compoment.ts) private _isvalid: boolean; public isvalid(): boolean { return this._isvalid; } public set isvalid(v: boolean) { this._isvalid = v; } // read property private _show: boolean; public show(): boolean { return this._isvalid; } template (component.html) <h2 *ngif="show">show me</h2> from understand, angular 2 uses native es2015 computed properties. ex. define person component: export class personcomponent { firstname: string; lastname: string; fullname() { return `${this.firstname} ${this.lastname}`; } } and use ngmodel bin...

ubuntu - MongoDB Failed: can't create ActualPath object from path dump: stat dump: no such file or directory -

i have bunch of mongo databases need restore. used mongodump backup directories, include collections inside of them. this: |- mydir |-- db1 |--- collection1 |--- collections2 |-- db2 |--- collection1 |--- collections2 i cd mydir , mongorestore , following error: 2016-07-25t10:41:12.378-0400 using default 'dump' directory 2016-07-25t10:41:12.378-0400 failed: can't create actualpath object path dump: stat dump: no such file or directory then try restore specific database this: mongorestore db2 , following errors: 2016-07-25t10:47:04.413-0400 building list of dbs , collections restore db2 dir 2016-07-25t10:47:04.413-0400 don't know file "db2/collection1.bson", skipping... 2016-07-25t10:47:04.413-0400 don't know file "db2/collection1.metadata.json", skipping..."db2/collection2.bson", skipping... 2016-07-25t10:47:04.413-0400 don't know file "db2/collection2.metadata.json", skipping... 2016-0...

"Undefined reference to"-error / static member var in C++/Qt -

first of all, i'm not familiar c++/qt , tried it, in c# ... have problems pointers.. the story: use qserialport read , write on serial 232 port. of course, there should 1 instance, otherwise there access errors. idea define static member variable hold object. the problem: error "undefined reference serialmanager::obj " the source code: serialmanager.h #include <qserialport> class serialmanager { public: static qserialport* getobj(); private: static qserialport* obj; } serialmanager.cpp #include "serialmanager.h" qserialport *obj = new qserialport(); qserialport* serialmanager::getobj() { if(!obj->isopen()) { obj->setportname("/dev/ttyo1"); //error line obj->setbaudrate(qserialport::baud57600); //and on... } return obj; } in header file, declaring serialmanager::obj in header file. in implementation file, defining obj , not serialmanager::obj . the fix cha...

How to loop through attributes in rails controller params -

i have has_many relationship , want loop field on each of items link main model (ingredients on recipe). im trying in before_filter can parse users input correctly want. how can set loop params want the request parameters in rails accessible via params hash. can loop on hash using iterator. params.each |k,v| puts "#{k}: #{v}" end as parsing user's input, not in before_filter method. gave example below of converting input such "1 1/2" 1.5. try this: ingredient.rb: # amount :decimal (assuming column exists on ingredients table) def humanized_amount amount.humanize! end def humanized_amount=(value) amount = cast_humanized_value_to_decimal(value) end then use humanized_amount attribute form input. suggestion. there's not right answer.

how to write/read vector of A Class safely with fstream in C++? -

recently got annoying bug read data vector of class.i have written simple program test fstream in main function , worked without problem. while coding book class in book.h , implement class in book.cpp,then attempted write vector of book file ofstream,no bug occurred. //write data ofstream output("book.bat",ios::binary); if( !output ){ exit(-1); } output.write(reinterpret_cast<char*>(&books[0]),sizeof(book)*books.size()); output.close(); //read data ifstream input("book.bat",ios::binary); if( !input ){ exit(-1); } book tmp; while( input.read(reinterpret_cast<char*>(&tmp),sizeof(book)) ) { books.push_back(tmp); } input.close(); unfortunately when program run step of readding file vector,the bug occurred.having searched hours, got nothing deal bug. help. for point of view of class type encapsulates interna...

c# - Asp:Label that determined by dropdownlistbox not working properly -

this working other day, not sure happened isn't , cant figure out. label give me 1 item out of around 20(give or take) distinct items. no matter select in drop down list, gives me same value on label. html: <td> <asp:dropdownlist id="ddlcompanycode" runat="server" cssclass="dropdown" autopostback="true" onselectedindexchanged="ddlcompanycode_selectedindexchanged" width="139px" datasourceid="companycodeds" datatextfield="companycode" datavaluefield="companycode"></asp:dropdownlist> <asp:requiredfieldvalidator id="requiredfieldvalidator2" runat="server" controltovalidate="ddlcompanycode" display="dynamic" errormessage="*please select drop down list item." forecolor="#cc0000" validationgroup="submit"></asp:requiredfieldvalidator> ...

vba - Extracting attachment from an attachment -

i have macros save attachments in specific folder. works following code: atmt.saveasfile some emails contain email attachment contain desired file. how extract such second-level attachment? update: thank suggestions. following works: for each atmt in zmsg.attachments 'loop through attachments atmt.saveasfile destpath & atmt.filename set zmsg2 = application.createitemfromtemplate(destpath & atmt.filename) each atmt2 in zmsg2.attachments atmt2.saveasfile destpath & atmt2.filename next set zmsg2 = nothing kill destpath & atmt.filename next

android - What could cause file path NULL only on Galaxy S4 5.0.1? -

a file being caught camera. don't use intent , save file tempfile object. code private static final int image_capture = 1002; //class-wide private string mcurrentphotopath; //class-wide //... file photofile = createimagefile(); uri uri = uri.fromfile(photofile); intent.putextra(mediastore.extra_output, uri); startactivityforresult(intent, image_capture); //... private file createimagefile() throws ioexception { imagename = mcodecontent + "_" + integer.tostring(randomnumber) + ".png"; file storagedir = environment.getexternalstoragepublicdirectory(environment.directory_pictures); file image = file.createtempfile(imagename, ".png", storagedir); mcurrentphotopath = image.getabsolutefile().getpath(); mimagenamelist.add(imagename); return image; } but moment, variable mcurrentphotopath not null. however, after user takes image, variable mcurrentphotopath becomes null in onactivityresult creates...

angular - how to reload/refresh the component view forcefully? -

in application have json object hardcoded. values bound input controls in view. if changes values of json object during events, changes values not getting reflected in view/input controls? how forcefully reload/refresh view? please component below. in values have assigned inside constructor gets reflected in view during load of component. based on events on parent component, method loadextractorqueuedetails() called , same variable this.sampledata being reset other values. ideally expect these values reflected in view? doesn't seem happen? why not happening? how reload/refresh views ? import { component, input, oninit } '@angular/core' import { form_directives } '@angular/common'; @component({ selector: 'extractorqueuedetails', directives: [form_directives], providers: [cachedataservice, http_providers], templateurl: './html/admin/extractorqueuedetails.html' }) export class extractorqueuedetails { resultdata: extracto...

Javafx Not Editable Combobox prompt text style with CSS -

i'm trying have not editable combobox having prompt text fill text color bit lighter actual text fill color (as text input). i crossed topic explains solution going through override of button cell: javafx 8 - how change color of prompt text of not editable combobox via css? my question pretty simple: can implement mechanism described in post through css file? have feeling not possible, i'm not expert @ in css wonder if may have missed something. a skin can assigned css. apply modifications skinnable in skin 's constructor, not skin s should do. assigning pseudoclass whenever no item selected skin do. with such pseudo-class buttoncell can styled css. package combobox.promptstyle; import com.sun.javafx.scene.control.skin.comboboxlistviewskin; import javafx.beans.value.changelistener; import javafx.css.pseudoclass; import javafx.scene.control.combobox; import javafx.scene.control.selectionmodel; // extend default combobox skin public class prompts...

ios - SecAccessControl has no member takeRetainedValue -

i'm followig link https://www.cigital.com/blog/integrating-touch-id-into-ios-applications/ let sacref = secaccesscontrolcreatewithflags(kcfallocatordefault, ksecattraccessiblewhenpasscodesetthisdeviceonly, .userpresence, &error); let data: nsdata = "sup3r_s3cur3_k3y".datausingencoding(nsutf8stringencoding, allowlossyconversion: false)!; var attributes: nsmutabledictionary = nsmutabledictionary( objects: [ ksecclassgenericpassword, service, data, kcfbooleantrue, sacref.takeretainedvalue() ], forkeys: [ ksecclass, ksecattrservice, ksecvaluedata, ksecusenoauthenticationui, ksecattraccesscontrol]); var status: osstatus = secitemadd(attributes cfdictionaryref, nil); on line sacref.takeretainedvalue() i value of type 'secaccesscontrol' has no me...

javascript - Detect the user's prefered units -

how can detect units user prefers read? i mean celcius vs fahrenheit, meters vs miles, etc. i can use third-party services http://freegeoip.net/json/ ip, country code, etc. use navigator.language in browser have hint of language, not sure if there safe way sure present results in right units user. (having select units options solve user, not in scope of question.) no it's not in windows or other os aware of. android started offering icu (either 4j or c) via api latest "nougat" release. icu , unicode cldr know several units, unit system @ moment not exposed there either. if call api http://freegeoip.net/json/ , country name or code allow decide countries adopted metric system opposed others (only 3 including us), there many countries e.g. britain units used imperial system. street signs show distance in miles while see gas station offer fuel per litre, not gallon in us.

java - update onOptionsItemSelected() without setting a new a listener -

so have couple of settings fragments, , want diffrent things when 'save' icon pressed, can toolbar.setonmenuitemclicklistener , imply setting listener every other fragment, , doesn't feel right, what's right way this? if understand question correctly, try following: in fragments, override method onoptionsitemselected() . if you've correctly assigned options menu save button item id, may write following code achieve want. @override public boolean onoptionsitemselected(menuitem item) { int id = item.getitemid(); switch (id) { case r.id.save_button: // sure replace id yours! // <this should put code button's action> return true; } return super.onoptionsitemselected(item); }

botframework - MS Bot: receive file via Skype connector -

does know how accept file received ms bot via skype connector? on bot side looks url files, need instruction how authorize access them: attachment: { "contenttype": "application/octet-stream", "contenturl": "https://df-apis.skype.com/v2/attachments/0-weu-d1-8ce3f64a740658ec8f227311edacc258/views/original", "thumbnailurl": "https://df-apis.skype.com/v2/attachments/0-weu-d1-8ce3f64a740658ec8f227311edacc258/views/thumbnail" } the skype attachment urls secured jwttoken, should set jwttoken of bot authorization header request bot initiates fetch image. see following sample code .

python - Pulling the Next Value Under the Same Column Header -

i using python's csv module read ".csv" files , parse them out mysql insert statements. in order maintain syntax statements need determine type of values listed under each column header. however, have run problem of rows start null value. how can use csv module return next value under same column until value returned not null ? not have accomplished csv module; open solutions. after looking through documentation not sure csv module capable of doing need. thinking along these lines: if rowvalue == '': rowvalue = nextrowvalue(row) obviously next() method returns next value in csv "list" rather returning next value under same column want, , nextrowvalue() object not exist. demonstrating idea. edit: add context, here example of doing , problems running into. if table follows: id date time voltage current watts 0 7/2 11:15 0 0 0 7/2 11:15 0 0 0 7/2 11:15 380 1 380 and here slimmed dow...

c++ - VS2015 executable become virus (with potential solution but don't know why) -

this 1 of weirdest things ever happen me in programmer career. i working on mfc project, , antivirus software bitdefender sees executable virus " gen:variant.razy.47148 " here scan result virustotal.com antivirus result update alyac gen:variant.razy.47148 ad-aware gen:variant.razy.47148 arcabit trojan.razy.db82c bitdefender gen:variant.razy.47148 emsisoft gen:variant.razy.47148 f-secure gen:variant.razy.47148 gdata gen:variant.razy.47148 escan gen:variant.razy.47148 *the rest clear result i have few configurations, happens 1 of them. compare setting difference, turns out linker--debugging--generate debug info problem. when "no", not virus, when yes, virus. @ does, says "this option enables creation of debugging information ofr .exe file or dll." detailed description ms https://msdn.microsoft.com/en-us/library/xe4t6fc1.aspx don't see possible way make executable become virus. more might...

c++ - How to use lock_guard in this conditional -

a thread has following control flow: mutex.lock() if (condition) { // synced things mutex.unlock(); // parallel things } else { // other synced things mutex.unlock(); // other parallel things } note how 4 do parts execute different things. how replace direct calls lock , unlock using std::lock_guard instead? std::unique_lock looks you're looking for. semantics similar std::lock_guard , allows more sophisticated constructs . in case still exception safety, can explicitly unlock early. like: std::unique_lock<decltype(mutex)> guard(mutex); // calls mutex.lock() lock_guard if (condition) { // synced things guard.unlock(); // parallel things } else { // other synced things guard.unlock(); // other parallel things } // unlocks on leaving scope, if held similar lock_guard

ios - calling function from a different class - Throws error 'class has no member the function' -

i have below class declared in separate swift file class keerthanaiarray: nsobject { var songtitle: string = string() var songlyrics: string = string() var esongtitle: string = string() init(songtitle: string, songlyrics:string, esongtitle: string) { self.songtitle = songtitle self.songlyrics = songlyrics self.esongtitle = esongtitle } func match(string:string) -> bool { return songtitle.containsstring(string) || esongtitle.containsstring(string) } } but when reference class in masterviewcontroller throws error message saying value of type [keerthanaiarray] has no member 'match' below code..the code fails in searchr statement var keerthanaiarray = [keerthanaiarray]() override func viewdidload() { super.viewdidload() **let searchr = (keerthanaiarray.match(keerthanaiarray.songtitle.lowercasestring))** var keerthanaiarray = [keerthanaiarray]() this instantiating array of keerth...

cmd use input as variable -

am trying write batch file take user input , use call list of stored variables. i have figured out how using if statements, feel there must cleaner way! what looking this: set a=1 set p%a%= hello *this works , can echoed: echo %p1% *output: hello set /p prompt input selection: prompt=1 set var=%prompt% echo %p(!var!)% *ideally same as: echo %p1% or whatever prompt value desired value of %a% cannot part work prompt=1 should set prompt=1 echo %p(!var!)% should echo !p%x%! (with setlocal enabledelayedexpansion of course)

loops - How to iterate over a JavaScript object? -

i have object in javascript: { abc: '...', bca: '...', zzz: '...', xxx: '...', ccc: '...', // ... } i want use for loop properties. , want iterate in parts (not object properties @ once). with simple array can standard for loop: for (i = 0; < 100; i++) { ... } // first part (i = 100; < 300; i++) { ... } // second (i = 300; < arr.length; i++) { ... } // last but how objects? for objects, use for .. in : for (var key in yourobject) { console.log(key, yourobject[key]); } to avoid logging inherited properties, check hasownproperty : for (var key in yourobject) { if (yourobject.hasownproperty(key)) { console.log(key, yourobject[key]); } } this mdn documentation explains more how deal objects , properties. if want "in chunks", best extract keys in array. order isn't guaranteed, proper way. in modern browsers, can use var keys = object.keys(yourobject); ...

swift - Color difference between UINavigationBar Tint Color and rest of app in IOS -

Image
this design in sketch: sketch says blue color 70,164,239. so have following code tab: uinavigationbar.appearance().bartintcolor = uicolor(red: 70.0/255.0, green: 164.0/255.0, blue: 239.0/255.0, alpha: 1.0) uinavigationbar.appearance().tintcolor = uicolor.clearcolor() uinavigationbar.appearance().titletextattributes = [nsforegroundcolorattributename : uicolor.whitecolor()] and following view underneath (inside action): self.two_buttons_view.backgroundcolor = uicolor(red: 70.0/255.0, green: 164.0/255.0, blue: 239.0/255.0, alpha: 1.0) but what's going on, navigation bar color little lighter color of view. light blue there's slight difference if go darker blue gets more noticeable. appears navigation bar's colors never rich rest of pages views are: the tintcolor tint color. combines translucency (is word?) of bar, along what's behind bar, give other resulting color. if want full control on actual color of navigation bar, set translucent fa...

python - trying to display data from database, only getting blank page -

i'm trying display data data base. here's template: <ul> {% post in latest_post %} <li>{{ post.id }} : {{ post.post_body }}</li> {% endfor %} </ul> here's subview: def success(request): latest_post = models.post.objects template = loader.get_template('success.html') context = { 'lastest_post': latest_post } return httpresponse(template.render(context, request)) but i'm getting blank page. why? here's model i'm trying display data: from django.db import models class post(models.model): creation_date = models.datetimefield(null=true) post_name = models.charfield(max_length=30, null=true) post_title = models.charfield(max_length=50, null=true) post_body = models.textfield(max_length=2000, null=true) post_pass = models.charfield(max_length=100, null=true) post_im = models.charfield(max_length=15, null=true) post_image = models.charfield(max_lengt...

github forked repository: How to pull the changes from forkedrepo/branch to orignalrepo/<Create-new-branch> -

usera original repository creator: no branches. master only. userb forks repository , makes changes , creates new branch , puts changes github.com/ userb /repo-name/newbranch-name how can usera , pull changes github.com/ userb /repo-name/newbranch-name , put new branch same name of userb ....that is, github.com/ usera /repo-name/newbranch-name some info on current scenario userb(forked user) not available push changes - question not "how can something" "how can myself" without requesting userb push changes usera (original repo creator) in addition, usera doesnt want merge master. usera prefers put these changes in new branch. i.e. github.com/usera/repo-name/{create-new-branch} add userb's repository remote, pull new branch locally, push usera's repository: git remote add usera github.com/usera/repo-name git remote add userb github.com/userb/repo-name git pull userb newbranch-name git push usera newbranch-name

python - scipy curve_fit unable to fit curve -

i trying use scipy.optimize function curve_fit fit set of data points using custom exponential function. code follows: import numpy np import matplotlib.pyplot plt scipy.optimize import curve_fit def fit(x, tau, beta): return np.exp(-1 * np.power(x / tau, beta)) def plot_e2e(times, e2es): optimalparams, covariance = curve_fit(fit, times, e2es) tau = optimalparams[0] beta = optimalparams[1] print 'tau is:', tau print 'beta is:', beta if __name__ == '__main__': % read_e2e_data not included proprietary reasons. times, e2es = read_e2e_data(filename) plot_e2e(times, e2es) doing raises following exception (line numbers may different due taking out unrelated stuff): traceback (most recent call last): file ".\plot_e2e.py", line 54, in <module> plot_e2e(times, e2es) file ".\plot_e2e.py", line 34, in plot_e2e optimalparams, covariance = curve_fit(fit, times, e2es) file "c:\anaco...

r - Shiny dateRangeInput - extract month and year from user input -

i know if possible extract month , year separate variables daterangeinput after user input. ui.r shinyui(fluidpage( titlepanel("time series forecasting arima+stl"), sidebarlayout( sidebarpanel( daterangeinput('daterange', label = paste('date range selection'), start = "2010-01-01", end = "2012-12-31", min = "2010-01-01", max = "2012-12-31", separator = " - ", weekstart = 1 ), actionbutton("go", "go!") ), ) )) server.r shinyserver( function(input, output, session){ forecast <- eventreactive(input$go, { }) }) from have read on subject far know how extract entire date user input. in above code there way me use variable contains start , end month obtained daterangeinput in server.ui? appreciated.

javascript - Compare dates as strings in typescript -

i trying compare 2 dates strings in typescript. input have below :- startwindow = '05/2014' endwindow = '05/2018' i need write function check if start window greater end window. both inputs of string type. thanks you can convert date , compare them: function convertdate(d) { var parts = d.split('/'); return new date(parts[1], parts[0]); } var start = convertdate('05/2014'); var end = convertdate('05/2018'); alert(start < end);

python - Get result of value_count() to excel from Pandas -

i have data frame "df" column called "column1" . running below code: df.column1.value_counts() i output contains values in column1 , frequency. want result in excel. when try running below code: df.column1.value_counts().to_excel("result.xlsx",index=none) i below error: attributeerror: 'series' object has no attribute 'to_excel' how can accomplish above task? you using index = none , need index, name of values. pd.dataframe(df.column1.value_counts()).to_excel("result.xlsx")

sql - Creating a view for 3 tables with a little complex relationships -

so have 3 tables, "ruta", "track_ruta", "punto_ruta" ruta has relationship of 1 many track_ruta , relationship of 1 many punto_ruta. track_ruta has relationship of 1 many punto_ruta. ruta means route in spanish way. long story short route has tracks , tracks have points. there can points without tracks belong route. why way is. need retrieve , searches according dates on points , need points of route. had sql sentence select distinct p.* puntoruta p, ruta r, trackruta t ((r.codigo=routeid , t.ruta.codigo=r.codigo , p.trackruta.codigo=t.codigo) or p.ruta=routeid) routeid replacing id on code this worked. dont using distinct know costly , worked while. until user had million points on route , takes ever search when using limits. have not had handle complex db relations in ages rusty. i fuzzy on how transform view. using joins this select * punto_ruta p join track_ruta t on p.id_track_ruta=t.id_track_ruta join ruta r on r....

python - Importing Keras inside of Django causes it to crash -

i've created restful api computer vision app i've made. it works fine using existing svm , nolearn neural network. however, i've trained new cnn using keras (theano backend) , whenever import keras inside 1 of py modules, crashes. import keras i tried importing views.py file , crashes. this weird , seems directly related django. running python on machine , doing import keras reveals no issue @ all. what's going on here? i came error when call model_load function django web backend. must create session when use tensorflow in websever backend! fix add: import tensorflow tf with tf.session(): //my code call keras unit this may you. https://www.tensorflow.org/versions/r0.11/api_docs/python/client/session_management

Rails: How to order by descending value in controller -

i trying show list of jobs ordered median_salary descending order. far, seems take account first number of median_salary . 900 listed above 1000, though value of 1000 > 900. homes_controller.rb: def index nyc_highest = highestpaidjob.where("city = ?", "nyc") @nyc_highest = nyc_highest.order("median_salary desc") end index.html.erb: <%= @nyc_highest.inspect %> returns: #<activerecord::relation [#<highestpaidjob id: 11, job: "architect, city planner", median_salary: "95928.48", count: 237, margin_of_error: "", city: "nyc", state: "new york", created_at: "2016-07-25 18:17:17", updated_at: "2016-07-25 18:17:17">, #<highestpaidjob id: 7, job: "medical", median_salary: "170507.69", count: 128, margin_of_error: "", city: "nyc", state: "new york", created_at: "2016-07-25 18:09:30", updated_at: ...

Inconsistent colors in Excel/PowerPoint/Word Charts -

Image
i have 2 scatter plots, representing same things, 2 different scenarios. created in same excel workbook, on different sheets, , have same color schemes applied them. however, colors don't line between charts. have 6 charts total, , 4 start dark color , other 2 start lighter color. chart 1 - first color dark chart 2 - first color lighter i haven't been able find else who's run same problem. issue occurs when copy charts powerpoint , word well. pretty annoying because want keep colors consistent throughout charts. edit can copy chart colors want , edit data, charts consistent. still not sure how ended different colors, though. i've run issue in past. i've looked around , found following suggestions. after copying chart excel, when you're in either powerpoint or word, click on downward arrow "paste", try any one of following: 'paste special' 'paste link'; or 'paste options' 'keep source formatt...

python - Removed Rows from Pandas Dataframe - Now Indexes Are Messed Up? -

so have dataframe in pandas includes genders of patients. wanted sort gender used: df = df[df.gender == 0] but when print dataframe like: gender 0 0 2 0 5 0 where row indexes on left stay before row removal , don't "resequence" 0, 1, 2 etc. making difficult or impossible iterate through right now. how resequence row indexes? df = df[df.gender == 0] is taking slice of df df.gender equal 0 . expected. bringing along it, row indices each of rows df.gender equal 0 . correct , has many wonderful benefits. if don't want see that, , instead want order 0 whatever, others have suggested in comments. df = df[df.gender == 0].reset_index(drop=true)

linux - Bash: Read in file, edit line, output to new file -

i new linux , new scripting. working in linux environment using bash. need following things: 1. read txt file line line 2. delete first line 3. remove middle part of each line after first 4. copy changes new txt file each line after first has 3 sections, first ends in .pdf , third begins r0 middle section has no consistency. example of 2 lines in file: r01234567_high transcript_01234567.pdf high school transcript r01234567 r01891023_application_01891023127.pdf application r01891023 here have far. i'm reading file, printing screen , copying file. #! /bin/bash cd /usr/local/bin; #echo "list of files:"; #ls; index in *.txt; echo "file: ${index}"; echo "reading..." exec<${index} value=0 while read line #value='expr ${value} +1'; echo ${line}; done echo "read done ${index}"; cp ${index} /usr/local/bin/test2; echo "file ${index} moved test2"; done so question is, how can delete middle bit of each li...

node.js - Unable to install npm under corporate proxy -

i have tried given in link: using npm behind corporate proxy .pac but i'm still unable install webpack , babel. i've been told if got npm nodejs, need modify path avoid using one. npm default go c:\users\username\xxxx . so, updated path as: %path%;c:\users\username\xxxx;c:\util\nodejs . have empty npm folder under path c:\users\username\xxx & still, it's reading npm nodejs 1 only. even npm install npm -g not working (same proxy error).

caffe - BatchNorm and Reshuffle train images after each epoch -

the recommended way of using batchnorm reshuffle training imageset between each epoch, given image not fall in mini-batch same images on each pass. how achieve caffe? if use imagedata layer input, set "shuffle" true . for example, if have: layer { name: "data" type: "imagedata" top: "data" top: "label" transform_param { mirror: false crop_size: 227 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" } image_data_param { source: "examples/_temp/file_list.txt" batch_size: 50 new_height: 256 new_width: 256 } } just add: layer { name: "data" type: "imagedata" top: "data" top: "label" transform_param { mirror: false crop_size: 227 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" } image_data_param { source: "examples/_temp/file_list.txt" batch_size: 50 ne...

excel - Repeat part of my sub -

i'd run part of sub, different keyword each time it's run. i'm writing this, there shorter way doing it? i'm making category direct debits, atm cash withdrawals, , debit card purchases in column d - searching d/d, c/l, , pos respectively in column b. i'm changing variables, typing , running same bit of code every time. feel there should way "run bit again, searchterm , searchresult changed!" i'm sure more knowledgable help. i'm using sub can't insert sub run within it, or function? , i'm looping i'm not sure how loop fit in? what do? can guess i'm quite new this, little js knowledge in past. sub organisedefaultcategories() ' ' organisedefaultcategories macro ' categorise bank statement entries default inputs. run first. ' dim foundrange range, firstaddress string, searchterm variant, searchresult variant searchterm = "d/d" searchresult = "direct debit" ...

regex - Regular Expression (PHP) => greater that or if not -

it possible have in regular expression (php), '>' or 'if not' ¿? for example: have 5 number string 'xxxxx': '00054', '47690', '20593'... i need regular expression verify: 5 numbers greater 1 i had this: '/^[0-9]{5}$/' doesn't verify greater '00001' ! i'm looking '>' or 'if not 00000'... thanks ps: know can done with: if((int)$string > 1) i can figure out 2 ways: /^(?!00000)\d{5}$/ this first checks start not followed 5 zeros, searches 5 digits. /^(?:[1-9]\d{4}|\d[1-9]\d{3}|\d{2}[1-9]\d{2}|\d{3}[1-9]\d|\d{4}[1-9])$/ this 1 checks 5 combinations, each of contains non-zero digit in 1 of 5 positions.

select - Angular2 - get selected part of text value -

i'd create simple editor make selected text bolder example. there textarea "super text" value. now select part of text (for example "super"). how selected value? <textarea (selected)=".."></textarea> this call function every time select inside textarea. <textarea (selected)="view(textarea.value)" #textarea></textarea> this print whole textarea value when select something. i'd print part of text, selected. how that? i see binding function (selected) attribute on texarea. should (select) event fired selection. since getting callback executed, assume typo. now main question. on textarea, have 2 properties selectionstart , selectionend, name suggest indexes of position in value selection starts , ends. can selected substring using textarea.value.substring(textarea.selectionstart, textarea.selectend) you can pass value of expression inside component's functions. hence, this <texta...

jquery - Couldn't show messages in the center using center() function -

i calling flash messages through function: function check_notice(visible_for) { notice = $('.notice').text(); $('#block').show(); $('.notice_container').center().show().delay(visible_for).animate({ 'opacity' : '0' }, 2000, function() { $('.notice_container').css({'opacity':'1', 'display':'none'}); $('.notice').empty(); $('#block').hide(); }); } $.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerheight()) / 2) + $(window).scrolltop() + "px"); this.css("left", (($(window).width() - this.outerwidth()) / 2) + $(window).scrollleft() + "px"); return this; } .center() meant messages displayed in center. when use, there no message displaying , when remove center(), messages shown @ top. please me.

ios - Hold or batch Realm notifications? -

i have scenario i'll doing many updates end effecting result vc listening to. ideally i'd send 1 notification @ end of batch a few questions: is possible batch notifications, rather having every update send notification? is right way think it? should stop listening notifications when batch starts , start listening again when it's done? notifications occur @ end of write transaction, easiest thing case perform of work in 1 transaction (i'd recommend doing on background thread), , close when want notification fired. this general recommended approach since guarantee fine-grained change indexes coalesced singular notification @ end. if don't care fine-grained change indexes (i.e., you're doing complete refresh on each notification), consider setting flag disregards notifications until you've completed work. you remove notification block, mean there'd significant amount of tear-down, , re-setup work you'd have each time.

java - how to know if the pixel color is black from a float 4 -

i ask question how know pixel color using t_sampler in jocl in different way want konw if pixel black or white knowing using t_sampler in kernel const sampler_t smp = clk_normalized_coords_false | //natural coordinates clk_address_clamp | //clamp zeros clk_filter_nearest; //don't interpolate then used int2 coord = (int2)(get_global_id(0), get_global_id(1)); float4 pixel = read_imageui(input, smp, coord); my question is: how use value pixel know color of concerned pixel? i stuck few days , tried many solutions solve problem, if need clarifications respond. here kernel code const sampler_t smp = clk_normalized_coords_false | //natural coordinates clk_address_clamp | //clamp zeros clk_filter_nearest; //don't interpolate __kernel void basic(__read_only image2d_t input,__global float *result) { int gidx = get_global_id(0); int gidy = get_global_id(1); int2 coord ...

Duplicate WebRTC class in android -

i'm getting these errors in android app , here logcat. > error:execution failed task > ':android:transformclasseswithjarmergingfordebug'. > com.android.build.api.transform.transformexception: java.util.zip.zipexception: duplicate entry: > org/webrtc/voiceengine/webrtcaudiorecord.class i trying integrate second webrtc android app, have integrated tokbox jar in project , i'm trying put vsee sdk in app well, i'm guessing both have webrtc libraries so, i'm getting duplicate error i'm unable finding way exclude 1 of fix duplicate error. so far tried add on app's gradle build. > exclude group: 'org.webrtc' but it's not working, can me this? in advance! i got same error. turnd out, in case, written: "duplicate". had same "compile" line on "build.gradle" - "dependencies". there, error started jump after upgraded android studio (2.2) , gradle version ('classpath '...

javascript - Firebase v3 - Handling Unverified Password-Based Users? -

how handle user sessions in case password-based auth user has not yet verified email address using custom email action handlers ? specifically, have chip in upper right corner of web app displaying displayname of signed in user. handling signed in user unverified in app logic no problem except technically signed in , need way sign out. showing sign out button bit misleading bcs have no privileges until email validated. showing "visitor" seems odd. how should handle scenario? var myappname = (function() { var pub = {}; pub.doc = document; var doc = pub.doc; pub.email; pub.displayname; pub.photourl; pub.uid; pub.validuser = false; firebase.auth().onauthstatechanged(function(user) { pub.loaduservariables(); if (user) { var provider = firebase.auth().currentuser.providerdata[0].providerid; var verified = firebase.auth().currentuser.emailverified; switch(provider) ...

plotly/python- how to embed newest plot on your website -

i want include plot plotly on website. now have this: (as website) <iframe width=750 height=500 frameborder=”0” seamless=”seamless” scrolling=”no” src='https://plot.ly/~zfrancica/66/machine-worn-percenatage/'> </iframe> but can specific plot. call in backend generate new picture every time refresh webpage , data may change. how should newest plot in account? if understand question correctly need timer in javascript periodically checks backend new plot

Python for loop only goes through once -

i'm writing script search through multiple text files mac addresses in them find port associated with. need several hundred mac addresses. function runs first time through fine. after though new mac address doesn't passed function remains same 1 used , functions loop seems run once. import re import csv f = open('all_switches.csv','u') source_file = csv.reader(f) m = open('macaddress.csv','wb') macaddress = csv.writer(m) s = open('test.txt','r') source_mac = s.read().splitlines() count = 0 countmac = 0 countfor = 0 def find_mac(sneaky): global count global countfor count = count +1 switches in source_file: countfor = countfor + 1 # print sneaky goes through loop once switch = switches[4] source_switch = open(switch + '.txt', 'r') switch_read = source_switch.readlines() mac in switch_read: # print mac search through switches ...

qt - Is it safe to check if a string equals to a qsTr string in a multi language app - qml -

so if have following property: property string somestring: qstr("text") and have following function: function isequal(tothisstring) { if (somestring === tothisstring) { return true } else return false } } my question if application has translation other language other english. function still compare "text" or compare translated string? an example qt: const qstring english = "hello world"); const qstring spanish = qobject::tr(english); // hola mundo is equal? qdebug() << "is equal? " << (english == spanish); qdebug() << "is equal? " << (qobject::tr(english) == spanish); result: is equal? false equal? true you have translate every string, , should same string exactly. it's dificult manage, looks recipe disaster. you have use alternative data field compare values, avoid strings. example qcombobox: enum countries {eeuu = 0, spain, france}; qcombobox* combo = ne...

css - jquery.mb.YTPlayer how to add a url redirect triggered by the end of the video -

new coding, have tried inserting various html5 code such as: function redirect() { document.location="index_2.html"; } browser cannot display video element. this works browser player tried adding element of above following code: function redirect() { document.location="index.html"; } <a id="bg-video" class="player" data-property="{videourl:'https://www.youtube.com/watch?v=tdvbwpzj7dy',containment:'body',autoplay:true, mute:false, startat:0, showcontrols:false, loop:false, onended:redirect()"}" data-poster="images/bg.jpg">youtube</a> <div id="bg-video-controls"> <a id="bg-video-volume" class="fa fa-volume-off" href="#" title="unmute">&nbsp;</a> <a id="bg-video-play" class="fa fa-pause" href="#" title="pause">&nbsp;</a> </div> <!-- ...

c# - ASP.NET Web API to be consumed by Angular application -

i looking workaround allow crud operations carried out on database served sql server 2000. have read, sql server 2000 incompatible entity framework provided asp.net. have seen post detailing how create connection database ado.net, i've not found illuminating articles performing cruds. for example, have following code works mysql server on local machine: public class routesdemocontroller : controller { public actionresult one() { string querystring = "select first_name student"; string connectionstring = "server=localhost;database=testdb;user id=uid;password=password;"; string result = ""; using (mysqlconnection connection = new mysqlconnection(connectionstring)) { mysqlcommand command = new mysqlcommand(querystring, connection); connection.open(); mysqldatareader reader = command.executereader(); try ...

winforms - C# keyup event issue -

i use keyup event add functionality pressing enter cursor move next control. event works typed in textbox , press enter cursor move next control letters typed in previous control clear. did not add clear function anywhere in code. here code: private void nametextbox_keyup(object sender, keyeventargs e) { if(e.keycode == keys.enter) { this.selectnextcontrol(nametextbox, true, true, true, true); } } private void emailtextbox_keyup(object sender, keyeventargs e) { if (e.keycode == keys.enter) { this.selectnextcontrol(agetextbox, true, true, true, true); } } set e.handled flag true prevent default key actions suspect adding new line control , hiding text: if(e.keycode == keys.enter) { this.selectnextcontrol(nametextbox, true, true, true, true); e.handled = true; } you need override processcmdkey in order prevent new lines being entered , hiding ...

How to build libjingle_peerconnection of webrtc only -

i try build webrtc project. big. ninja file generated whole project. how build single libjingle_peerconnection lib ? after running hooks (ie. gclient sync ) setup directories, can compile libs want running like, ninja -c ./out <libjingle libs> you can create own separate .gyp file build static lib has libjingle libs direct dependencies, way have build single lib link libjingle libs.

javascript - Lightbox not opening on iPhone -

i made own lightbox javascript , css somehow wont work on iphones. why that? jquery( document ).ready(function() { //lightbox open jquery('.lightbox_trigger').css('cursor','pointer'); jquery('.lightbox_trigger').live('click', function(){ jquery('#overlay, #lightbox').show(); }); }); <a href="#" class="lightbox_trigger qbutton or-border-btn" onclick="">tickets</a> as can see tried multiple things adding cursor: pointer , empty onclick. still wont work iphones. missing something? try this: jquery('.lightbox_trigger').live('click', function(e){ e.preventdefault(); i think iphone try go # href if put preventdefault don't have behavior.

has_many relations in Ruby on Rails 5.0 -

i have been struggling time problem in rails app. have 3 classes, merchandise , merchandisecategory , merchandisemerchandisecategory . merchandisemerchandisecategory used create many-to-many relation between other two. when run following commands in rails console, corresponding results: m = merchandisemerchandisecategory.first # returns object relates first merchandise # first merchandise category m.merchandise_category # returns corresponding merchandise_category m.merchandise_category.merchandise_merchandise_categories.first # returns array of corresponding merchandisemerchandisecategy ids m.merchandise # returns corresponding merchandise m.merchandise.merchandise_merchandise_categories.first # loaderror: unable autoload constant # merchandise::merchandisemerchandisecategory, expected # /home/bjarki/development/h2/app/models/merchandise/merchandise_merchandise_category.rb # define so, relations work except one-to-many relation between merchandise , merchandisemerchandi...

How solve import error in Python when trying to import Numpy -

this error when trying import numpy on opening python (2.7.8): traceback (most recent call last): file "<stdin>", line 1, in <module> importerror: no module named numpy this path of python binary /usr/local/bin/python this path of pip /usr/local/bin/pip also, when put in pip freeze found numpy package numpy==1.8.0rc1 i have looked @ other relevant questions, i'm not able diagnose cause. i'm guessing might problem in paths. start? as akshat pointed out in comments above, had multiple versions of python installed. have been effect of using homebrew and/or macports in past. followed steps detailed in too many pythons on mac os x mountain lion , did fresh install of python 2.7.12 able reinstall pip , packages subsequently.

php - I can't use my User model in my view -

i trying peform method such getusername() in foreach of posts gives me error: class 'user' not found (view: /home/stackingcoder/development/php/internetstuffer/resources/views/index.blade.php) i have in homecontroller.php: use app\user; still doesn't work. know why? here code of view: @foreach($posts $post) <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default"> <div class="panel-heading"><i class="fa fa-btn fa-message"></i>{{ $post->gettitle() }} | {{ user::find( $post->getuser_id() )->getusername() }} </div> <div class="panel-body"> {{ $post->gettext() }} </div> </div> </div> </div> ...

javascript - How to referesh a php page after reception of post from jquery -

i posting local time on client machine server using jquery. besides displaying local time through php, save in database on server side. display client's time correctly, need refresh php page after receiving post jquery. how can that? here code. tried use header("refresh:0"), didn't work. <script type="text/javascript"> $(function(){ var d = new date(); var datestr = d.tostring() $.post(window.location, { datestr: datestr }).success(function(data){ var res = $(data).filter('#divmessage').text(); alert(res); }); }); </script> <div id="divmessage"> <?php $v2 = 'nothing!'; if(isset($_post["datestr"]) && strlen(trim($_post["datestr"])) > 0) { $dstr = $_post["datestr"]; $v2 = 'current date/time '.$dstr; echo "<span style=\"color:green\">$v2</span>"; ...