Posts

Showing posts from January, 2012

tkinter - Direct entry in the SpinBox -

consider simple code: from tkinter import * root = tk() def update_label(): my_label.config(text = my_var.get()) my_label = label(root, text = "?") my_label.pack() my_var = intvar() spinbox(root, from_ = 1, = 10, textvariable = my_var, command = update_label).pack() root.mainloop() the documentation @ new mexico tech states that: the user can enter values directly, treating widget if entry. however if enter value directly in spinbox above code, not trigger command callback. further, can enter value in spinbox widget despite fact have restricted -from , _to values between 1 , 10. my questions: can direct entry in spinbox triggers command callback ? can restrict value can entered directly within 1 , 10 ? you can add trace my_var can called everytime value changes. little more information, see: what arguments tkinter variable trace method callbacks? you can data validation using validate , validatecommand attributes of spinb

R - multiple nested loops inferno -

i want create list of matrices 3 vectors, sd_vec strictly positive: z_vec <- c(qnorm(0.90), qnorm(0.95), qnorm(0.975)) # 95% ci, 90% ci, 80% ci me_vec <- c(0.50, 0.25, 0.10, 0.05) sd_vec <- rnorm(n = 9, 0.8, 0.4) sd_vec[which(sd_vec <= 0)] <- 0.1 my question two-fold: how can generalize loops 1 matrix multiple matrices? can create matrices stepwise (2 levels of nesting), indexing breaks down when nest 3 levels. how can avoid for-loops altogether (in spirit of this answer )? welcome answers sapply() , etc. here example of attempt: new_n <- matrix(na, 3,4) for(i in seq_along(z_vec)){ for(j in seq_along(me_vec)){ new_n[i, j] <- ((z_vec[i] * sd_vec[1]) /me_vec[j])^2 } } new_n # [,1] [,2] [,3] [,4] # [1,] 2.45 9.82 61.4 245 # [2,] 4.04 16.17 101.1 404 # [3,] 5.74 22.96 143.5 574 then indexing failure: new_n <- vector("list", length = length(sd_vec)) for(k in seq_along(sd_vec)){ for(i in seq_along(z_vec)){

plotting only selected class from multiple CSV files in R (ggplot) -

let's have imported 2(or more) csv files having similar columns. let's have "a", "b" , "class" columns in each of csv files values different. let's suppose dataset in 1 csv file is: a b class 1 2 2 3 b 4 1 3 7 c 4 5 ..... let's 2nd csvs dataset be: a b class 10 20 20 10 c 40 10 b 30 17 14 15 ..... and on other csvs.. initially have made ggplots individual csv files using "a" , "b". want plot csv files in single plot using 1 class @ time i.e., let's want plot class csvs in single plot. i did plot files in single plot want plot class wise.. can 1 tell how can thing? just join csvs 1 dataframe , subset , plot? e.g. csv1 <- read.csv(...) csv2 <- read.csv(...) bigcsv <- rbind(csv1, csv2) library(ggplot2) ggplot(subset(bigscv, class == 'a'), aes(...)) + ... the key subset(bigcsv, class=='a') . you can use rbind.fill rbind big list of datafra

ruby - Watir Error: unable to locate element -

i writing web scraper watir , can't seem figure out error i'm getting. have array of text links on page, when loop through , click on link , go back, breaks. here html code <div> <a href="wherever">text here</a> </div> <div> <a href="wherever">text here 2</a> </div> <div> <a href="wherever">text here 3</a> </div> and here watir code browser = watir::browser.new browser.goto 'some_valid_site.com' array = ['text here', 'text here 2', 'text here 3'] array.each |text| browser.link(:text, text).click browser.back end it executes first link correctly, when comes second link, following error message: ruby-2.2.2@gemset/gems/watir-webdriver-0.8.0/lib/watir-webdriver/elements/element.rb:533: in `assert_element_found': unable locate element, using {:element=>#<selenium::webdriver::element:0x1bef61e9aef3c36a id="{ad

django - Create fields based on another model -

i have user model fields. of them require feedback, correctly filled (if not, specific message displayed on user profile). the problem is, how represent 'invalid' fields in database. idea create model (call extuser) onetoonefield user. , extuser should have same fields' names user, types boolean, determining whether field filled in correctly. example, if user has field called email: email = models.charfield(max_length=100) extuser have following field: email = models.booleanfield(default=false) here's problem approach. how supposed create fields in extuser? of course can create them manually, breaking of dry principle, , i'm not going that. question is, can add fields model dynamically, , have them in database (so assume require called before migrate)? i have django 1.8 , don't want use external modules/libraries. if has idea of how represent data in database, please add comment, not reply - question creating fields dynamically. you ne

ios - Core Data Migration: Possible to delete old store except for a few specific objects? -

the new version of our app complete redo, different in every way. reading migration, think i'd fall heavy camp (added relationships), i'm not sure need of data , not sure have chops complex migration. being said, realized users can save favorite stories , i'd preserve of data (but not whole nsmo story entity different now). that's need, few pieces of data few nsmos. i've got detection setup -isconfiguration:compatiblewithstoremetadata: , have deleted old store -removeitematurl: wort case scenario, there way fetch couple things before delete , build new objects? yes, can stand old store old model , fetch data out of , manually insert new stack. delete old store afterwards. actual workflow be: new model separate file new store separate file (new file name) then: look old file name on disk. if doesn't exist stand stack stand old stack. stand new stack. copy data old stack new stack. save new stack. release old stack , delete old

How can i read a local txt file using javascript and winJs? -

hi read txt file using javascript. saw lot of ways still not clear me. file read simple path "c:/javascript/file.txt. my file new york california miami i every element (by line) , put var. any appreciate, thank's

node.js - Only the first task run while chaining tasks on package.json -

i have these scripts part of package.json: "scripts": { "clean": "rm -rf lib", "watch-js": "./node_modules/.bin/babel src -d lib --experimental -w", "dev-server": "node lib/server/webpack", "server": "nodemon lib/server/server", "start": "npm run watch-js & npm run dev-server & npm run server", "build": "npm run clean && ./node_modules/.bin/babel src -d lib --experimental" } when running 'npm run start', first task in chain running (npm run watch-js). when running each 1 of these chained tasks simultaneously work. also when swapping places between tasks, first task 1 run. how can make of chained tasks under "start" run?

running java main class using subprocess.Popen in python -

i want execute java main class main.java python using subprocess.popen() . main.java takes 3 args. i wonder how it? example have helloworld.java class: public class helloworld { public static void main(string[] args) { system.out.println("hello world!" + args[0]); } } i tried call in python using command: print (subprocess.popen('java c:/users/testing/hello.main sayhello', shell=true, stdout=subprocess.pipe).stdout.read()) where 'sayhello' string args want pass in. said error: not find or load main class c:.users.testing.hello.main thanks you may run java file extension .class following way: java your.path.main arg1 arg2 where, java - command, runs java interpreter your.path.main - full name of class (without .class ) arg1 arg2 - arguments (written spaces or between " ) further, when formatted line, transmits in subprocess.popen() argument. subprocess.popen('java your.path.main arg

Selenium Steam community market listings python -

i trying write program open steam community page , read first value in table of prices. stuff afterwards. not want use steam api if anyones suggestion know how select first id in table because change , cannot define set id , trying locate class proving difficult. my code can open webpage not issue example of item community market. <div class="market_listing_right_cell market_listing_their_price"> <span class="market_table_value"> <span class="market_listing_price market_listing_price_with_fee"></span> <span class="market_listing_price market_listing_price_without_fee"></span> from understand, working this page . to list of prices, iterate on results containing in div elements market_listing_row class , text of elements market_listing_their_price class: for result in driver.find_elements_by_css_selector("div.market_listing_row"): price = result.find_element_by_css

android - Data in ListFragment if added multiple time every time it re-opened -

i have listfragment inside dialogfragment, passing list data listfragment activity->dialogfragment->listfragment. issue every time open dialog same instance of activity list shown list data getting appended drawn list. here snapshot of code working with. class testactivity extends fragmentactivity { public void onbuttonclick() { testdialogfragment.newinstance(data).show(getsupportfragmentmanager(), null); } } class testdialogfragment extends dialogfragment { data data; public static testdialogfragment newinstance(data data) { final testdialogfragment fragment = new testdialogfragment(); // add input fragment argument return fragment; } @override public view oncreateview(final layoutinflater inflater, final viewgroup container, final bundle savedinstancestate) { final view dialogview = inflater.inflate(r.layout.fragment_test_dialog, container, false); // read data fragment argument return dialog

javascript - Programatically enable iOS keyboard on orientation change -

i'm building website responsive design goes between mobile , desktop view if viewport big/small enough. because of this, have 2 search bars (mobile , desktop). on ipad, want able rotate screen while focusing on 1 search bar, , other focused on automatically, including keyboard. here's have going in script right now: window.onorientationchange = function() { $('input').css('cursor', 'pointer'); if($('.search-input-mobile').css('display') != 'none' && $('.search-input').css('display') == 'none' && $('input:focus').length > 0 && math.abs(window.orientation) != 90) { $('.search-input-mobile').trigger('click'); } else if(math.abs(window.orientation) === 90 && $('input:focus').length > 0 ) { $('.search-input').trigger('click'); } else if($('input:focus

rest - How to fetch email lists from MailChimp RestAPI -

i using mailchimp api 3.0. trying email lists new api , following works fine. http://usxx.api.mailchimp.com/3.0/lists/3399ju772?apikey=xxyy3399ddff87336663-usxx the api key , list id provided fake. using above code gets me list id , related contents. however, tried grab name of list using following code http://usxx.api.mailchimp.com/3.0/lists?fields=lists.name/99uy6633?apikey=xxxyyyzzzxxxeeee-usxx and following error {"type":"http://kb.mailchimp.com/api/error-docs/401-api-key-missing","title":"api key missing","status":401,"detail":"your request did not include api key.","instance":"99hhytt-5444f-453gfgfg-bfgfg4bd-4545ggfg"} is there syntax error? couldn't find syntax in documentation except here i appreciate help. mailchimp api 3.0 has issue if multiple query-parameters provided (at least apikey , exclude_fields or fields ). instead of providing apikey query-

java - JAR, when runs, looks for resource files inside the JAR (itselfe) or outside? -

a java program uses different files, stored under path "src/main/resources/files/files.drl". if export program run-able jar , run jar, these files inside jar or outside in folder src->main->resources->files ? a sample code how these files used java program : drlfilename = "./src/main/resources/files/files.drl"; fileinputstream fis = null; fis = new fileinputstream(drlfilename); kbuilder.add( resourcefactory.newinputstreamresource(fis), resourcetype.drl); how package application doesn't determine find resources in cases. in whatever directory tell in. if specify jar file, using various jar file apis (e.g. java.util.jar.jarfile ), that's program find data. if in os's file system (e.g. using things java.io.fileinputstream ) that's find data. the exception when use classloader::getresource search classpath find specified resource. so, example, if classpath points single jar file, resource looked in jar file. note if use cu

Inserting html content from b.php into a div in the included a.php -

i have 2 files. a.php , b.php . a.php template including in b.php . here contents of a.php : <div id="main"></div> here contents of b.php : <?php include ('/a.php'); ?> <h1>hello</h1> how insert <h1>hello</h1> into <div id="main"></div> ? the reason im asking because have login php file , have form in it. want insert template's main div section. is possible or have copy template , paste login php file? you handle giving template values should inserted placeholders in template. include inherits current scope of location include happens, example you'd $content = "<h1>hello</h1>"; include("a.php"); .. , have echo($content) in a.php . i'd suggest using actual template library make more structured yourself. since include inherits current scope, can wrap in function (or class , call method render template) avoid symbols leak

Agent decision making in repast simphony using java uses a lot of memory -

i building model number of autonomous agents. make decisions on object choose within immediate environment or "neighborhood". retrieving objects, add them list, sort list based on preferences, , choose top choice every iteration . decision determines movement. unfortunately, once population of agents becomes high, program slows down massively. i use compare method (below), relatively short, uses lot of memory, compare objects. wondering if there other methods guys know of might more computationally efficient? class objectcomparator implements comparator <tree> { @override public int compare(object object1, object object2) { return new comparetobuilder() .append(object1.gettype(), object2.gettype()) .append(object2.getdbh(), object1.getdbh()) .append(object1.getdistancefrom(), object2.getdistancefrom()) .append(object2.isideal(), tree1.isideal()).tocomparison(); } } some points may us

linux - bash prevent escaping with echo -

i relatively new linux , trying create tikz figure parsing file. in order read in file $%&-bash script containing following statement echo "\fill[color=blue] ($xp,$zp) circle (5pt);" >> $fout this results in following output ^lill[color=blue] ($xp,$zp) circle (5pt); obviously echo escapes \f , did not find way around it. have tried options "-e" "-n" , have you, have tried kinds of combinations of " ' etc, no avail. i stuck linux, time google didn't (omg=oh google!!!!!!!!). echo should not backslash escapes default, unless -e specified. can try echo -e force turning them off (in case have aliased echo echo -e or something). alternatively, try using single quotes (although think it, don't see how help): echo '\fill[color=blue] ('"$xp,$zp"') circle (5pt);' >> $fout

javascript - AutoScroll to next div after a pause -

basically have website title of page 1 takes entire screen , content below after scroll. wondering if possible make automatically scroll smoothly next div after maybe half second on "title screen". can see talking going on this page . the class name content contactus, made specific class name scrolling called scroll-down. because want use in few different areas, same concept each area. looking @ code, works: $(document).ready(function(){ $('html,body').animate({ scrolltop: $('.portfolio-header').height() }, 1000); }); note using animate() smoothly scroll (in period of 1000 milisecs) , getting height of previous block .portfolio-header in order know number of pixels scroll. and finally, wrap of in .ready() function wait document ready before doing scroll.

What does () mean in JavaScript -

i'm testing invoked function in javascript. found when running below code in chrome, throws uncaught syntaxerror: unexpected token ) function foo(){ console.log(1); }(); i think parser break code 2 parts: function declaration , (); . happen if add 1 between () , turns out won't throw error. so suppose (1); valid expression, means? thanks answer. it immediately-invoked function expression : (function foo(){ console.log(1); })(); // call function here explanation: suppose create function: function foo(){ console.log(1); } now call function do: foo() now if saw gave function name , called it. can call in same line like: (function foo(){ console.log(1); })(); here article can read .

android - How to AutoCompleteTextView into Dialog -

i have problem android program wheere need put autocompletetextview dialog not working. i share code: public class registeractivity extends appcompatactivity { private expandablelistview mylist; private list<convenios> conveniolist; private arraylist<string> convenionames = new arraylist<string>(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_register); } public void cadastrarnovoconvenio(view view) { cadastraconvenio(); } private void cadastraconvenio() { final dialog dialog = new dialog(this); dialog.setcontentview(r.layout.add_new_convenio); final radiogroup tipoconvenio = (radiogroup) dialog.findviewbyid(r.id.rbg); final button save = (button) dialog.findviewbyid(r.id.bt_cadastrar); final button cancel = (button) dialog.findviewbyid(r.id.bt_cancelar); final autocompletetextview conveniotextview = (autocompletetextview) findviewbyi

c++ - Create multiple instances of class & store them in vector<class> -

what i'm trying create multiple instances of class point , access class variables each instance. class point { public: float x, y, z; }; in following main() program, i'm creating single instance of type point , called point_ , pushing same instance multiple times in vector. int main() { std::vector < point > vect; point point_; int num_instances; // user defined (int = 0; < num_instances; i++) { vect.push_back(point_); // (^^^) } } (^^^) here, problem vector of type poin t adding 1 single instance (called point_) manually created. what want based on num_instances input user (say 5), same number (i.e. 5) of instances of type point should created , stored in vector (called vect). in following main() program, i'm creating single instance of type point, called point_ , pushing same instance multiple times in vector. yes creating single instance of type point called point_ . no not pushing same inst

java - PrintWriter not appending content in the right order -

i have list contains objects (whose constructor contains inner object). when i'm trying print list file, go through each object , call object's respective writer methods. public void writer(string file, boolean append) { file path = new file("../opdracht6_2/src/" + file); try { printwriter write = new printwriter(new fileoutputstream(path, append)); (superobject o : this.list) { if (o instanceof object1) { ((subobject1) w).writer1(file); } if (o instanceof object2) { ((subobject3) w).writer2(file); }if (o instanceof object3) { ((subobject3) w).writer3(file); } } write.close(); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } } in object's writer method try first print line says type , call writer method innerobject. after wan

search - How to make google show my website with category layout -

all: i wonder how can make google search result of website formated , list category google itself? called seo optimization? basically want website looks in google search results like enter "google", "github", "stackoverflow" in google search, show categories , search bar thanks ofcourse, comes under seo. called site links, automatically generated google's algorithm depending on traffic various important pages of site. login , contact pages automatically detected if have right seo structure. sub domains listed automatically if have any. in case of stack overflow, shows important pages , subomains such java , python again individual communitites, made google show them in search result. more google site links here

react router - reactjs - Is it possible to have non nested routes -

i'm playing reactjs routes. in examples routes nested, such <route path="/" handler={app} > <route name="about" handler={about} /> <route name="contact" handler={contact} /> </route> is possible have simple non nested routes, below? <route path="/" handler={app} /> <route name="about" handler={about} /> <route name="contact" handler={contact} /> update: var routes = ( <route name="root" handler={root}> <route path="/" handler={home} /> <route path="/home" handler={home} /> <route path="/about" handler={about} /> <route path="/projects" handler={projects} /> <route path="/contact" handler={contact} /> </route> ); strange issues, after updating suggested answer below. name not working anymore path works? h

parsing - Java Httpconnection preprocess url content for jsoup or other parser -

i have program, connects url java httpconnection. inputstream parsed jsoup. problem taking 1 second each url. webpage has 12000 lines of code, need specific area (about 500 lines within div), wondering if preprocess inputstream , handing on part of code jsoup parsing. have 100.000 pages crawl cannot handle within 1 day 1 server. hope kind of preprocessing can lower parsing time sth. 50-150 ms. allready checked jsoup parsing bottleneck , not internet connection / downloading. i appreciate hints. yes, of course solution on right track. but problem - block of code in inputstream start? depends on html document code. if it's quite specific can read stream , throw away bytes not matched start of block. you can read input stream , use indexof or regexp pattern (regex more slower). then prepend <html><body> , append </body></html> extracted string , here have jsoup parse

watchkit - watchOS 1 storyboard crashes in Xcode 7 -

i converting project on xcode 7 , swift 2. had watchkit extension, , allowed xcode convert watchos 2. when go open storyboard, crash. storyboards broken , need manual adjustments? process: xcode [97053] path: /applications/xcode-beta.app/contents/macos/xcode identifier: com.apple.dt.xcode version: 7.0 (8163.8) build info: ideframeworks-8163008000000000~7 code type: x86-64 (native) parent process: ??? [1] responsible: xcode [97053] user id: 504 date/time: 2015-07-16 18:39:19.620 -0400 os version: mac os x 10.10.4 (14e46) report version: 11 anonymous uuid: 56576435-6521-af4c-a27c-f5e11a057a25 sleep/wake uuid: baa76d42-23ac-45b6-a291-6cffb2574157 time awake since boot: 1300000 seconds time since wake: 10000 seconds crashed thread: 0

MySQL row size error -

i can not understand issue. have table under innodb minimum row size, , started getting error when last field in row being filled. last field being 1280 (varchar) field, attempting place 879 characters of data within it. returns: #1118 - row size large (> 8126). changing columns text or blob or using row_format=dynamic or row_format=compressed may help. in current row format, blob prefix of 768 bytes stored inline. ok read , figured had overhead in row, split in two. did taking large section out of front end form talking table, , storing in separate table altogether. modified php handle 2 tables instead of one. made no difference - same error trying fill out same last field same 879 characters in severely shrunken table. so try making table row_format=dynamic - still same result. try row_format=compressed - , yes, still same problem. driving me nuts. what left do? missing? as requested, here table structure: drop table if exists `app_aigprreq`; /*!40101

android - Cordova - Trying to execute a function inside a webview -

i have webview website working in app. i'm trying asking users when hit android button if want leave app. i'm using inappbrowser plugin. here's code. document.addeventlistener("deviceready", ondeviceready, false); // cordova ready function ondeviceready() { navigator.splashscreen.show(); var ref = window.open("http://m.estadao.com.br", "_self", "location=no"); ref.addeventlistener('loadstop', function(){ ref.executescript({ code: document.addeventlistener("backbutton", onbackkeydown, false); function onbackkeydown() { navigator.notification.confirm( "tem certeza que deseja sair?", function(buttonindex){ confirmexit(buttonindex);

html - How to render partial form as a horizontal form in rails 4 -

i have partial (triggered ajax) on main page consists of form. form displayed horizontally rather vertically. have tried such wrapping in <form class="form-inline"> i've tried <%=f.number_field :pointsspend, :class => "checkbox inline"%> , altering css display: inline none of seems work the main form in partial rendered: <div class="row"> <div class="col-md-12"> <%= link_to image_tag("biceps.jpg"),'#', id: 'challengebutton', class: "btn btn-lg btn-primary" %> <div id="challengecentre"></div> </div> </div> the form <%= form_for(@challenge) |f| %> <% if @challenge.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@challenge.errors.count, "error") %> prohibited challenge being saved:</h2> <ul>

sql - Data Warehouse - duplicate dimension members for multiple divisions -

i new data warehousing , ssis, have been tasked populating data warehouse sales transaction records 2 different divisions of parent company. issue...i modifying ssis package populates product (skus) dimension accommodate products pertain 2 divisions , have ended few product names exist in both divisions. need solution accommodate product list each division in same dimension table. possible?? to illustrate: https://www.dropbox.com/s/hkda4n1bfs5o178/capture.jpg?dl=0 where 'widget_3' , 'widget_4' named same in both divisions, not same product. happened named same. imagine common problem, reluctant make changes dimension table schema before consulting first. i working product dimension table has [memberid] primary key , [product] unique non clustered constraint ignore_dup_key = off. first instinct modify table schema change ignore_dup_key on , rely on having [division] attribute populate data in fact table; use [product] , [division] identify [memberid] on upd

Comparing sets in Java; operation does not work as expected in both directions -

having created 2 sets of different sizes, common elements, intention identify elements in each set make different other set. set class in java seemed have method: removeall. did following: import java.util.*; public class helloworld { @suppresswarnings("unchecked") public static void main(string args[]) { // create new set set<string> myset1 = new hashset(); // add elements myset1.add("1"); myset1.add("2"); myset1.add("4"); myset1.add("5"); myset1.add("6"); myset1.add("7"); // print elements of set1 system.out.println("myset1: " + myset1); // create new set set<string> myset2 = new hashset(); // add elements myset2.add("1"); myset2.add("2"); myset2.add("3"); myset2.add("5"); myset2.ad

scala - Play: Run tests with custom GuiceApplicationLoader -

i have customapplicationloader extends guiceapplicationloader in loading environment specific conf file. when run tests in applicationspec values taken environment specific conf files missing supposedly means customapplicationloader hasn't been executed. any idea how pass customapplicationloader on fakeapplication or other approach read values conf files during tests? or shouldn't work out of box? so found out can inject custom guiceapplicationloader passing argument withapplicationloader this: @runwith(classof[junitrunner]) class applicationspec extends specification { "my component" should { "load environment specific conf values loaded in customapplicationloader" in new withapplicationloader(new customapplicationloader) { ... } } }

javascript - node.js regex splitting a string to send to another server -

i'm trying split type of string in node.js send information 1 server another. i'm having trouble getting regular expression work considering kind of stink @ regular expressions in node.js or language @ moment. i'm trying make easier on myself without having bunch of strings replace or split array. so, here's string: ?name!identity@url.url is possible name string without .replace() , .split()? using matching groups: var mystring = "?name!identity@url.url"; var myregexp = /\?(.*?)\!.+?/g; var match = myregexp.exec(mystring); if(match) { alert(match[1]); // name } else { alert("no match"); }

ios - Creating NSDate from Int components -

i have calendar select date: func sacalendardate(calendar: sacalendar!, didselectdate day: int32, month: int32, year: int32) { var date = date.from(year: int(year), month: int(month), day: int(day)) print("\(year) , \(month) , \(day)") let formatter = nsdateformatter() formatter.datestyle = nsdateformatterstyle.mediumstyle formatter.timestyle = nsdateformatterstyle.nostyle let datestring = formatter.stringfromdate(date) buttonselectdates.settitle("\(datestring)", forstate: uicontrolstate.normal) getusers(date) } when feed "date" in method: class func from(#year:int, month:int, day:int) -> nsdate { var c = nsdatecomponents() c.year = year c.month = month c.day = day var gregorian = nscalendar(identifier:nscalendaridentifiergregorian) var date = gregorian!.datefromcomponents(c) return date! } i date 1 day behind: selecteddate: 2015-07-14 22:00:00 +0000 , parameters are: 2015, 7 ,

opencv - HOG Detection training with CvSVM -

i've been looking everywhere, , cannot find tutorials on training hogdescriptor . i'm beginner hog, have used other object detection algorithms before (e.g. cascadeclassifier ). the way see it, have create cvsvm object , run cvsvm::train() , passing in vector of vectors of floats (mat), labels (1 or -1) mat, , cvsvmparams object. confused how convert cvsvm vector of floats required in hogdescriptor::setsvmdetector() . aware can use cvsvm::predict() , doesn't allow me multi-scale detection. there code available pass in trained cvsvm (or possibly original vector of vectors) , vector of floats use train hogdescriptor ? you can build own multiscale detector running cvsvm::predict() on multiple scales of same image assuming fact had same scales in training set.

android - How to use security (Authentication & Authorization) in ASP.NET Web Api -

i developing android application use sql server(database) store application's data. in addition, application use asp web api send , receive xml or json between client , server. i confused how make application authentication securely , how keep user logged in without need keep sending user's credentials in http requests. therefore, need recommendation how secure application , provide me tutorial links if possible. login (username, password shored in basicnamevaluepair) client (here android) access web api controller (perhaps /token if use samples asp.net web api website). if success, access token responsed , save in client (sharedpreference or database) then, need send access token (no need username, password anymore) request other api controllers. of course, https should used here better security. sample codes getting access token (login phase): public static object getaccesstoken(string address, string grant_type, string username, string password) th

python - Computing logarithm -

i must write function computes logarithm of number x relative base b (rounded down if answer not integer). wrote function it's not working def mylog(x, b): result = 1 if b > x : result -= 1 return result elif x == b : return result else : result += 1 b *= result return mylog(x,b) why multiplying base result , changing base? when determine base fits input number, should dividing number base. since division means final number 1 more, add 1 result of recursive call. def mylog(x, b): result = 1 if b > x: result -= 1 return result elif x == b: return result else: x /= b return 1 + mylog(x, b) example: mylog(32, 2): 32/2 = 16, add 1 answer 16/2 = 8, add 1 answer ... answer = 5 some of code unnecessary though, , further edit this: def mylog(x, b): if b > x: return 0 elif x == b:

jQuery Validate unobtrusive - Enable validation for hidden fields -

i use asp.net mvc 5, jquery validate unobtrusive, jquery validate 1.13 version. have searched answer, although problem have solve,but want know method. $.validator.setdefaults({ ignore: [] }); //valid $("#form1").data("validator").settings.ignore = []; //invalid,all input validate invalid $("#form1").data("validator").settings.debug = true;//valid,if use method,debug ture model open, why? if put code in $(document).ready. code useless how enable validation hidden fields 1 form? instead of enabling validation hidden fields , better enable validation ones want. you can assigning class hidden fields want validate , using following code. // add special-hidden class hidden fields want validate. var validator = $("#formid").validate({ rules: rules }); // line basicially tells validator ignore hidden fields apart ones class special-hidden validator.settings.ignore = ':hidden:not([class~=special-hidden])';

hyperlink and bold word text display after form submission with innerhtml with javascript -

i display block of text(based on user input) after form submission using innerhtml. wanted know how make bold hyperlink within text block. text displayed in hidden panel below form. many i'm not sure understood question, but... you can use old html tags (like <b> or <i>) directly innerhtml = ""; without them being stripped.

MySQL Select all where DATETIME field is not NULL -

i having trouble selecting proper values query: select * discounts disclimit > 0 , disclimit >= discredeemed or discexp not null , discexp <= now() discexp datetime field defaults null . i trying select current unexpired discounts database: select * discounts where : the limit > 0 (a limit exists) , limit >= number redeemed an expiration exists (not null) , expiration in future it seems retrieving values datetime field null . appreciated. you need parentheses! try this: select * discounts (disclimit > 0 , disclimit >= discredeemed) or (discexp not null , discexp <= now()) but, question, i'm not sure if or correct. if want meet of following conditions: the limit > 0 (a limit exists) the limit >= number redeemed an expiration exists (not null) the expiration in future you want, this: select * discounts disclimit > 0 , disclimit >= discredeemed , discexp not null , discexp <= now() or, if want

arm - Status of setcontext / getcontext in BSD and Linux -

i using setcontext / getcontext creating coroutines in c. current software implemented armv7 using linux 3.18 kernel. since these apis deprecated, couldn't find proper information regarding development status. have read reimplemented arm deprecated on x86 oses. however, can still find up-to-date man pages freebsd , linux . there aren't warnings or notices regarding use. is reliable choice continue using them ? why still exists in libc ? status in linux kernel 4 ? thanks

How to insert data from one table to another from two oracle database servers with public database link? -

i going insert data table2 table1 , 2 tables in different database, different servers. there public database links both database. in details of public database links, there names of owner, db_link, username , host. i want ask how use public database links insert data table2 table1 , thanks. i have tried like insert table1 select 'xxxx, xxxx, xxxx', columns_from_table2 table2@"db_link" criteria; but prompts out error message of ora-02019: connection description remote database not found 02019. 00000 - "connection description remote database not found" i think not using correct dblink. try , tell me: select * dual@"db_link" select * dba_db_links db_link = "[your_db_link_name]"

javascript - Keep absolute element (dropdown-menu) in viewport or window width -

<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">dropdown <span class="caret"></span></a> <ul class="dropdown-menu menu-multicolumn"> <li class="menu-column"> <ul> <li class="menu-column-title">multi page</li> <li><a href="#">action</a></li> <li><a href="#">another action</a></li> <li><a href="#">something here</a></li> <li><a href="#">separated link</a><

N-Queens in Java using Stacks, Keeps taking the same route after backtracking -

title pretty says all. i've been working on , can't figure out way prevent happening. perhaps way store invalid placements? or how implement way 'resume' last time @ row doesn't pick same value again? ignore while i, debugging. same prints. import java.util.stack; public class nqueens { //***** fill in code here ***** //feel free add additional methods necessary //finds , prints out solutions n-queens problem public static int solve(int n) { //***** fill in code here ***** //scaffolding code stacks.pdf //------------------------------------------------------------------------------------------------------------------ // create empty stack , set current position 0 stack<integer> s = new stack<integer>(); int column = 0; int row = 0; int solutionscount = 0; int = 0; //repeat { //loop current position last position until valid position found //current row while (i < 5){ for(column = 0

java - Finding out when the close button in notepad is clicked -

i need open notepad @ runtime. of processbuilder. processbuilder pb = new processbuilder("notepad.exe" , "file.txt"); pb.start(); after notepad opens, type in stuff , when click close button. want java program recognize , continue rest of program. know thread.sleep(*some long value*) but think program more efficient if recognizes when notepad.exe closes. do :- processbuilder pb = new processbuilder("notepad.exe" , "file.txt"); process pro = pb.start(); int val = pro.waitfor(); with process pro wait complete execution, val should 0 normal termination, according convention. for getting file path : this file.txt created @ current directory. in order current directory path, can use :- file f = new file("."); string path = f.getcanonicalpath();

sql - Oracle scenario -

please me in solving below scenario : i/p name salary ram 200 shyam 900 rabi 700 ram 600 rabi 100 shyam 300 o/p name. salary ram 200 ram 800 shyam 900 shyam 1200 rabi 700 rabi 800 how using oracle sql query ? you seem want cumulative sum: select name, sum(salary) on (partition name order id) cumesalary table t order name; the order by not output is. if ordering important, please more explicit rule ordering. also, assumes have sort of id or creation date specify ordering of table. sql tables represent unordered sets, there no inherent ordering. need column specify ordering.

xml - How do I compare attribute to a lower case value? -

how create filter attribute value lowercase? this works: xmlitem = xml.*.(attribute("name")==propertyname); but throwing error: xmlitem = xml.*.(attribute("name").tolowercase()==propertyname); it looks have use tostring() string object , can use tolowercase(): var xmllist:xmllist = xml.*.(attribute("name").tostring().tolowercase()==lowercasepropertyname);

Prevent Notepad++ from highlighting javascript code -

Image
i don't mind syntax coloring, find annoying notepad++ highlights entire blocks of javascript code, dimming them , making difficult read. looks like: as can see shades entire block of javascript purple color. there way prevent happening? go settings > style configurator . from languages list select javascript. go through each option in 'style' list, changing background colour white.

php - Ajax call crash on CodeIgniter - CSRF Error 403 -

i'm trying perform ajax calls within codeigniter. had searched before, when csrf protection active, hash (randomly generated) must submitted each request server. in research found following code hash sent along other data through ajax request: $.ajaxsetup({ data: { arquivo_facil_tk: $.cookie('arquivo_facil_co') } }); so got positive result on first call right after page loaded. attempt second call, error 403. found option of adding code snippet each ajax call make, software performs several calls, becomes unfeasible , rude. how fix this? tried using beforesend event got same error. rather using ajaxsetup include csrf token along data in actual ajax call so: data: {var: value, arquivo_facil_tk: $.cookie('arquivo_facil_co')} or if you're serializing forms simply: data: $(this).serialize() + '&arquivo_facil_tk=' + $.cookie('arquivo_facil_co')

java - IllegalBlockSize Exception When Doing RSA on bytes of Strings -

i trying write rsa encryption , decryption classes in java server client passing strings , forth. have following code classes: public class rsaencryption { public static final string keygenalgorithm = "rsa"; public static final string algorithm = "rsa/ecb/pkcs1padding"; public static keypaircontainer generatekey() { keypairgenerator keygen; keypair key; try { keygen = keypairgenerator.getinstance(keygenalgorithm); keygen.initialize(1024); key = keygen.generatekeypair(); return new keypaircontainer(key.getpublic(), key.getprivate()); } catch (nosuchalgorithmexception e) { e.printstacktrace(); system.out.println("error: no such algorithm"); } return null; } public static string pubkeytostring(publickey key){ byte[] array = key.getencoded(); base64encoder encoder = new base64encoder(); string tempstring = encoder.encode(array); return tempstring; } public sta

javascript - Ember Error while testing: You will need to wrap any code with asynchronous side-effects in a run -

we have app working working add test cases purpose of ci. we have small code tries login process , checking happens after possible login states success, failure, invalid account account locked etc. so tried follwing code. visit('/login') .fillin('#identification', "testuser") .fillin('#password', "testpass") .click('input[type="submit"]') andthen(function(){ ok(!exists('button:contains(sign in)'), '3. login button not displayed when authenticated'); ok(exists('.dropdownmenuoptions li:contains(logout)'), '4. logout button displayed when authenticated'); }); and gives following error in console. ember.debug.js:5162 uncaught error: assertion failed: have turned on testing mode, disabled run-loop's autorun. need wrap code asynchronous side-effects in run this error occurs after click performed. click makes ajax call server , on response route