Posts

Showing posts from June, 2012

google apps script - SELECT or Filter from JSON(?) Array -

i have call large json data set. has multiple items , each item has multiple pieces of information. want output 1 item's single piece of information. need filter down information 1 item or use select statement such might in sql. tried following, receive error: error: typeerror: cannot find function filter in object [object object]. (line 28, file "gwspidy api") . can't life of me figure out how boil data down 1 item. hard test code in google apps scripting. function test3(itemid) { var myurl = "http://www.gw2spidy.com/api/v0.9/json/all-items/all"; var jsondata = urlfetchapp.fetch(myurl); var jsonstring = jsondata.getcontenttext(); var jsonarray = json.parse(jsonstring).result; var jsonfilter = jsonarray.filter(function(itemid,jsonarray){if(jsonarray.data_id.match(itemid)) {return itemid;}}); var adjustedvalue = (jsonfilter.min_sale_unit_price / 100); return adjustedvalue; } also, secondary question regards cache service. asked previou...

java - find out the log value of a number from input -

i have edittext field users input. user can enter values ten digit number.when clicking on button, need show log [ mathematics log ] value of number in double precision. that showned below. if input xxxxxxxxxx [ consider number ] the output must yy.yy. package com.example.logvalue; import android.os.bundle; import android.app.activity; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class main extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); edittext edit = (edittext) findviewbyid(r.id.edittext1); final int noo = integer.parseint(edit.gettext().tostring()); button b1 = (button) findviewbyid(r.id.button1); b1.setonclicklistener(new onclicklistener() { public void onclick(view arg0) { toast.mak...

optimization - Slightly different loops in python / Minimize code -

i want minify rows of code. have 2 loops difference 2 lines. possible (functions or classes) change lines in each occasion? 2 loops are: cursor = '' while true: data = api_like_query(id,cursor) #more code in data['data']: ids_likes += i['id']+' , ' #more code and cursor = '' while true: data = api_com_query(id,cursor) #more code in data['data']: ids_likes += i['from']['id']+' , ' #more code more code same chunk of code used. difference in function call (line 3) , different dictionary object in line 6. you can create function quite easily: def do_stuff(api_func, get_data_func): cursor = '' while true: data = api_func(id, cursor) #more code in data['data']: ids_likes += get_data_func(i) + ', ' #more code then first loop can reproduced with: do_stuff(api_like_query, l...

java - Robot class - If a Button Is Pressed? -

i have read , understood how robot class in java works. thing ask, how press , release mouse button inside if statement. example make click if (and right after) space button pressed/released. use code: try { robot robot = new robot(); if (/*insert statement here*/) { try { robot.mousepress(inputevent.button1_mask); robot.mouserelease(inputevent.button1_mask); } catch (interruptedexception ex) {} } } catch (awtexception e) {} unfortunately, there isn't way directly control hardware (well, in fact there is , have use jni/jna), means can't check if key pressed. you can use keybindings bind space key action, when spacebar pressed set flag true , when it's released set flag false . in order use solution, application has gui application, won't work console applications. action pressedaction = new abstractaction() { public void actionperformed(actionevent e) { spacebarpressed = true; } }; action releasedaction = ne...

cmd - Removing N rows of multiple CSV and then Merging them -

i have folder multiple (dozens) csv files, , need merge them in bigger csv, removing first n rows of each individual file, , wanted in bulk operation. i've seen here solutions "more" command, use have run once each small csv, , that's want avoid - have process daily. to merge csvs, can use (all csvs in same folder): copy *.csv alldata.csv is there similar approach, wildcards or that, remove first n rows of csvs? btw i'm running windows, can install programs if necessary. this super easy in autohotkey . assuming want skip first 7 rows, script this: (untested...) n = 7 loop, *.csv { tooltip, reading %a_loopfilename% loop, read, %a_loopfilename% { if (a_index<=n) continue fileappend, %a_loopreadline%`n, alldata.csv } } tooltip, msgbox, done

c# - Develop a custom authentication and authorization system in consistence with web form application -

Image
i creating new asp.net mvc 4 application (actually first mvc application) part of previous asp.net web forms application. have never used asp.net inbuilt authentication methods in of project. new mvc 4 app published on sub-domain of previous app. login done previous app. return url should provided mvc app return current page if not logged in. however, new user registration, account recovery options developed in previous web forms application , don't want replicate them in new mvc application. a cookie token token number issued web form application on event of successful login shared domain *.maindomain.com . now want merge own token validation method asp.net inbuilt methods can make use of authorize , other security related options in new mvc application. in previous application have developed custom user validation system in following way. first, have following related sql server tables and following classes public class token { public static uint generatet...

Systrace on Android 4.3 -

i'm trying measure performance attributes of app through systrace using new trace api introduced in jb 4.3. idea similar use of traceview method profiling, i.e. can measure specific code section using trace.beginsection , trace.endsection . however, when run systrace through python script provided in android tools, don't see relating sections specified above calls. am missing something? correct way of accessing systrace output? see in documentation trace calls "writes trace events system trace buffer", have no idea how access trace buffer. any appreciated. you have provide additional argument systrace command: -app=pkgname (or -a pkgname ) where, pkgname package name app manifest. it's name see in ps output (which possibly more relevant, since that's it's matching against). there example here .

Google script : cannot access e.user on edit change -

the following algorithm: make form in script editor, create script function: function displayuser(e){ logger.log(e.user); logger.log(e.user.getemail()); } create trigger runs displayuser after event from spreadsheet on edit . edit spreadsheet of form the logging output displays: undefined the execution transcript says: execution failed: typeerror: cannot call method "getemail" of undefined. (line 3, file "code") however, google documentation specifies e.user : always returns user object, representing owner of spreadsheet it's not case here e.user undefined. i used command before new access right management system of google, , worked fine - returned information owner of spreadsheet. did make mistake? you're right, doesn't return owner of ss. when renamed onedit() , working simple trigger return effective user of sheet guess that's not need ;-) - never used before cannot confirm worked before ...

asp.net mvc - LINQ to SQL - Filtering the dataset between two nested collections -

i have mvc 3 project in visual studio c#. have linq sql query works fine , following example listed elsewhere on stackoverflow: comparing 2 lists using linq sql i have been able reduce results 2 nested collections match. bit of code did trick (example link above): var anydesiredskills = canidateskills.any( c => desiredskills.select( ds => ds.skillid ).contains( c.skillid ) ); i've adapted successfully, need able filter records using more 1 condition. wondering if able adapt above show how include more 1 condition? to give background on goal is: a search page can select number of contacts each contact added search criteria may/may not have 'role' assigned. if role present should factored in query. results returned based on dynamic criteria. thanks in advance , :o) it sounds you're looking like: var desiredskillids = desiredskills.select(_=>_.skillid).tolist(); var matchingcontacts = contact in contacts contact.role == null...

c# - 401 Unauthorized error web api mvc windows authentication -

Image
i getting 401 unauthorized error . web service written in mvc . in iis configured use windows authentication. below screen shot of fiddler when hit url browser gives me popup window enter user name , password. how can avoid popup window? i calling web api window service. i suspect 2 web services may hosted on same server. in case, problem may caused loopback check. in order test, try referencing service without using qualified domain name , see if works. if does, use following steps specify host names on local computer. method 1: specify host names (preferred method if ntlm authentication desired) ( http://support.microsoft.com/kb/896861 ) to specify host names mapped loopback address , can connect web sites on computer, follow these steps: set disablestrictnamechecking registry entry 1. more information how this, click following article number view article in microsoft knowledge base: 281308 connecting smb share on windows 2000-based computer or windows serve...

How to structure a booking system in ruby on rails -

my goal create reservation system in ruby(v=1.9.3p231) on rails (v=3.2.13). should reservation system hotel. should able let create rooms , perform reservations rooms. of course need valdidations if room reserved. after many hours of trying out stuff, think structur failing. please give me hints, how set reservation-system? tried 2 different ways: 1. created search-form. showed me available room, don't know how specific requests. how use time period (arrival - depature). 2. tried directly reservation (that means booking , validation in one). problem here have no idea how create correct databases , relations. anybody draft layout of project? or tell me how many controllers needed. thanks in advance.

sql - How to use a total of a computed column as a value in another query? -

background :- have scenario find out value of items have quoted on projects have been named preferred supplier , value of items not named for. the tables have @ disposal dba.lead -> dba.a_quotelne columns decide whether items specified or not : "dba"."a_quotelne"."altlineref" if altlineref = 0 not named, if = 1 have been named. first line of each group of items contains 1 or 0. rest null. example "leadno" "lead_desc" "lineno" "calc_value" "altlineref" "calc_groupingref" 1 canary wharf 1 10 0 1000 1 canary wharf 2 16 null 1000 1 canary wharf 3 12 null 1000 1 canary wharf 4 12 1 1001 1 canary wharf 5 13 ...

c++ - Use throw_with_nested and catch nested exception -

i std::throw_with_nested in c++11 since emulates java's printstacktrace() right curious how catch nested exception, example: void f() { try { throw someexception(); } catch( ... ) { std::throw_with_nested( std::runtime_error( "inside f()" ) ); } } void g() { try { f(); } catch( someexception & e ) { // want catch someexception here, not std::runtime_error, :( // } } previously, thought std::throw_with_nested generates new exception multiply derived 2 exceptions (std::runtime_error , someexception) after reading online tutorial, encapsulates someexception within std::exception_ptr , it's probabaly why canonot catch it. then realized can fix using std::rethrow_if_nested( e ) above case 2 level easy handle thinking more general situation 10 level folded , don't want write std::rethrow_if_nested 10 times handle it. any suggestions appreciated. unwrapping std::nested_exception readily acc...

iphone - Do something when audio stops -

im wondering of how make app aware of when audio stops. have 30 minute audio recorded thats triggered when hit play button. play button changed pause button. pause button switch play button when audio complete. using avaudioplayer. how do this? thanks! the avaudioplayerdelegate contains method called audioplayerdidfinishplaying:successfully: . override method , put play/pause button login in there. something this: in .h #import <uikit/uikit.h> #import "avfoundation/avaudioplayer.h" @interface viewcontroller : uiviewcontroller<avaudioplayerdelegate> @end in .m @implementation viewcontroller{ avaudioplayer *_player; } - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. _player.delegate = self; } -(void)audioplayerdidfinishplaying:(avaudioplayer *)player successfully:(bool)flag{ //show play button } @end more info on avaudioplayerdelegate here

asp.net - Page Load only partially fires in production -

i have .aspx file .aspx.vb code behind page working fine in visual studio 2010 not in production. most disturbing page_load (non postback) working of lines. here code protected sub page_load(byval sender object, byval e system.eventargs) handles me.load dim shortages_filter string = "" if not ispostback ' next 4 lines work in localhost, don't work in production alert_label.text = "not postback" shortages_filter += "(num_short_qty > 0) " ddl_shortages_list.items.insert(0, new listitem("shortages list filter", "1=1")) ddl_shortages_list.items.insert(1, new listitem("show shortages list", shortages_filter)) ' next 6 lines work in both environments pref_datasource.filterparameters.add("user_name_param", replace(system.web.httpcontext.current.request.servervariables("logon_user"), "boumatic\", "")) pref_dat...

html - Flexbox: Justify content: flex-end -

i have problems implementing justify content using flexbox. want language , social media bar floating right in flex container. i'm using chrome, have -webkit prefixes in code snippet. doing wrong? according w3c spec , chrome dev tools, approach should correct, maybe i'm wrong. thanks in advance replies. code snippet: html: <div id="upbar"> <div id="languagepanel"> <ul> <li><a href="#">eng</a></li> <li><a href="#">ger</a></li> <li><a href="#">fr</a></li> </ul> </div> <div id="media"> <ul> <li><a href="#">fb</a></li> <li><a href="#">mail</a></li> </ul> </div> ...

Adding new columns in Django models -

this question has answer here: altering database tables in django 8 answers i have created sample django application multiple models within , populated data. now, need add new column 1 of models? here concerns? what happen if syncdb after adding column model , alter table , add new column? or create new table after deleting columns? is there better way tackle issue? syncdb not work altering database tables. here the documentation (readup on : syncdb not alter existing tables) a clean way achieve use 3rd party tool such django south handle migrations (handle alter table scripts in case) you. here step step tutorial on south, , here official documentation on south

what if I don't want to return anything in jquery ajax call? -

i calling ajax function $.ajax({ url: $.grails.createlink('class', 'action'), data: {id: id1}, async: false }); so calling grails method here def action = { } now @ end of action method if don't return js error 'sorry, error occurred' explicitly specified ' render "" ' @ end of action method. is there way avoid render? if don't return anything, grails try , render view grails-app/views/controller/action.gsp i expect doesn't exist, you'll 404 you can add empty view, render blank template, or doing (the shortest option)

sql - Java DB / Derby - white space in table name - how to escape? -

java db / derby - white space in table (column) name - how escape? in mysql database escaped `` (grave accent), if trying execute query (java db) like: create table `etc etc` (id int primary key, title varchar(12)) i error: java.sql.sqlsyntaxerrorexception: lexical error @ line 1, column 14. encountered: "`" (96), after : "". is there solution? edited: thanks comprehensive answers indeed. found interesting thing (java db): it ok create table this: create table "etc etc" (id int primary key, title varchar(12)) and later results: select * "etc etc" but if create table (without white space , quotes): create table etc_etc (id int primary key, title varchar(12)) and later results (with double quotes, example, don't needed): select * "etc_etc" i error: java.sql.sqlsyntaxerrorexception: table/view 'etc_etc' not exist. so conclusion if quotes used while creating table (it not importan...

amazon web services - How to setup Cloudera Hadoop Cluster on EC2 - S3 or EBS Instances? -

how setup cloudera hadoop cluster on ec2 - s3 or ebs instances? have cloudera manager on 1 of ec2 instance has ebs storage. when start creating hadoop cluster cloudera manager starts creating new ec2 instances per number of node specify. request instance issue generates "instance store" instances. how can provide existing instances has ebs or s3 storage? any idea? this design: why cloudera manager prefer instance store-backed on ebs-backed amis? although ebs volumes offer persistent storage, network-attached , charge per i/o request, not suitable hadoop deployments. if wish experiment ebs-backed instances, can use custom ebs ami. source

vb.net - Cast(Of ?) from UIElement -

in silverlight custom controls in the uielementcollection of stackpanel . want list of them specific value. there divelements in container. returns nothing when know have 1 or more. know can make simple loop , cast types inline, want better linq , cast(of tresult) . attempt @ casting: dim mylist = trycast(spdivs.children.where(function(o) directcast(o, divelement).elementparent bcomm).cast(of divelement)(), list(of divelement)) the problem can't cast list(of divelement) . collection uielementcollection , not list(of t) . you build new list, though. can simplified using oftype instead of casting manually: dim mylist = spdivs.children.oftype(of divelement)() .where(function(o) o.elementparent bcomm) .tolist()

javascript - Is it possible to fix lower right corner of div to screen w.r.t scroll up/down -

i want make div vertically expand when scroll down , vertically contract when scroll such lower right corner approximately maintain same position on browser screen. #resizable { position:relative; float:left; width: 300px; height: 200px; padding: 0.7em; top:8px; left:2px; word-wrap: break-word;} div need relative , adjustable align outer text wrap around it. $(function() { $( "#resizable" ).resizable();}); http://jsfiddle.net/eyasq/1/ i able without fixed positioning using bit of javascript: http://jsfiddle.net/eyasq/5/ $(document).scroll(function() { var top = $(document).scrolltop(); $("#resizable").css("margintop", top); }); the scroll event listener update top margin of #resizable div whenever page scrolled. div appear stay in place text reflow around it. effect little unusual, seems match requirements.

c# - Microsoft SpeechSynthesizer (TTS) Voice Crackle -

when using microsoft speechsynthesizer voices crackle, fuzy... // initialize new instance of speechsynthesizer. speechsynthesizer synth = new speechsynthesizer(); // configure audio output. synth.setoutputtodefaultaudiodevice(); // speak string. synth.speak("this example demonstrates basic use of speech synthesizer"); i assume related cpu usage. happend on powerfull computer too. there best practices or workaroud ? adjust rate downwards, until crackling disappears.

visual studio 2012 - Team foundation error Could not load file or assembly Microsoft.Practices.EnterpriseLibrary.Common -

i trying edit build definition of 1 of builds on visual studio (specifically, changing password). finished , press ctrl+s following error: team foundation error could not load file or assembly 'microsoft.practices.enterpriselibrary.common, version=5.0.414.0, culture=neutral, publickeytoken=31bf2856ad364e35' or 1 of dependencies. system cannot find file specified. i have looked build, dev , production servers , can see file , correct version (5.0.414.0). idea going wrong here? this issue entirely visual studio on local machine, not tfs. apparently when edit build definition, team explorer 2010 assumes you're doing open solution. still not know why not find assembly when in bin\debug directory, there go. the solution simple closing , re-opening visual studio. able edit , save definition new parameter , promote production appropriately.

javascript - Why are these two jQuery functions both not firing on click? -

okay, have 2 jquery functions. 1 of them simple explode effect on div. other function enhances explode effect sending particles in circle around div. when click on div both functions set, fire explode effect , not function debris on site. something strange in jsfiddle debris working , not explode, on site explode effect working not debris. here jsfiddle example: jsfiddle.net/fyb98/3/ note : i'm using same jquery version both site , jsfiddle example, that's jquery-1.9.1. this code <style> .debris { display: none; position: absolute; width: 28px; height: 28px; background-color: #ff00ff; opacity: 1.0; overflow: hidden; border-radius: 8px; } #bubble { position:absolute; background-color: #ff0000; left:150px; top:150px; width:32px; height:32px; border-radius: 8px; z-index: 9; } </style> <div id="content"> <div id="bubble"></div> <div id="dummy_debris" class="d...

java - Redundant methods across several unit tests/classes -

say in main code, you've got this: myclass.java public class myclass { public list<obj1> create(list<obja> list) { return (new myclasscreator()).create(list); } // similar methods other crud operations } myclasscreator.java public class myclasscreator { obj1maker obj1maker = new obj1maker(); public list<obj1> create(list<obja> list) { list<obj1> converted = new list<obj1>(); for(obja obja : list) converted.add(obj1maker.convert(obja)); return converted; } } obj1maker.java public class obj1maker { public obj1 convert(obja obja) { obj1 obj1 = new obj1(); obj1.setprop(formatobjaproperty(obja)); return obj1; } private string formatobjaproperty(obja obja) { // obja prop , manipulation on } } assume unit test obj1maker done, , involves method makeobjamock() mocks complex object a. my questions: for unit testing ...

java ee - removing project name from j2ee web application URL -

i have web dynamic project in eclipse , index.html in webapps folder, able access : http://localhost:8080/javatest i want access application : http://localhost:8080 i tried changing context-root "/" right click on project->properties->web project settings, on http://localhost:8080/ getting requested resource not found, , application still running on http://localhost:8080/javatest . this web.xml : <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="webapp_id" version="2.5"> <display-name>javatest</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome...

c# - asp.net Label cannot ever be modified from code-behind -

i have panel/updatepanel contains asp.net label. seems under no circumstances whatsoever text field of control can changed. code: <asp:panel runat="server" id="panel1" width="100%"> <asp:updatepanel runat="server" id="updroutegroup" updatemode="conditional"> <triggers> <asp:postbacktrigger controlid="btndisableonhold" /> </triggers> <contenttemplate> <asp:panel id="pnlimpexcel" runat="server" > <div style="width:100%"> <table colspan="0" width="100%" cellpadding="0" cellspacing="0"> <tr> <th colspan="3"> on hold music </th> </tr> <tr style="height:10px"></tr> <tr> <td a...

oracle - How do I generate combinations based on column values in SQL? (Is this even possible?) -

i'm trying make new column in table contents based off values of existing pair of columns. if have table like(id not primary key) id | value | new column(the column want) 1 a:apple 1 b a:orange 2 apple b:apple 2 orange b:orange im novice sql, insight here helpful. btw, im using oracle if matters. additional details: im looking pair values:values based on fact id's dont match assuming want values id1 paired values id2, can cross-join table itself, filtered on id: select t1.value ||':'|| t2.value my_table t1 cross join my_table t2 t1.id = 1 , t2.id = 2; sql fiddle .

python - Getting HTML to linebreak in django admin's display -

Image
i have django display the code doing is: class purchaseorder(models.model): product = models.manytomanyfield('product', null =true) def get_products(self): return "\n".join([p.products p in self.product.all()]) class product(models.model): products = models.charfield(max_length=256, null =true) def __unicode__(self): return self.products views.py: class purchaseorderadmin(admin.modeladmin): fields = ['product'] list_display = ('get_products') so i've attempted this: from django.utils.html import format_html def get_products(self): return format_html(" <p> </p>").join([p.products p in self.product.all()]) however, it's still not returning in html. or rather, way want in image you need set field allow tags html show in admin list display: class purchaseorder(models.model): product = models.manytomanyfield('product', null =true) de...

matplotlib - flow streamlines over topography by streamplot -

i trying show flow streamlines in x-z cross-section, cutting through mountain streamplot in matplotlib. realized streamplot accepts fixed coordinated. instance, each x need different z-vectors (due topography or surface elevation), requires 2d arrays x , z. there way use streamplot changing coordinates (like have quiver , contour )?

html - jQuery - Sidebar that slides in, and keep the window width -

i've been trying figure out i've not managed yet.. i'm asking help! what want is: when user clicks button sidebar either shown or hidden. content should follow, slide same direction sidebar, , user should not able see y overflow. this want do: http://mikedidthis-pierre.tumblr.com/ thanks in advance! cheers create button toggle menu: var menuenabled = false; $("button").click(function() { if (menuenabled) { $("#left").css("display", "none"); $("#content").css("margin-left", "0"); menuenabled = false; } else { $("#left").css("display", "block"); $("#content").css("margin-left", "200px"); menuenabled = true; } }); full demo here: http://jsfiddle.net/ywrsb/4/

c++ - Qt 5.1 QML property through Threads -

for purpose of resolution, i've created testapp repeat same problem have. i'm porting software qt 4.8 qt 5.1. my first program multithreaded, , working smoothly qml, provided classes thread safe. message : qobject::connect: no such slot testapp::run() in ..\threadingtest\main.cpp:21 qqmlengine: illegal attempt connect testapp(0x29cfb8) in different thread qml engine qqmlengine(0x2f3e0f8). this code reproduce error : main.cpp : #include <qtgui/qguiapplication> #include <qqmlcontext> #include <qthread> #include "qtquick2applicationviewer.h" #include "testapp.h" int main(int argc, char *argv[]) { int out; qguiapplication app(argc, argv); qtquick2applicationviewer viewer; testapp * testapp = new testapp(); qthread * testappthread; testappthread = new qthread(); qobject::connect(testappthread, signal(started()), testapp, slot(run())); testapp->movetothread(testappthread); testappthr...

testing - XML test data for large text element? -

we need build test data complex nested xml schema (xsd). tried xmlspy, have following situation. here our .xsd piece.-------------------------- <xsd:sequence> <xsd:element name="explanation" type="explanationtype" minoccurs="0"/> </xsd:sequence> xsd type definition ------------------ <xsd:simpletype name="explanationtype"> <xsd:annotation> <xsd:documentation>a note field allows 9000 characters</xsd:documentation> </xsd:annotation> <xsd:restriction base="texttype"> <xsd:maxlength value="9000"/> </xsd:restriction> </xsd:simpletype> generated test xml via xmlspy <explanation>!</explanation> even though element defined 9000 length, have 1 character (!). how 9000 length string such **<explanation>xxxxxxxxxxxxxxxxxxx ……………………………(9000 length)<...

Python Pandas - Remove values from first dataframe if not in second dataframe -

i have user/item data recommender. i'm splitting test , train data, , need sure new users or items in test data omitted before evaluating recommender. approach works small datasets, when gets big, takes ever. there better way this? # test set removing users or items not in train te = pd.dataframe({'user': [1,2,3,1,6,1], 'item':[16,12,19,15,13,12]}) tr = pd.dataframe({'user': [1,2,3,4,5], 'item':[11,12,13,14,15]}) print "training_______" print tr print "\ntesting_______" print te # using 2 joins , selecting proper indices, 'new' members of test set removed b = pd.merge( pd.merge(te,tr, on='user', suffixes=['', '_d']) , tr, on='item', suffixes=['', '_d'])[['user', 'item']] print "\nsolution_______" print b gives: training_______ item user 0 11 1 1 12 2 2 13 3 3 14 4 4 15 5 testing_______ item user ...

sql - Simplifying UNION query to use a single SELECT -

the data: i have sqlite table following example rows: +-------------+----------------+-----------------+ | id | groupid | selected | +-------------+----------------+-----------------+ | 1 | -1 | 0 | | 2 | 2 | 0 | | 3 | 2 | 1 | | 4 | 5 | 0 | +-------------+----------------+-----------------+ it's pretty simple, if groupid less 0, it's single element, else it's in group (even if groupid not referencing of id s. the query: i want filter every element groupid less 0 , not selected plus every first element each group. table, id s: 1, 2 , 4. the current solution union : select * (select * elements (groupid < 0 , selected = 0 ) union select * elements groupid >= 0 group groupid) the goal: i want change query use single select statement. single statement can use anything, aggregate ...

c++ - findContours, contourArea give errors with nested contours. "Assertion failed", "input array is not a valid matrix" -

Image
i trying find largest contour in binarized image. judging this question , this tutorial think trivial, , agree. when run code on the image below though, produces errors. note 2x2 dot in upper left hand corner, should count 1 contour. mat img = imread("problem.png", cv_load_image_grayscale); vector<vector<point>> contourvector; findcontours(img, contourvector, cv_retr_list, cv_chain_approx_none); //findcontours(img, contourvector, cv_retr_external, cv_chain_approx_none); // alternative mode int biggest = 0; double biggestcontourarea = contourarea(contourvector[biggest]); (int = 1; != contourvector.size(); ++i){ if ( (contourarea(contourvector[i])) > biggestcontourarea) { biggest = i; biggestcontourarea = contourarea(contourvector[biggest]); } } img = scalar(0,0,0); drawcontours(img, contourvector, biggest, scalar(255,255,255), cv_filled ); imshow("largest contour", img); waitkey(0); if mode cv_retr_list used, error @ = 3, altho...

How to check for redundant combinations in a python dictionary -

i have following python dictionary tuples keys , values: {(a, 1): (b, 2), (c, 3): (d, 4), (b, 2): (a, 1), (d, 4): (c, 3), } how unique set of combinations between keys , values? such (a,1):(b,2) appears, not (b,2):(a,1) ? d = {('a', 1): ('b', 2), ('c', 3): ('d', 4), ('b', 2): ('a', 1), ('d', 4): ('c', 3), } >>> dict(set(frozenset(item) item in d.items())) {('a', 1): ('b', 2), ('d', 4): ('c', 3)} this works converting each key/value pair in dictionary set. important because pair (a, b) , set([a, b]) equal set([b, a]) . perfect if take of key/value sets , add them set, eliminate of duplicates. can't set type because isn't hashable, use frozenset instead. built-in dict() function can accept iterable of key/value pairs argument, can pass in our set of key/value pairs , work expected. a great point made in comments causing is...

build - Maven plugin inheritance from pluginManagement -

there i have parent pom.xml defines the default configuration maven-ear-plugin <pluginmanagement> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-ear-plugin</artifactid> <version>2.8</version> <configuration> <modules> <jarmodule> <groupid>com.test</groupid> <artifactid>artifact1</artifactid> </jarmodule> <jarmodule> <groupid>com.test</groupid> <artifactid>artifact2</artifactid> </jarmodule> </modules> </configuration> </plugin> </plugins> </pluginmanagement> in child pom, defined maven-ear-p...

android - View and SurfaceView, which one is better? -

this question has answer here: difference between surfaceview , view? 7 answers what difference between view , surfaceview? 1 should used getting better , fast results? why surfaceholder used in surfaceview? a surfaceview behaves view. if need draw static component (such textviews) should use view. a surfaceview must used if need draw view several times (such in video player, game, animation , on), surfaceholder can draw view in off-screen canvas , post drawn in surfaceview (also called double-buffering) it's usefull if want draw in thread.

Windows Phone 8: XML Read issue -

okay im looking @ xml document ( http://dev.virtualearth.net/rest/v1/locations/53.8100,-1.5500?o=xml&key=# ) its getting downloaded app correctly keep getting error here lang = resultelements.element("resourcesets") _ .element("resourceset") _ .element("resources") _ .element("location") _ .element("address") _ .descendants("postalcode").value.tostring() anybody know why? the reason you're getting null reference exception because didn't handle namespace in xml document: <response xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1"> there's 3 namespaces, 2 of them assigned prefixes. 1 w...

Regex collection groups in C# when using an OR -

if have following code: regex xp = new regex(@"(\*\*)(.+?)\*\*|(\*)([^\*]+)\*"); string text = @"*hello* **world**"; matchcollection r_matches = xp.matches(text); foreach (match m in r_matches) { console.writeline(m.groups[1].tostring()); console.writeline(m.groups[3].tostring()); } // outputs: // '' // '*' // '**' // '' how can run above regular expression , have result of first collection either side of or appear in same place? (ie. .groups[1] returns either ** or _ , gather isn't how regexes in c# work achievable? , if how?) as 1 of commenters said, can use named groups this. .net more flexible of other regex flavors in allows use same name in different parts of regex, no restrictions. regex: @"(?<delim>\*\*)(?<content>.+?)\*\*|(?<delim>\*)(?<content>[^*]+)\*" ...you can extract parts interest this: foreach (match m in r_matches) { console.writeline(...

how i can return json in rest web service developed in java -

from server sending normal json data, on client expecting jsonp. response server not jsonp , browser throw exception syntax wrong. can explain me how have using java mi web service type restful if client expects jsonp, that's server needs send. how have server send jsonp depends on type of server use. if use jersey example, can use answer question: returning jsonp jersey

html5 - css styles work in id, but not in class -

i trying apply styles div. div unique in width, padding , other attributes, there many other divs in site same border-radius , opacity styles, (but different widths paddings etc) want use class. find if list attributes under div id, works perfectly, if list under #selector , others under .selector, class selector styles not applied. know why. can't done or error in code? thank you!! here code doesn't work: html: <section id="container"> <div id="gallery" class="outline">this problem div</div> </section> css: div#gallery { display:inline-block; margin:0 auto; max-width:100%; text-align:center; width:100%; } .outline { background: #212121; -moz-border-radius:0.5em; -webkit-border-radius:0.5em; border-radius:0.5em; opacity:0.75; filter:alpha(opacity=7.5); }

vendor prefix - Why can't I combine ::selection and ::-moz-selection in one CSS rule? -

this question has answer here: why isn't possible combine vendor-specific pseudo-elements/classes 1 rule set? 2 answers i'm big fan of using ::selection , ::-moz-selection spruce website bit - hate default blue , white colours! however, find 1 little thing bugs me: can't put ::selection , ::-moz-selection in same css rule, this: ::selection, ::-moz-selection { background:#8a1920; color:#ffff; } jsfiddle link i find quite annoying, because means if want change background colour (or other selection style) have edit 2 separate rules. violates policy follow religiously: d.r.y. ( don't repeat yourself ). i tested in chrome 28, chrome canary 30, firefox 22, firefox 23, ie 9 , ie 10 , yield same result. what's going wrong here? if must remain separate, there way have them join further on? like: .selected { background:#8a1920...

error handling - Why Node.js stop working? -

i installed node.js on server , it's working. stops after while error: events.js:77 throw er; // unhandled 'error' event ^ error: connection lost: server closed connection. @ protocol.end (/var/www/node/node_modules/mysql/lib/protocol/protocol.js:73:13) @ socket.onend (stream.js:79:10) @ socket.eventemitter.emit (events.js:122:20) @ _stream_readable.js:910:16 @ process._tickcallback (node.js:373:11) error: forever detected script exited code: 8 error: forever restarting script 14 time the run node.js on port 8000 socket.io , node-mysql , mc . the file path events.js /node/lib/events.js . if use forever can run continuously error still comes up. it's restart script. not best solution (better nothing, maybe worst solution). i'm gonna give try uncaughtexception still not best solution. code: process.on('uncaughtexception', function (err) { console.log('caught exception: ' + err); }); ple...

Minified jQuery redirecting to non-minified jquery from Google CDN -

i loading minified jquery script google cdn @ //ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js however, when load page on browser, according chrome developer tools, looks though standard jquery (non-minified) file being loaded. why happening? jquery trying load image not exist (css/images/ui-bg_highlight-soft_100_eeeeee_1x100.png) it's more awesome reindenting , reformating code. the secret javascript source map , enables developers link minified file original source debugger able display original ungarbled code. technique detailed here : http://devtoolsecrets.com/secret/debugging-use-javascript-source-maps.html if go network panel, you'll see file loaded minified one, , if @ header of file, contains source map declaration : /*! jquery v1.10.2 | (c) 2005, 2013 jquery foundation, inc. | jquery.org/license //@ sourcemappingurl=jquery.min.map */

Typescript 0.9.1 no option to keep comments set to off -

i've upgraded 0.9.1 has found (besides having find-replace : bool : boolean) comments copied on generated javascript? i want have suppressed cannot find option turn off in web essentials options. the flag called --removecomments in command-line compiler. if @ possible, stop using web essentials typescript features. these have been extremely problematic in past (e.g. spawning 1 copy of tsc.exe per .ts file in solution) , being removed in future versions of web essentials. can use typescript .targets file , msbuild task instead now.

javascript - Associate a string with a function name -

i have text input want enable users call functions from. essentially want tie strings functions when user types 'command' prefaced backslash corresponding function called. right example's sake can type /name , followed value , set name property of user object value user gives. so how 20 or 'commands'? http://jsfiddle.net/k7sht/5/ jquery: $('#textcommand').on('keypress', function(e) { if(e.keycode==13) { sendconsole(); } }); var user = {}; var sendconsole = function() { value = $('#textcommand').val(); if (value.substring(0,5) === "/name") { user.name = value.substring(6,20); alert(user.name); } else { $('body').append("<span>unknown command: "+value+"</span><br />") $('#textcommand').val(""); } } html: <input id="textcommand" type="text"><br/...

Confused with jQuery show/hide for images -

i have 7 images lined on 1 of pages. have show/hide functionality working shows odd images "odd" button , shows images "even" button. way works if click on odd button, shows odd. , vise versa ones. however, if odd images shown , click on button, want them shown, adds them shown. if nothing shown, clicking on button should show images? same thing odd images. but if images shown, clicking should show images , hide odd ... clicking odd should show odd , hide even. i hope makes sense. not sure how work. need conditional statement? don't know check for. here working code, not how want work. <script> $(function () { $("#evenbutton").click(function () { $("img").show("slow"); $("img:even").show("slow"); }); }) </script> <script> $(function () { $("#oddbutton").click(function () { $("img").show("slow"); $("img:...

How to specify *one* tab as field separator in AWK? -

the default white-space field separators, such tab when using fs = "\t" , in awk either 1 or many. therefore, if want read in tab separated file null values in columns (other last), skips on them. example: 1 "\t" 2 "\t" "" "\t" 4 "\t" 5 $3 refer 4 , not null "" though there 2 tabs. what should can specify field separator 1 tab only, $4 refer 4 , not 5 ? echo '1 "\t" 2 "\t" "" "\t" 4 "\t" 5' | awk -f"\t" '{print "$3="$3 , "$4="$4}' output $3=" "" " $4=" 4 " so can remove dbl-quotes in original string, , get echo '1\t2\t\t4\t5' | awk -f"\t" '{print "$3="$3 , "$4="$4}' output2 $3= $4=4 you're right, default fs white space, caveat space , tab char next each other, qualify 1 fs instance. use "\t" fs,...

autoresizingmask - iOS: Using auto resize mask to keep UIView at bottom of phone, no matter the screen size -

Image
i've attached screenshot of color view have positioned @ bottom of screen using auto resize mask. i've tried every combination of resize masks can think of, when change simulated metric's size 3.5 or 4 inch, doesn't move. :( what doing wrong? possible auto resizing masks? edit attached image me anchoring bottom well. what want like: the fixed i-beam (the vertical "strut") @ bottom says "keep distance bottom constant" (i.e. stay pegged @ bottom). lack of up-down arrow (the "spring") says "don't change height superview's height changes." the other three, horizontal components optional: left , right i-beams (struts) "if go between landscape , portrait, keep left , right distances pegged are" , left , right arrow in middle (the spring) says "and let change width superview gets wider or narrower." this fix 3.5" vs 4.0" problem. should handle different widths (e.g. la...

XML Schema Validation failing for derived type -

i know whats type of xsd attribute defined xsd simpletype , below schema failing validation because of that. please take loot @ this, schema validator tools throwing error @ "*" demarcated region saying base attributes type not derived correctly..not sure if correct structure define...i have no business model aroud , trying play different options of restrictions , extensions here.. <xsd:complextype name="comptype_simplecontent"> <xsd:simplecontent> <xsd:restriction base="aaa"> <xsd:attribute name="aaa_attr" *type="xsd:anysimpletype"*></xsd:attribute> </xsd:restriction> </xsd:simplecontent> </xsd:complextype> <xsd:complextype name="aaa" block="extension"> <xsd:simplecontent> <xsd:extension base="xsd:integer"> <xsd:attribute name="aaa_attr"> ...