Posts

Showing posts from March, 2014

c++ - Why std::hash<int> seems to be identity function -

#include <iostream> int main() { std::hash<int> hash_f; std::cout << hash_f(0) << std::endl; std::cout << hash_f(1) << std::endl; std::cout << hash_f(2) << std::endl; std::cout << hash_f(3) << std::endl; } i compile "g++ main.cpp -std=c++11" , result : 0 1 2 3 why happening? don't use library , don't have specialized hashing function. addendum : wanted define hash unordered_set of unordered_set of int hash of set being sum of components hashs, if it's identity it's not cool because hash of {2,4} same hash of {1,5}. simplest way avoid may use std::hash double function. it seems identity, allowed distinct.. cpp reference the actual hash functions implementation-dependent , not required fulfill other quality criteria except specified above. notably, implementations use trivial (identity) hash functions map integer itself. in other words, these hash functions...

scikit learn - Ensembling with dynamic weights -

i wondering if possible use dynamic weights in sklearn's votingclassifier. overall have 3 labels 0 = other, 1 = spam, 2 = emotion. dynamic weights mean following: i have 2 classifiers. first 1 random forest performs best on spam detection. other 1 cnn superior topic detection (good distinction between other , emotion). votingclassifier gives higher weight rf when assigns label "spam/1". is votingclassifier right way go? best regards, stefan

External HTML file in Django -

i'm making django app in need embed many external html files in template. each html file stored in own directory, along subdirectory contains images. file structure: abstract1 pictures image1.png image2.png abstract1.html i use custom template tag embedding (see below). problem: html files loaded, linked resources (e.g. img) not working (i.e. they're not being displayed). html files use relative urls, which, mixed django template base path produce invalid url, if use hardcoded absolute urls problem remains. feel i'm missing obvious. there proper (or not proper working) way overcome such problem? template {% load abstracts_extras %} <!doctype html> <html> <body style="margin-left:10px"> <h2>{{abstract}}</h2> <b>authors:</b><br/> <ul> {% author in authors %} <li>{{author}}</li> {% endfor %} ...

java - Setting a parameter request in alfresco webscript -

in source code below: @override protected void execute(webscriptrequest request, map params, jsonobject resultat) throws exception { string user = request.getparameter( param_user ); //need set parameter here using instruction request.setparameter(...) resultat.put(resultat_json_param, "ok"); } i need set request parameter in webscript. idea on how it?

xml - jsonix: Element [] is not known in this context, could not determine its type -

following instructions on using jsonix-schema-compiler got mapping object xsd-file; summarized content of is: var identperson_module_factory = function () { var identperson = { name: 'identperson', defaultelementnamespaceuri: 'http:\/\/www.some.domain.de\/mynamespace', typeinfos: [{ .... .... }], elementinfos: [{ elementname: 'person', typeinfo: '.person' }] }; return { identperson: identperson }; }; now want produce xml-string using jsonix , above json-mapping-object: var context = new jsonix.context([identperson]); var marshaller = context.createmarshaller(); var xmldoc = marshaller.marshalstring(myjsonstring); first lines of myjsonstring following: { person: { aliasname: { titel: '', namenssuffix: '', familyname: [object], ..... ..... } ending error: message: element [person] not known in context, not determine type. stack: error: ele...

.net - Jquery Ajax call to url not working in ASP.NET -

i use ajax call in aspx page , use url rewrite. ajax call hit webmethod without url rewrite rule after applying rewrite rule stop working. my aspx page ajax call is: $.ajax({ type: "post", url: "../cc/page.aspx/sendnewsletter", data: d, contenttype: "application/json; charset=utf-8", datatype: "json", success: function (response) { alert('hi'); if (response.d == "1") { alert("newsletter has been sent successfully."); } else { alert("something went wrong.please try again later."); } }, failure: function (response) { alert(response.d); } }).always(function () { }); and webmethod is: [webmethod] public static string sendnewsletter(string to, string newsletter, string newslettername) { } my rewrite rule is: <rul...

javascript - Laravel,Ajax,Jquery Plugin image upload,preview, convert to thumbnails and display -

enter image description here preview uploaded images after upload.and show image on form.want achieve of jquery image upload laravel framework. appreciated. @simon have implemented ur code.its working,but 1 image shown in view , want show 3 images,which selected.plz help enter image description here if using standard file input type , using moderish browser etc try following. $('#addimage').on('change', function(evt) { var selectedimage = evt.currenttarget.files[0]; var imagewrapper = document.queryselector('.image-wrapper'); var theimage = document.createelement('img'); imagewrapper.innerhtml = ''; var regex = /^([a-za-z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/; if (regex.test(selectedimage.name.tolowercase())) { if (typeof(filereader) != 'undefined') { var reader = new filereader(); reader.onload = function(e) { theimage.id = 'new-selected-image'; ...

c# - Dead lock when retrieving several keys from Redis -

i'm trying result of queries redis (using stackexchange c# client) in parallel somehow i'm running in deadlock , not sure where the method retrieving data: public livedata get(string sessionid) { return getasync(sessionid).result; } private async task<livedata> getasync(string sessionid) { var baskettask = getbasketasync(sessionid); var historytask = gethistoryasync(sessionid); var captureddatatask = getcaptureddataasync(sessionid); var basket = await baskettask; var history = await historytask; var captureddata = await captureddatatask; return new livedata { basket = basket.isnullorempty ? new list<product>() : jsonconvert.deserializeobject<list<product>>(basket), history = history.select(cachedproduct => jsonconvert.deserializeobject<product>(cachedproduct.value.tostring())).tolist(), captureddata = captureddata.todictionary<hashentry,...

linux - Sudo not working - "sudo: effective uid is not 0, is sudo installed setuid root?" -

i have been trying allow access normal user of ec2 amazon server ('ec2-user') library. i did: "sudo chown -r ec2-user /usr" realize had been fatal mistake. worked, sudo gone. if try use sudo get: "sudo: effective uid not 0, sudo installed setuid root?" i tried "chmod u+s /usr" suggested in answer. not solve issue. i guess there basic missing. forgive newb ignorance. the suid bit of permissions sudo changes effective user owner of sudo command file, changed ec2-user. need give ownership of sudo command root.

php - Behat\Laravel can't find submit -

i'am trying test laravel app behat. there homepage fields name, email , "register" button. i'm trying press button in behat-test, have error fatal error: call member function press() on null (behat\testwork\call\exception\fatalthrowableerror) my html: <html> <head> </head> <title>registration</title> <body> <form action="/thanks" name="register"> <p align="center"><font size="4"><b>please, enter name , e-mail</b></font></p> <p align="center"><input name="name" type="text" value="name"></p> <p align="center"><input name="email" type="text" value="e-mail"></p> <p align="center"><input name="registerbutton" type="sub...

html - Change the content for each tab Angular 2 -

i'm using segmentedbar tabs. , menu.html file looks this: <stacklayout orientation="vertical" width="310" height="610"> <nav> <h1 class="title">hello world</h1> <segmentedbar #tabs [items]="items" [selectedindex]="selectedindex" ></segmentedbar> </nav> </stacklayout> the problem if modify it, nothing seems happen on ui. shows tabs, that's it, i.e. 'hello world' doesn't show on interface. want modify html, there other actions happen. why happening? how can change views, there different views each tab? and here menu.component.ts file: import {component, oninit, ondestroy, afterviewinit, viewchild, elementref} '@angular/core'; import {page} 'ui/page'; import {segmentedbar, segmentedbaritem, selectedindexchangedeventdata} 'ui/segmented-bar'; @component({ selector: 'tabs', templateurl:"./compone...

ember.js - Ember Data plural serializer -

i have product model, , /products/ route - ember data sends request host/api/v1/product instead of host/api/v1/products - why this? also, how can use plural end point individual product fetch? i.e: host/api/v1/product/1 check buildurl method by default, pluralizes type's name (for example, 'post' becomes 'posts' , 'person' becomes 'people'). override pluralization see [pathfortype](#method_pathfortype). and there list of sub-methods ( https://github.com/emberjs/data/blob/v2.6.1/addon/-private/adapters/build-url-mixin.js#l54 ) switch (requesttype) { case 'findrecord': return this.urlforfindrecord(id, modelname, snapshot); case 'findall': return this.urlforfindall(modelname, snapshot); case 'query': return this.urlforquery(query, modelname); case 'queryrecord': return this.urlforqueryrecord(query, modelname); case 'findmany': return this.urlforfindmany(id, ...

c# - Regex for containing a word with specific characters -

Image
i need regex find whether sentence contain word. if word having prefix or postfix word in valid valid specific characters ,.*+- etc below example. searching process word, valid sentence make them bold processes process processing process-specific processed processor procession inter-process uniprocessor multiprocessing process's "process" process10 use word-boundary class ( \b ): \bprocess\b in case-insensitive regex match should give correct result: string[] strings = new string[] { @"processes", @"process", @"processing", @"process-specific", @"processed", @"processor", @"procession", @"inter-process", @"uniprocessor", @"multiprocessing", @"process's", @"""process""", @"process10" }; foreach (string s in strings) { if (regex....

How to split large file and write into individual record using identical pattern perl? -

i have multi-gb file consisting of thousands of individual files based on ids. each component file consists of 4 comment lines followed contents. every second commented lines has unique id. split file individual files named id. there second size list of ids , size. want have line written first first line in each output file. examples size list a_1 100 bxx_xx 25 p_b 342 1a_z0 343 z867 200 bws 111 input file # ver xx # query: a_1 # database: xx # usage: xx a_1 .* a_1 .* a_1 .* a_1 .* a_1 .* # ver # query: bxx_xx # database: xxxxxx # usage: xxxxx bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* bxx_xx .* # ver # query: p_b # database: xxxxxx # usage: xxxxx p_b.* p_b.* p_b.* p_b.* p_b.* p_b.* # ver # query: 1a_z0 # database: xxxxxx # usage: xxxxx 1a_z0.* 1a_z0.* 1a_z0.* 1a_z0.* # ver # query: z867 # database: xxxxxx # usage: xxxxx # ver # query: bws # database: xxxxxx # usage: xxxxx bws.* bws.* bws.* output sho...

sql server - System.Data.SqlClient.SqlException error at asp.net -

Image
i new @ asp.net. trying database connection. getting error. please advice me. using system; using system.collections.generic; using system.data.sqlclient; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; namespace webapplication1 { public partial class webform1 : system.web.ui.page { protected void page_load(object sender, eventargs e) { string cs = "data source=.;initial catalog=test;integrated security=sspi"; sqlconnection con = new sqlconnection(cs); sqlcommand comma = new sqlcommand("select * try", con); con.open(); gridview1.datasource = comma.executereader(); gridview1.databind(); con.close(); } } } the issue connection string using. data source=.;initial catalog=test;integrated security=sspi check sql server instance name running on local. data source=**.\yourinstancename**;initial ca...

java - Not able to replace a text in PDF using PDFBox 2.0.2 -

my requirements 1) need identify particular text pattern 2) replace text pattern pre-defined text-value same format of text pattern, such font, font colour, bold … 3) able identify text, replace text predefined values, writing pdf failing. i tried following 2 appraches write pdf 1) overriding writestring(string string, list textpositions)of pdftextstripper 2) using cosarray.add(new cosstring(replacedfield)); or cosarray.set(…) results approach 1 - overriding writestring the pdf generated code not getting opened in pdf. able open in word, there no format of original text. results approach 2 - using cosarray.add or cosarray.set(…) seeing boxes in generated pdf . code approach 1 - overriding writestring public void rewrite(string templatepdfpath) throws ioexception { pddocument document = null; writer pdfwriter = null; try { file templatefile = new file(templatepdfpath); document = pddocument.load(templatefi...

python - start flask server @ startup with supervisor: FATAL Exited too quickly -

i trying start flaskserver @ startup of supervisor. error message: python_auutostart fatal exited (process log may have details) this entry in logfile: traceback (most recent call last): file "run.py", line 2, in <module> app import app file "/home/flaskserver/app/__init__.py", line 1, in <module> flask import flask importerror: no module named flask this .conf: [program:python_auutostart] user=nobody command = python run.py directory = /home/flaskserver/ autostart = true autorestart = true stderr_logfile=/etc/supervisor/long.err.log stdout_logfile=/etc/supervisor/long.out.log i can start flaskserver without problems if run ./run.py don´t run supervisor. don´t see why importerror posted. maybe some1 can point me probleme here. the python use default system python (you can check wich which python should display /usr/bin/python or wherever system python is). not have access (by default) libraries i...

visual studio - slowcheetah: how to add an existing file as a transform -

i'm using slowcheetah config transforms vs2013. let's web.config , web.debug.config files via external source, reason. how can import both files in solution , have slowcheetah detect transform relation? know can manually change csproj file it, can done automatically? as side question if web.config in project add web.debug.config transform? what i'm doing select add transform, may add several more transform test, staging , on. delete ones don't need , open transforms , copy content manually.. this action doesn't happen often, bugs me when does.

sharepoint 2013 - As a site collection administrator I am not able to access site settings on site collection -

Image
as collection administrator not able access site settings on sharepoint site collection. if click on site settings showing "sorry, site has doesn't share you". login using site collection administrator account on dev server. if create new site collection same web application can access everything. 1 more thing restored production database on server , associated web application. i hope can issue please. this might happen production environment have different users , when restore development environment, development environment changes override. to fix issue, go central administration -> application management. under site collection section, click on "change site collection administrators". in select site collection. change site collection administrator , click ok.

Google Maps API v2 Android add shape drawable as marker -

i've been trying add shape drawable marker icon marker want add on map. shape looks (res/drawable/blue_circle.xml): <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <size android:width="15dp" android:height="15dp" /> <solid android:color="@color/blue" /> </shape> and try add marker this: markeroptions.icon(bitmapdescriptorfactory.fromresource(r.drawable.blue_circle)); apparently nullpointer exception. must marker icon bitmap? allowed add shapes drawables marker icons? , if yes doing wrong? create drawable marker (res/drawable/map_dot_red.xml): <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <gradient ...

android - Stub value of Build.VERSION.SDK_INT in Local Unit Test -

i wondering if there anyway stub value of build.version.sdk_int ? suppose have following lines in classundertest : if (build.version.sdk_int >= build.version_codes.jelly_bean) { //do work }else{ //do work } how can cover code ? i mean want run 2 tests different sdk_int enter both blocks. is possible in android local unit tests using mockito / powermockito ? thanks change value using reflection. static void setfinalstatic(field field, object newvalue) throws exception { field.setaccessible(true); field modifiersfield = field.class.getdeclaredfield("modifiers"); modifiersfield.setaccessible(true); modifiersfield.setint(field, field.getmodifiers() & ~modifier.final); field.set(null, newvalue); } and then setfinalstatic(build.version.class.getfield("sdk_int"), 123); it tested. works.

Java single regex as all alphabets or strictly alphanumeric of 6 length -

i want make java regex strictly alphanumeric of 6 digits or alphabets of 6 digits. want these in single regex. in stack overflow found (?=.*[a-za-z])(?=.*[\\d]).* did not work condition of 6 digits. tried or inside regex (?=.*[a-za-z])(?=.*[\\d]){6}.*|[a-z]{6} didn't worked. please suggest better solution kind of regex. so want allow alphanumeric strings of 6 length disallow digits only. "^(?!\\d*$)[^\\w_]{6}$" the lookahead disallow digits only. [^\w_] is short alnum [a-za-z0-9] see demo @ regexplanet (click java)

wordpress - How to filter orders for a customer API Woocommerce 2.6 -

i filter orders based on id of client, following syntax doesn't working, when try: www.example.com/wp-json/wc/customers/1/orders? provide me correct syntax i'm on woocommerce 2.6 try syntax get orders?customer=1

android - Connect to mySQL database over LAN without using a webserver -

i want have multiple clients connect server on lan , access/modify mysql database in server. how go doing this? can guys provide resources/links research on topic to answer question, should able connect mysql database adding jdbc driver project jar file in android studio. now real app plan distributed thousands of users there security issues, performance issues, , scalability issues. security issues: you expose database directly internet opening port public access apps connect. web app adds layer in middle, keeping database access inside intranet. you expose data directy public providing @ least 1 public account known (i assume way access because managing 1 account per user wouldn't realistic). web app isolates user account database accounts. by providing access way, android mobile devices can rooted, potentially granting anonymous access data. performance issues: with web app in middle, webapp manages connections database. enables sharing connections ...

android - Using Genymotion's GPS with Google Play Store -

i have installed genymotion , set virtual device (google nexus 5x 6.0.0 api 23) google play services on can access play store , other google services. i'm messing around location, , works great maps (change location france germany new york, ask maps update location, puts me in right place). with play store, however, it's not working. know play store displays different results based on location, here, whether i'm in new york, berlin or paris, results same, whether top charts or when type keyword. it's same list of apps. i don't know try fix problem. i've tried closing down app before changing location, restarting emulator... didn't help. i've been stuck on few days now, appreciate / suggestions.

Dynamically calling JSON data using jQuery & HTML5 data-* -

i'm working expressionengine , have converted channel entries json, works nicely. what trying populate sweet alert 2 overlay information specific json objects using id stored in data-* attribute. here example of json: var director_45 = { "title": "andy h", "entry_id": 45, } and if simple jquery alert this, returns name: alert(director_45.title) however, if in jquery: $('.trigger-director').on('click', function() { var director_id = $(this).data('director'); var director = 'director_' + director_id; alert(director.title); }); with html fire it: <div class="col-xs-6 col-md-3"> <div class="director-box"> <img src="/images/made/images/uploads/images/andy_400_300_c1.jpg" class="img-responsive" width="400" height="300" alt="" /> <h3>andy h</h3> <p>director</p> <a ...

Sending email by using java applications -

i added mail.jar , activation.jar class path dont know how use them. want send mail application. you can use following library: https://github.com/cloudrail/cloudrail-si-java-sdk you can send email choosing between sendgrid , mailjet. example: email mailjet = new mailjet(null, "clientid", "clientsecret"); mailjet.sendemail("fromemail", "fromname", toaddresses, "subject", "textbody", "htmlbody", ccaddresses, bccaddresses);

java - JPA: left join without @OneToMany annotations -

i have onetomany relationship in db don't want hibernate manages directly. this relationships translations, dto represents translated registry: @entity @table(name = "my_table") public class mytable { @id @column(name = "id", nullable = false, unique = true) private integer id; @transient private string lang; @transient private string text; // getters , setters ... } @entity @table(name = "my_table_translation") public class mytabletranslation { @id @column(name = "id", nullable = false, unique = false) private integer id; @id @column(name = "lang", nullable = false, unique = false, length = 2) private string lang; @column(name = "text", nullable = false, unique = false, length = 200) private string text; // getters , setters ... } i want have specific findall(string lang) method lang parameter, , use specification criteria build...

point of sale - how to set more than one timer in verifone vx520 -

i want set timer inputting key , 1 timer turning light off use first timer set , can't set more 1 timer , second timer didn't work. i use code below int timer1, timer2; long events; timer1 = set_timer(8000, evt_timer); timer2 = set_timer(5000, evt_timer); while(1){ events = wait_event(); if(events & evt_kbd){ clr_timer(timer1); break; } else if (events & evt_timer) { printf("time_out"); break; } while(1){ events = wait_event(); if(events & evt_kbd){ clr_timer(timer2); break; } else if (events & evt_timer) { printf("time_out2"); break; } } you need use different event mask (evt_timer) if want capture them different events. tricky thing need careful use because may trigger other actions. these events defined in svc.h (note mask long , long defined being 32 bits, don't have left after standard events used). the news set_timer returns id (that's timer1 , timer2 in code). can use svc_ticks api determine timer ...

c - if global variable have default external linkage then why can't we access it directly in another file? -

i have gone through following questions: global variable in c static or not? are global variables extern default or equivalent declaring variable extern in global? above links describe if define global variable in 1 file , haven't specified extern keyword accessible in source file because of translation unit. now have file1.c in have defined following global variable , function: int testvariable; void testfunction() { printf ("value of testvariable %d \n", testvariable); } in file2.c have following code void main() { testvariable = 40; testfunction(); } now getting error: 'testvariable' undeclared (first use in function ) -- why? note: both files used in same program using makefile. as per understanding both function , global variable have default external linkage. function can use directly it's name in file variable can't why? can 1 have idea? edit: from below answer idea in case of function old compiler gu...

Unable to connect OpenShift mysql db using java code even after creating different users in users table -

i trying connect mysql created in "openshift" platform through java code. my connect establishment like, con = drivermanager.getconnection("jdbc:mysql://127.3.175.2:3306/sivam", "root", "root"); i getting below error while running code, java.sql.sqlexception: access denied user 'root'@'localhost' (using password: yes) i did below step after googling, create user 'root'@'%' identified '***'; grant privileges on * . * 'root'@'%' identified '***' grant option max_queries_per_hour 0 max_connections_per_hour 0 max_updates_per_hour 0 max_user_connections 0 ; grant privileges on `root\_%` . * 'root'@'%'; but still getting same error. also don't know why ip address '127.3.175.2:3306' replaced 'localhost' in error message. may duplicate question searched , tried nothing worked out me.

algorithm - Different Data sets for classification and timeseries analysis? -

i'm new predictive analytics , want analyze data timeseries , classification algorithms. have prepare data sets myself, wanted ask if have create different datasets each analysis? if so, there rules can follow? thank in advance short answer: no, can build time series data , use classification long answer!: time series model of data representation integrate time or time periods. can build time series data , label it, can classify model different class , use classification algorithm predict classes. it's read classification articles improve sight. notice different between classification , regression. classification used discreet values , regression used continuous values: https://math.stackexchange.com/questions/141381/regression-vs-classification also time series might become advance concept in situation. it's not such easy task in problem. there statistical concepts(e.g arma and...) must use in order , efficient data mining task. if familiar r, good: ...

javascript - Change next div display - input value -

i'm trying hide/show div depending on checkbox, can't make work. i've seen many examples, tutorials, couldn't adapt them case. seems there lot of ways that. here part of code: <div id="layer-control"> <p>selectionnez les couches pour les afficher sur la carte.</p> <div id="reciprocite"> <nav id='filter-group-reci' class='filter-group-reci'></nav> <div id='recipro-polygon' class='legend' style="display:none;">> <div><span style='background-color: #e6d94c' 'opacity:0.45'></span>gpv (adhérent urne)</div> <div><span style='background-color: #010492' 'opacity:0.45'></span>gprmv (adhérent urne)</div> <div><span style='background-color: #179201' 'opacity:0.45'></span>eh3vv (adhérent urne)</...

lua - torch: what is the structure for tensors of different sizes? -

table? inserting big tensors table not efficient, not possible because of memory in case. works fine, it's ugly: local s_ = 0 s_ = s_ + 1; local x_py_1 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) s_ = s_ + 1; local x_py_2 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) s_ = s_ + 1; local x_py_3 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) s_ = s_ + 1; local x_py_4 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) s_ = s_ + 1; local x_py_5 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) s_ = s_ + 1; local x_py_6 = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[s_])) x_py = {x_py_1, x_py_2, x_py_3, x_py_4, x_py_5, x_py_6} show code.. please you x_py = {x_py_1, x_py_2, x_py_3, x_py_4, x_py_5, x_py_6} i, v in ipairs(x_py) v = fromfile(('%s/x_py_%.2f.bin'):format(data_dir, scales[i-1])) end simply using table, want it?

adding specific database data to an excel file using VB.NET -

Image
i want add data excel file, have established connection database , pulled information need stored procedure using ssms. i have added columns based on information need, of rows static data here code: private sub exceloutput_click(byval sender system.object, byval e system.eventargs) handles exceloutput.click dim xlapp excel.application dim xlworkbook excel.workbook dim xlworksheet excel.worksheet dim xlrange excel.range dim misvalue object = system.reflection.missing.value dim rnum random = new random xlapp = new excel.application xlworkbook = xlapp.workbooks.add(misvalue) xlworksheet = xlworkbook.sheets("sheet1") xlrange = xlworksheet.usedrange xlworksheet .range("a1").value = "col1" .range("b1").value = "col2" .range("c1").value = "col3" .range("d1").value = "col4" .range("e1").value = "col5" .range("f1").value = "col6...

android - Performance improvements to tint menu icons -

Image
i want tint menu icons, visible ones 1 color , ones in overflow menu different color. wrote following code: final menubuilder builder = getmenubuilder(menu); if (builder != null) { builder.flagactionitems(); final arraylist<menuitemimpl> items = builder.getvisibleitems(); (int = 0, size = items.size(); < size; ++i) { final menuitemimpl item = items.get(i); final drawable icon = item.geticon(); if (icon != null) { final drawable mutate = icon.mutate(); if (item.isactionbutton()) { mutate.setcolorfilter(actionitemcolor, porterduff.mode.src_atop); } else { mutate.setcolorfilter(color, porterduff.mode.src_atop); } item.seticon(mutate); } } } this code works not pleased performance, since started using vector drawables. here measurement of 3 vector icons, thee icons...

asp.net - Required DataAnnotations needs BeginForm to fire validation in MVC5 -

is necessary write , place controls inside @using (html.beginform()) { // html elements , html helpers. } while using [required] dataannotations ? i facing strange issue in mvc5 based application. problem have used 1 property named e.g "credit" in model , datatype of property integer , set[required] dataannotations above property. but haven't used begin form. in case validation doesn't fire. whereas if write beginform validation works. so, necessary place html elements & html helpers inside beginform validate controls ? thanks -nimesh. if want client-side validation work, yes form controls etc. need within <form> tag (as generated html.beginform helper). server-side validation still work regardless of this. like commenter above, question why want have controls outside form tag in first place. if plan submit data using ajax, it's better semantic design use form tag, because it's clear data items belong together, , ...

python - How to rotate a figure in all directions in matplotlib -

Image
i trying rotate figure horizontally in python. mouse able rotate through 1 degree of freedom being able spin figure, example can @ momement: these movements vertical. able rotate figure in directions, example: this allow me put figure on side etc. @ moment cannot this, can rotate along 1 degree of freedom. here code: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot plt mpl_toolkits.mplot3d.art3d import poly3dcollection import numpy np import math fig = plt.figure() ax = fig.gca(projection='3d') nphi,nz= 13, 101 r=1 phi = np.linspace(0,360, nphi)/180.0*np.pi z= np.linspace(0,350,nz) cols=[] verts2 = [] in range(len(phi)-1): cp0= r*np.cos(phi[i]) cp1= r*np.cos(phi[i+1]) sp0= r*np.sin(phi[i]) sp1= r*np.sin(phi[i+1]) j in range(len(z)-1): z0=z[j] z1=z[j+1] verts=[] verts.append((cp0, sp0, z0)) verts.append((cp1, sp1, z0)) verts.append((cp1, sp1, z1)) verts.append((cp0, s...

javascript - Grunt connect-php not found, is it installed? -

i have problem when running grunt serve . says: local npm module "connect-php" not found. installed? all other grunt plugins have been installing work fine. , can see plugin map connect-php in node_modules map i'm supposed to. does problem can be? thanks. this part added in beginning of gruntfile. var phpmiddleware = require('connect-php'); this part added within grunt.initconfig connect: { options: { debug: true, livereload: true, port: 8000, base: '<%= config.destination %>', }, rules: [ {from: '(^((?!css|html|js|php|img|font|\/$).)*$)', to: '$1.html'}, ], dev: { options: { middleware: function(connect, options) { var middlewares = []; var directory = options.directory || options.base[options.base.length -1]; if (!array.isarray(options.base)) { options.base = [options.base]; } middleware...

Using SES SDK to send email from python 2.7 on Lambda -

i trying build lambda function using python 2.7 ( using boto3). need use aws sdk trigger ses email. sending to, email_subject, email_body arguments function. function in turn should use aws access key id , aws secrete access key have permissions trigger emails verified domain , verified email id. i looking way specify aws credentials - import boto3 client = boto3.client('ses') ..... < how mention credentials before calling send_email function ? > response = client.send_email( ...... )

c++ - Sorting both ID and 2 sets of values using STL containers -

Image
i need suggestion use stl containers in best possible way sort 3 sets of data 1. id (integer) 2. first value (string) 3. second value (string) an example of data structure below: i want use map sorted @ time of insert , no need execute sorting algorithm separately. since id can repeat must multimap, , each data of column linked each other rows change in order sort keeping same values attached id. sorting id , value ok, how sort 2 values multimap can take 1 value. thinking multimap of multimap or struct of data structure , stl containers. want make simple possible. need suggestion on how can achieved. thanks! having map or set makes sense if , if going many insert/erase operations it. if data structure static, storing vector , sorting once way more effective. said, if understand question correctly, think don't need map, multiset. typedef pair<int, pair<string, string>> mydatatype; set<mydatatype> myset; here, operator < of pair take...

javascript - How to use $scope.$watch on TypeScript -

i want watch element binding component. value may change(in component) because makes asynchronous call (promise). until in js use $scope.$watch , when binding element change has callback , can continue value of element. example of js: $scope.$watch('myctrl.mylayout', function (newval, oldval) { console.log('layout is:'); console.log(_this.mylayout); }); angular.module('blocks.ui') .component('myform', { templateurl: 'app/blocks/ui/form.html', controller: myform, controlleras: 'myctrl', bindings: { mylayout: '=' } }); the question how implement same thing using "clean" typescript syntax (i know can inject $scope , implement $scope.$watch on typescript in same way). thanks. the solution using typescript & set private _mylayout:any; public mylayout() { return this._mylayout; } public s...

java - Is this code implements 'Factory Pattern', factory methods, both or none? -

although subject has been discussed many times, still find myself confused it. i have simple code sample: public class fruitfactory { public static apple getapple() { return new apple(); } public static banana getbanana() { return new banana(); } public static orange getorange() { return new orange(); } } which factory type code is? , proper writing of factory methods ? the factory pattern definition is: create object without exposing creation logic client if expose client of creation complexity example below, bad factory implementation? public static orange getorange(string weight, string size,) { return new orange(weight, size); } as said, factory merely abstraction object creation implementation intentionally encapsulated behind factory's public interface. factory not have class, not have package -- different languages achieve encapsulation of state , behavioral details differently (consider clos...

c# - Can I replace SLAB one-method-per-event with types? -

examples slab tend this: mycompanyeventsource.log.scalingrequestsubmitted( request.rolename, request.instancecount, context.rulename, context.currentinstancecount); i don't have edit mycompanyeventsource every time add new event type. don't logger available staticly. i'd rather have this: _logger.log(new scalingrequestsubmittedevent(request, context)); i know can roll own logging, before dismiss slab entirely, i'd know if i'm being unfair. there no way things this _logger.log(new scalingrequestsubmittedevent(request, context)); and have change logger time wish add new type of event, change information level or keyword. writing of own wrapper eventsource way achieve desired functionality.

javascript - Why won't window.location.href work on error pages? -

i developing google chrome extension, , if user goes site doesn't exist, thiswebsitedoesnotexist.com, want extension redirect them page set me. not talking sites give 404 errors. mean sites dns server address cannot found, google chrome gives it's standard error page. i tried using window.location.href = *link* , doesn't change webpage. how can around this? in advance. why won't window.location.href work on error pages? because, in fact, being shown document data: url internal error pages, despite address bar showing intended address. can verify devtools inspecting window.location in error page. data: urls are not scriptable chrome extensions : no host permission allows inject content scripts them. therefore, attempts programmatically inject content script changes window.location.href (or console.log ) fail due missing permissions, , match patterns content scripts in manifest won't apply. how can around this? you can use chrome....

wpf - Button style does not apply to button in disabled state -

i have defined default button style in app.xaml: <style targettype="button"> <setter property="margin" value="4"></setter> <setter property="horizontalalignment" value="stretch"/> </style> i see margin not work when button in disabled state. disabled state handled binding listbox.selecteditem property. <button click="buttonopen_click" content="connect"> <button.style> <style> <style.triggers> <datatrigger binding ="{binding elementname=listboxaddress, path=selectedindex}" value="-1"> <setter property="button.isenabled" value="false"/> </datatrigger> </style.triggers> ...