Posts

Showing posts from August, 2011

android - Hide context menu without disabling text selection -

the goal show custom context menu, on top of selected text. tried clearing menu items in onsupportactionmodestarted: @override public void onsupportactionmodestarted(android.support.v7.view.actionmode mode) { super.onsupportactionmodestarted(mode); mode.getmenu().clear(); mode.getmenu().close(); } but context menu still showing blank background , button , no items inside i tried setting <item name="windowactionmodeoverlay">false</item> apptheme no avail. is there way this? have tried way? @override public void onactionmodestarted(actionmode mode) { super.onactionmodestarted(mode); mode.getmenu().clear(); mode.getmenu().close(); } i have made without support , worked. have not needed: <item name="windowactionmodeoverlay">false</item> remember implement in 1 activity.

html - How to insert a JavaScript variable into Flask url_for() function? -

i have following code in flask template: <div id="cell1"></div> <script> var id="0014"; cell1.innerhtml = '<a href={{url_for('static',filename='+id+'".txt")}}">'+id+'</a>'; </script> i want link render to: http://my_address/static/0014.txt but got this: http://my_address/static/+id+.txt how make js variable id in flask url_for() function work? thanks help! try this: cell1.innerhtml = '<a href={{url_for('static', filename='')}}' + id + '.txt>' + id + '</a>'; url_for() generate link this: .../static/<filename> . if use url_for('static', filename='') , generate link like: .../static/ , can add text after (i.e. + id + '.txt>' ) .

java - mysql-connector strange behaviour in Tomcat -

i trying deploy app tomcat.everything works fine, except expected have error after deleting connector file(mysql-connector-java-5.1.40) web-inf>lib directory, but,surprise, still working without it. so, question if tomcat saving conector elsewhere(i ve searched in tomcat directories , found nothing). start tomcat use startup.bat bin directory of tomcat. simple code mysql db connection: public void jspinit() throws jspexception{ try{ class.forname("com.mysql.jdbc.driver"); con=drivermanager.getconnection("jdbc:mysql://localhost:3306/test","root",""); pst.con.preparestatement("insert employee values(?,?,?)"); } catch(exception e{ e.printstacktrace(); } } if left tomcat running deleted mysql driver jar, tomcat nevertheless have java bytecode loaded in jvm. did restart tomcat when deleted jar? update look for... a copy of jdbc driv...

mysql - Receive ERROR 1235 (42000) when only one Trigger exists. How can I fix this? -

i have been trying following trigger run. delimiter $$ create trigger prevent_value_less_than_6 after insert on t each row begin if exists (select * t numberofpeople <= 5) delete t numberofpeople <= 5; end if; end; $$ i receive following error despite having absolutely no other triggers database. error 1235 (42000) @ line 26: version of mysql doesn't yet support 'multiple triggers same action time , event 1 table' how can fix this?

node.js - Cognito USER_SRP_AUTHENTICATION -

in aws cognito docs, http://docs.aws.amazon.com/awsjavascriptsdk/latest/aws/cognitoidentityserviceprovider.html#initiateauth-property one of supported authentication flow user_srp_auth. when call initiateauth(), get invalidparameterexception: missing required parameter srp_a error. the doc silent how get/generate srp_a method requires. can find how use auth flow? thanks in advance! i had similar problem "admininitiateauth" method. able mine working enabling admin_no_srp_auth in userpool. go userpool > apps > show details , check checkbox "enable sign-in api server-based authentication (admin_no_srp_auth)". once done, use authflowtype.admin_no_srp_auth. // example java implementation... admininitiateauthrequest request = new admininitiateauthrequest(); request.withclientid(client_app_id); // clinet id assigned in userpool request.withuserpoolid(user_pool_id); // id of user pool request.addauthparametersentry("username", use...

sql - Duplicate rows using left join -

suppose have table this: +----+--------+-------------+----------------+--------+ | id | parent | description | numberofthings | number | +----+--------+-------------+----------------+--------+ | | null | | 1 | null | | b | null | b | 3 | null | | c | null | c | 2 | null | +----+--------+-------------+----------------+--------+ and want use numberofthings x create children number of things: +-----+--------+-------------+----------------+--------+ | id | parent | description | numberofthings | number | +-----+--------+-------------+----------------+--------+ | | null | | 1 | null | | b | null | b | 3 | null | | c | null | c | 2 | null | | a-1 | | | 1 | 1 | | b-1 | b | b | 1 | 1 | | c-1 | c | c | 1 | 1 | | b-2 | b | b | 1 | 2 | | c-2 | c | c | ...

java - Making new objects of different classes in a single for loop -

i'm new programming, , stuck. have 5 different classes in project: foo1, foo2, foo3, foo4, , foo5 different, similar things. need create new object of each one, like: foo1 bar1 = new foo1(); foo2 bar2 = new foo2(); foo3 bar3 = new foo3(); , on. sure works, i'm trying find way conserve lot of space if instantiate objects need in single for-loop, or in least put objects want create in single array work out of. can working if same class, not if different. possible? try read polymorphism can use in java. how interfaces , abstract classes works. extends , implements keyword in java , other ... i found these tutorials looks good: tutorialspoint polymorphism oracle polymorphism

Sorting for index values using a binary search function in python -

i being tasked designing python function returns index of given item inside given list. called binary_sort(l, item) l list(unsorted or sorted), , item item you're looking index of. here's have far, can handle sorted lists def binary_search(l, item, issorted=false): templist = list(l) templist.sort() if l == templist: issorted = true = 0 j = len(l)-1 if item in l: while != j + 1: m = (i + j)//2 if l[m] < item: = m + 1 else: j = m - 1 if 0 <= < len(l) , l[i] == item: return(i) else: return(none) how can modify return index of value in unsorted list if given unsorted list , value parameters? binary search (you misnamed - algorithm above not called "binary sort") - requires ordered sequences work. it can't work on unordered sequence, since ordering allows throw away @ least half of items in each search step. on other hand, since allowed use list.sorted metho...

javascript - Split if else statements for code refactoring -

code : show 1 error message on each time. function isvalidfields() { if (!$("#x").val()) { utilsservice.seterrorclass('x'); $scope.validationmessage.xerrormessage = true; } else if (!$("#a").val()) { utilsservice.seterrorclass('a'); $scope.validationmessage.yerrormessage = true; } else if (!$("#b").val()) { utilsservice.seterrorclass('b'); $scope.validationmessage.zgerrormessage = true; } else if (!$("#c").val()) { utilsservice.seterrorclass('c'); $scope.validationmessage.cgerrormessage = true; } else if (!$("#d").val()) { utilsservice.seterrorclass('d'); $scope.validationmessage.dgerrormessage = true; } else if (!$("#e").val()) { utilsservice.seterrorclass('e'); $scope.validati...

C++ Enviromental Variable -

i found simple , easy way incorporate mingw notepad++ issue added environmental variable still throws error 'g++' not recognized internal or external command, operable program or batch file. did add variable wrong or? (i added under path users) %userprofile%\appdata\local\microsoft\windowsapps;c:\mingw\bin; notepad++ code: npp_save cd $(current_directory) cmd /c g++ -ansi -pedantic -wall -w -wconversion -wshadow -wcast-qual -wwrite-strings $(file_name) -o $(name_part).exe & if errorlevel 1 (echo. && echo syntax errors found during compiling.) else ($(name_part).exe)

javascript - Asynchronous functions in Typescript/Angular 2 -

i having trouble when nesting 2 functions. second function executing before first 1 finished. have 2 methods: dologin() { return this.authservice.dologin(); } tologin(){ this.router.navigatebyurl("/secure"); } the first function dologin() takes awhile because of service. how can make second function, tologin() execute after dologin() has finished , returns true (using promises, or callbacks)? i new angular , javascript, please thorough in explanation. cheers! by using promise dologin() { return this.authservice.dologin().then(function(result){ tologin(); }); } you need return promise in this.authservice.dologin()

sql - How to find out if row being referenced changed? -

i've been thinking , looking solution problem don't know how search it. sorry if it's been answered. context i have app has persistence, , data provided rest api. 1 off calls supposed return new stuff, , comparing last time data retrieved time data changed. if changes newer retrieve, if not don't. suppose we're working on schema: company( id, address_id references address( id ), updated_at, ... ) equipment( id, address_id references address( id ), updated_at, ... ) address( id, updated_at, ... ) there trigger updates updated_at column on insert or update. the api response when company , it's referenced address updated , equipment updated: { company:{ info, address:{ info } }, equipment:{ info } } the problem i'm retrieving company or equipment when changes occurred, , i'm retrieving address if company , equipment changed , address changed well. the problem when address changed, because api never return changes. can't return...

firefox - bit-wise operator supported in GLSL ES 3.00 and above only -

i'm trying make function bit position color in glsl. precision highp float; uniform sampler2d utexture0; varying vec2 vtexturecoords; int getbit(float color, int bit){ highp int colorint = int(color); return (colorint >> bit) & 1; } void main(void) { highp vec4 texelcolour = texture2d(utexture0, vec2(vtexturecoords.s, vtexturecoords.t)); if(getbit(texelcolour.r * 255.0, 7) == 1 ){ gl_fragcolor = vec4(0.5, 0.8, 0.5, 0.8); }else{ gl_fragcolor = vec4(0.4, 0.1, 0.0, 0.0); } } chrome , firefox return error error: 0:35: '>>' : bit-wise operator supported in glsl es 3.00 , above error: 0:35: '&' : bit-wise operator supported in glsl es 3.00 , above i'm trying force version in first line of shader, : #version 130 but console return version not supported. is there way create subroutines getbit function ? or settings enable implements bitwize operator in sharder fragment ? thanks reply...

c# - How to change ComboBox SelectedValue programmatically with MVVM -

i have combobox items a, b, c, d, e. how can change selectedvalue of combobox after user selection, if user select list items "a", selectedvalue "d" (as if selected d himself). xaml: <stackpanel orientation="horizontal"> <textbox text="{binding path=name, updatesourcetrigger=propertychanged, mode=twoway}" height="25" width="100" /> <combobox isdropdownopen="{binding isdropdownopen, mode=twoway, updatesourcetrigger=propertychanged}" itemssource="{binding offsetvalues}" selectedvalue="{binding nodecategory, mode=twoway}" height="25" width="100" ishittestvisible="false" background="aliceblue"> <combobox.resources> <sys:double x:key="{x:static systemparameters.verticalscrollbarwidthkey}">0</sys:double> </combobox.resources> ...

updating array based on symbols Ruby -

how 1 update array based on symbols? data = [] string = "hello" if( !data.include? string ) count += 1 data.insert(-1, { label: string, value: count, }) else #logic change count value if string encountered again end i thinking of finding index string lies , delete insert updated values @ index. right approach? just use find match, provided 1 in array. can use select multiple matches. after update count as example taken out of context , contains errors, i've taken liberty make more complete example. data = [] strings = ["hello", "bye", "hello", "hi"] strings.each |string| hash = data.find{ |h| h[:label] == string } if hash.nil? data << {label: string, value: 1} else hash[:value] += 1 end end

ios - How to send events to Firebase Analytics in iMessage extension -

i've been trying send events when user taps on tableview cell firebase analytics through imessage app no avail. using firanalytics.logevent(withname: "\(stickeruniquename)", parameters: nil) i added -firanalyticsdebugenabled scheme i have setup on regular app, works fine , logs event in xcode console can see sent. can't show same imessage extension. i guess i'm eluding possible log events in imessage extension? there other service can track button presses on imessage extension? ok checked next day , events showed in firebase analytics woot! still haven't manage events log in xcode console. problem kinda solved... big take away here firebase analytics work in imessage extensions. takes couple hours show up.

ios - Xcode UI Testing Failure - Computed invalid hit point -

my xcode ui testcode failing error, when test runs on ipad pro 12.9 inch. iphone model , ipad retina, there no error seen. assertion failure: easytvuitests.m:81: ui testing failure - computed invalid hit point (-1.0, -1.3) cell 0x600000377dc0: traits: 8589934592, {{411.0, -1373.0}, {813.3, 106.3}} the failing test code line one: [[app.tables[@"programs"].cells elementboundbyindex:17] tap]; what error mean, , how debug it? here full run error: tap cell wait app idle find cell snapshot accessibility hierarchy com.[hidden] find: descendants matching type table find: elements matching predicate '"programs" in identifiers' find: descendants matching type cell find: element @ index 17 wait app idle synthesise event assertion failure: easytvuitests.m:81: ui testing failure - computed invalid hit point (-1.0, -1.3) cell 0x600000377dc0: traits: 8589934592, {{411.0, -1373.0}, {813.3, 106.3}} that index 17 n...

Paypal integration with Ruby-on-rails proxy -

i have problem paypal integration on website. can tell how set proxy paypal machine can access paypal address? our university server has firewall, , need bypass it. i used ruby-on-rails code site: https://launchschool.com/blog/paypal-payments-with-credit-cards . note: works on development station, doesn't work on production when deploy, because of proxy; using apache2 on production.

python - @asyncio.coroutine vs async def -

with asyncio library i've seen, @asyncio.coroutine def function(): ... and async def function(): ... used interchangeably. is there functional difference between two? yes, there functional differences between native coroutines using async def syntax , generator-based coroutines using asyncio.coroutine decorator. according pep 492 , introduces async def syntax: native coroutine objects not implement __iter__ , __next__ methods. therefore, cannot iterated on or passed iter() , list() , tuple() , other built-ins. cannot used in for..in loop. an attempt use __iter__ or __next__ on native coroutine object result in typeerror . plain generators cannot yield from native coroutines : doing result in typeerror . generator-based coroutines (for asyncio code must decorated @asyncio.coroutine ) can yield from native coroutine objects . inspect.isgenerator() , inspect.isgeneratorfunction() return false native ...

python - How do I measure the length of the scale bar in pixel point? -

scalebar.png how measure length of scale bar in pixel point, white area in picture? from pil import image im = image.open("scalebar.png") width, height = im.size print(width, height) 638 58 scalebar=io.imshow('scalebar.png') profile=np.mean(scalebar[31:34,:],axis=0) pixels=np.arange(1,np.size(profile)+1,1) typeerror: 'axesimage' object not subscriptable plt.plot(pixels,profile) plt.xlabel('pixels') plt.ylabel('intensity'); this trying do. when use imshow('scalebar.png') return handle figure, , not data. can convert image data directly numpy array. from pil import image import numpy np im = image.open("scalebar.png") width, height = im.size print(width, height) scalebar = np.asarray(im) profile = np.mean(scalebar[31:34,:],axis=0) pixels = np.arange(1,np.size(profile)+1,1) plot(pixels, profile)

recyclerview - Could not found method compile() in gradle Android Studio -

i'm new android studio , android development , developing first application. i want use carview , recyclerview display data. according many tutorials on it, need add following dependencies compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+' this how build.gradle is // top-level build file can add configuration options common sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.2' // note: not place application dependencies here; belong // in individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: delete) { delete rootproject.builddir } dependencies { compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+' } but on sync gradle, gives error...

Specflow Add new step to existing feature file -

i new specflow , i've hit strange issue. i have existing specflow feature , step file. want add new step , when shows new step unbound (purple). within visual studio 2015 chose option 'generate step definitions', selected existing step file overwrote file , lost existing steps new 1 added, how append new step without losing existing steps? thank there couple of other alternatives 1 outlined one go 'generate step definitions' dialogue on on there can select steps want generate definitions click 'copy methods clipboard' button rather 'generate', , paste methods existing step file. imho should default option. the other run tests , check output, definition required part of failing test output. option more viable if using continuous test runner ncrunch.

javascript - TDD basics - do I add or replace tests? -

i'm new tdd , working way through this article. it's clear except basic thing seems obvious mention: having run first test (module exists), do code before running next one? keep next test includes results first one? delete original code? or comment out , leave current test uncommented? put way, spec file end long list of tests run every time, or should contain current test? quoting same article linked in question. since don’t have failing test though, won’t write module code. rule is: no module code until there’s failing test. do? i write test —which means thinking again. spec end list of tests run every time check regression errors every additional feature. if adding new feature breaks added before previous tests indicate failing test.

html - Changing div's order with CSS with dynamic height, text vertical align middle -

here's html code: <ul> <li> <div class="imgbox"><img 1></div> <div class="txtbox">text 1</div> </li> <li> <div class="imgbox"><img 2></div> <div class="txtbox">text 2</div> </li> <li> <div class="imgbox"><img 3></div> <div class="txtbox">text 3</div> </li> <li> <div class="imgbox"><img 4></div> <div class="txtbox">text 4</div> </li> <ul> the expected result in desktop is: _____________________ | img 1 | txt 1 | _____________________ | txt 2 | img2 | _____________________ | img 3 | txt 3 | _____________________ | txt 4 | img 4 | _____________________ each block width:50%, images width:100% box, auto height; text in middle of box, display:table-cell; te...

function - Argument existence by assert statement in python -

is there way check existence of argument of function assert statement? def fractional(x) : assert x==none, "argument missing" <---- possible here check? assert type(x) == int, 'x must integer' assert x > 0 , ' x must positive ' output = 1 in range ( 1 , int(x)+1) : output = output*i assert output > 0 , 'output must positive' return output y=3 fractional() <----- argument missing you shouldn't have assert existence of argument explicitly. if argument isn't given when call function, you'll typeerror like: >>> def foo(x): ... pass ... >>> foo() traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: foo() takes 1 argument (0 given) >>> if wanted ensure other properties of argument (you mentioned existence), test properties , raise exceptions if weren't met: >>> def foo(x): ... ...

python 3.x - How do I get the programme to print out the receipt format with the correct subtotal? -

thanks help. want print out orders in format: 85791008 mango-1 £1 3 £3 86139113 strawberries-500g £1.50 2 £3 total cost of order: £6 this code: import csv option='yes' user_orders=[] final_price=0.00 while option=='yes': data=open('product information.csv', 'rt') purchase=csv.reader(data) order=input('please enter gtin-8 code of product purchase: ') row in purchase: field in row: if order in field: quantity=int(input('how of item: ')) final_price=quantity*float(row[2]) + final_price receipt=('{} {} {} {} {}'.format(row[0]+' ', row[1]+' ', str(quantity)+' ', "{:10.2f}".format(float(row[2]))+' ', "{:10.2f}".format(quantity * float(row[2])))) user_orders.append(receipt) print('you have a...

ruby on rails - When is executed the code defined in the class section of the model -

if put in model: class sample < applicationrecord enum level: [:one, :two, :three].map{|e| [e,e]}.to_h this section [:one, :two, :three].map{|e| [e,e]}.to_h will executed once? when model first loaded? or executed multiple times? once, when model loaded. in ruby, class definition code, enum in example method call, , [:one, :two, :three].map{|e| [e,e]}.to_h argument. the end result of calling enum several other methods defined on class, allowing things sample.two? per docs . have read of source code on github if want know how happens.

javascript - Error: TypeError: $(...).dialog is not a function -

i having issue getting dialog work basic functionality. here jquery source imports: <script type="text/javascript" src="scripts/jquery-1.9.1.js"></script> <script type="text/javascript" src="scripts/jquery-ui-1.11.1.js"></script> <script type="text/javascript" src="scripts/json.debug.js"></script> html: <button id="opener">open dialog</button> <div id="dialog1" title="dialog title" hidden="hidden">i'm dialog</div> <script type="text/javascript"> $("#opener").click(function() { $("#dialog1").dialog('open'); }); </script> from posts around seems library import issue. downloaded jquery ui core, widget, mouse , position dependencies. any ideas? be sure insert full version of jquery ui. should init dialog first: $(function () { ...

Any C++/C equivalent function with sparse in MATLAB -

i tried port m code c or cpp . in code there line a = sparse(i,j,ia,nr,nc); which converts row index i , col index j , , data ia sparse matrix a size nr x nc . is there equivalent code c++ or c? an naïve algorithm duplicate result in full matrix is double *a; = malloc(sizeof(double)*nr*nc); memset(a, 0, sizeof(double)); for(k=0; k<size_of_ia; k++) a[i[k]*nc + j[k]] += ia[k]; note if there common indices, value not on overwritten, accumulated. eigen example of c++ math matrix library cobtains sparse matrices. overloads operators make feel built in feature. there many c , c++ matrix libraries. none ship part of std , nor there built in. writing sparse matrix library quite hard; best bet finding pre-written one. recommendation questions off topic

c++ - How to detect XOFF and XON in Linux terminal application -

certain control sequences have special effects in linux, such ctrl-c sends sigint . can handle signals enough, appears ctrl-s (xoff) , ctrl-q (xon) special snowflakes. know effect (to pause input) can disabled in console stty -ixon , , use trickery run command, feels cheap workaround. is there proper way rid these sequences of special effect , actual ascii values ( ^s , ^q ) using system calls? know doable because text editor nano it, life of me can't find it's being handled. tried searching repo "xoff". https://github.com/dtrebbien/nano/tree/master/src use tcgetattr() , tcsetattr() system calls turn off ixon flag on standard input, explained in manual page.

Java: remove a range of indices from a list -

consider linked list of strings got somewhere linkedlist<string> names = getnames(); now, want remove first k elements list. currently, i'll way: for (int = 0 ; < k ; i++) { names.removefirst(); } is there way more efficiently , instead call like: names.removerange(0, k); note prefer not construct whole new list using sublist() , small k values, popping k times more efficient constructing new list maybe : names.sublist(0, k).clear(); this more efficient doesn't release memory according sublist it's view: names.sublist(k, names.size());

geometry - Math Parrallelogram Level Generation -

Image
i developing mobile runner. therefore need platforms allow transition 1 height (2d). given: triangle afb has rectangle alpha, triangle cde has rectangle @ delta, line bc = ef, line ed = ab , height of parralelogram ed(=ab) looking for: af = cd (any of both) i can't find solution. tip: have formula case when can give me parralel line long sides of parrallelogram able work out rest. couldn't find parrall line though. i'll try re-interpretation "planar mechanism" possibly still not right in input description. input: solid fixed triangle @ bottom short perpendicular sides length a , c . top triangle same, rotated 180°, not fixed. triangles connected bars of length b rotationally flexible , fixed giving angle phi . bottom triangle: a=(0,0), f=(c,0), b=(0,a) lower bar: f=(c,0), e=(c,0)+b*(cos(phi), sin(phi)) upper bar: b=(0,a), c=(0,a)+b*(cos(phi), sin(phi)) upper triangle: e=(c,0)+b*(cos(phi), sin(phi)) , d=(c,a)+b*(cos(phi), sin(phi)) ...

javascript - how to get the week number from two start and end custom dates in asp.net/c# -

for example have start date = 05-09-2016(dd-mm-yyyy) , end date = 09-01-2017 and want have week starting 5th sep called week 1 , last week 18 edit: shall giving date , these 2 start , end dates should give me week number. eg. when enter 09-11-2016 should give me week 6 and have acheive without doing hardcoding. uptil have written datetime date = new datetime(2016, 09, 05 ); datetimeformatinfo dfi = datetimeformatinfo.currentinfo; calendar cal = dfi.calendar; console.writeline( (cal.getweekofyear(date, dfi.calendarweekrule, dfi.firstdayofweek))-36); but doesn't work when new year starts .. advice please? tell if can acheive similar using javascript if not acheivable in asp.net/ c# it looks need calculate number of weeks between 2 dates, please give try below: this prints 18 expected. datetime date1 = new datetime(2016, 09, 05); datetime date2 = new datetime(2017, 01, 09); var weeks = math.ceil((date2 - date1).tota...

java - HashMap<String, List<String>> may not contain objects of type 'integer' -

i have written code displaying expandablelistview on android studio. code explandablelistview: public class recipes extends appcompatactivity implementsview.onclicklistener { expandablelistview exp; edittext t; button b; hashmap<string, list<string>> movies_category; list<string> movies_list; expandablelistview exp_list; moviesadapter adapter; protected void oncreate(bundle savedinstancestate) { settheme(r.style.noactionbar); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_recipes); t = (edittext) findviewbyid(r.id.t); b = (button) findviewbyid(r.id.b); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_recipes); exp_list = (expandablelistview) findviewbyid(r.id.exp_list); movies_category = dataprovider.getinfo(); movies_list = new arraylist<string>(movies_category.keyset()); adapter = new moviesadapter(this, movies_category, movies_list); exp_list.setadapte...

Python list object is not callable for a list of integers -

this question has answer here: typeerror: 'list' object not callable while trying access list 7 answers i error: 'list' object not callable... looked around in google , tried every given solution, it's still same. cannot code work. have list of integers, , need give every element different variables. dmy = input('what date? please put in this: 2.11.2016') dmy.strip(".") dmy = [int(x) x in dmy.split('.')] list(dmy) print(dmy) dd = dmy(0) mm = dmy(1) yy = dmy(2) the first part of code working. error while trying give list element variable dmy(0) not work. in books have way? i use python 3.5.2 i see trying do. element in list obtained list[index] format. while trying call list(index) python interpreting function call , hence throwing error: typeerror: 'list' object not callable corrected cod...

c - SDL2 Handling non character key presses as the same natural delay rate as SDL_TextInputEvent -

in sdl2 there event sdl_textinputevent captures input keyboard @ natural rate os configured be. when poll events, it's this: sdl_event event; while (sdl_pollevent(&event)) { switch (event.type) { case sdl_textinput: input_listener.last_key = event.text.text; break; default: break; } } the event.text.text char[32] contains character in utf-8 user inputs in program. great delay fine, if hold down a key wont insert loads of a characters fast possible. however, event doesn't seem capture non-character input pressing enter key or arrow keys. can, however, capture them so: ubyte* states = sdl_getkeyboardstate(null); if (states[sdl_scancode_backspace]) { ... stuff here } however not have os delay, , fire possible. program text editor, it's programmed if game. there game loop, update/rendering methods, etc. meaning check input done every frame. what can non-character input @ same delay rate os configured? there ...

c# - How to call A) a textBox B) And button click event inside a Form(That is created through a class in a button click event) -

this question has answer here: communicate between 2 windows forms in c# 10 answers i created class public static class prompt { public static form showcategorydialog() { form addcategorydialog = new form() { width = 500, height = 150, formborderstyle = formborderstyle.fixeddialog, text = "caption", startposition = formstartposition.centerscreen }; label textlabel = new label() { left = 50, top = 20, text = "asd" }; textbox textbox = new textbox() { left = 50, top = 50, width = 400 }; button confirmation = new button() { text = "ok", left = 350, width = 100, top = 70, dialogresult = dialogresult.ok }; confirmation.click += (sender, e) => { addcategorydialog.close(); }; addcategorydialog.controls.add(textbox);...

c - Printing the value of a 0-initialized array element prints nothing, why? -

i have initialize char array 0's. did like char array[256] = {0}; i wanted check if worked tried testing it #include <stdio.h> int main() { char s[256] = {0}; printf("%c\n", s[10]); return 0; } after compile , run it, command line output shows nothing. what missing ? perhaps initialized array in wrong manner ? tl;dr -- %c character representation. use %d see decimal 0 value. related , c11 , chapter §7.21.6.1, ( emphasis mine ) c          if no l length modifier present, int argument converted unsigned char , and resulting character written. fyi, see list of printable values. that said, hosted environment, int main() should int main(void) , @ least conform standard.

hadoop - Presto failing to query hive table -

on emr created dataset in parquet using spark , storing on s3. able create external table , query using hive when try perform same query using presto obtain error (the part referred changes @ every run). 2016-11-13t13:11:15.165z error remote-task-callback-36 com.facebook.presto.execution.stagestatemachine stage 20161113_131114_00004_yp8y5.1 failed com.facebook.presto.spi.prestoexception: error opening hive split s3://my_bucket/my_table/part-r-00013-b17b4495-f407-49e0-9d15-41bb0b68c605.snappy.parquet (offset=1100508800, length=68781800): null @ com.facebook.presto.hive.parquet.parquethiverecordcursor.createparquetrecordreader(parquethiverecordcursor.java:475) @ com.facebook.presto.hive.parquet.parquethiverecordcursor.<init>(parquethiverecordcursor.java:247) @ com.facebook.presto.hive.parquet.parquetrecordcursorprovider.createhiverecordcursor(parquetrecordcursorprovider.java:96) @ com.facebook.presto.hive.hivepagesourceprovider.gethiverecordcursor...

c api socket SO_REUSEADDR -

i try understand multicast code, , don't understand utilities of little part : int fd_socket = socket(af_inet, sock_dgram, 0); u_int yes = 1; setsockopt(fd_socket, sol_socket, so_reuseaddr, &yes, sizeof(yes)); i don't understand utilities of setsockopt function. understand that, function permits modify socket in kernel, , sol_socket because modification level of socket , not of level of protocol. don't understand so_reuseaddr . for udp sockets, setting so_reuseaddr option allows multiple sockets open on same port. if sockets joined multicast group, multicast packet coming in group , port delivered sockets open on port.

R- How to return named list without printing to console -

i want return named list function, f. example, calling f(args) gives me named list of variables named x , y. use return(list(x=x,y=y)) @ end of function. $x [1] 1 2 $y [1] 12 the problem output above prints values of entire list console. want avoid because $x may take value of large matrix. there way me define model<-f(args) , surpress print out of $x values when type model console. instead, want access x model$x. use invisible : f <- function(x, y) { invisible(list(x, y)) } f(rnorm(1e4), rnorm(1e4)) ## (nothing) str(f(rnorm(1e4), rnorm(1e4))) # list of 2 # $ : num [1:10000] 2.402 0.51 -1.117 0.415 0.849 ... # $ : num [1:10000] -0.642 0.967 -0.328 -0.33 -0.914 ...

php - SELECT * FROM table where id is in other table -

i have 2 tables: items_table item id item1 1 item2 3 item3 2 item4 1 item5 3 colors_table id color 1 red 2 green 3 blue how can select items items_table color = blue ? i think should use join don't know how use. can me, please? try this: select * items_table join colors_table ct on it. id = ct.id ct.color = "blue"

sql - Display ALL the columns from table that doesn`t contain the Primary Keys -

i`ve got query do. display columns table named 'somehow' not primary keys. this how trying obtain column headers differ primary key id column : select cols.column_name information_schema.table_constraints t join information_schema.key_column_usage k using(constraint_name,table_schema,table_name) t.constraint_type <> 'primary key' , t.table_schema='mydb' , t.table_name='somehow' something not right since sql error. doing wrong? update : select k.column_name information_schema.table_constraints t join information_schema.key_column_usage k using(constraint_name,table_schema,table_name) t.constraint_type <> 'primary' , t.table_schema='mydb' , t.table_name='somehow' this shows don`t want result (the primary key ) need else shown :( all table columns can found in mysql's system table columns . column_key field contains 'pri' in case column part of primary key. hence: select c...

java - How to specify port in JDBC connection URL for failoverPartner server in SQL Server -

i'm trying add server failover sql server , not using port 1443 , i'm using port 2776 . i'm trying specify tried didn't work. how that? private string url = "jdbc:sqlserver://server1:2776;databasename=db;failoverpartner=server2"; i've tried following configs, none of them worked. ...failoverpartner=server2:2776 ...failoverpartner=server2,2776 ...failoverpartner=server2\\db but everytime exception. com.microsoft.sqlserver.jdbc.sqlserverexception: tcp/ip connection host server2, port 1433 has failed. error: "connect timed out. verify connection properties, check instance of sql server running on host , accepting tcp/ip connections @ port, , no firewall blocking tcp connections port.". com.microsoft.sqlserver.jdbc.sqlserverexception: tcp/ip connection host server2:2776, port 1433 has failed. error: "null. verify connection properties, check instance of sql server running on host , accepting tcp/ip connections @ port, ...

R: ggplot2 & Plotly: Recreating 'reference bands' on bar graphs from Tableau in R -

Image
i trying recreate functionality use daily in tableau r (ggplot2 , plotly). need able create reference bands , lines similar image below. i've figured out how create reference lines geom_errorbar(). can't seem find solution 'reference band'. if solution isn't possible in ggplot2 or plotly open package, need somethign static rmarkdown reports , dynamic html widgets dashboard. below have sample code, add reference bands of 'high' , 'low' bar graph each person. library(ggplot2) #create data name <- c("rick","carl","daryl","glenn") pos <- c("m","m","d","d") load <- c(100,110,90,130) high <- c(150,160,130,140) low <- c(130,145,120,130) data <- data.frame(name,pos,load,high,low) rm(name,pos,load,high,low) #create plot ggplot(data = data, aes(x = name, y = load)) + geom_bar(stat ="identity", width=.4) could guidance appreciated. tha...

python - How do I easily convert a numpy.ndarray to a list of numpy.array? -

i struggling parsing data training framework. the problem framework not able handle ndarray. need convert list of array. input , output data stored 2 seperate lists of numpy.ndarray. the input data has converted list of numpy array each array contains column of ndarray. the output data has converted list of numpy arrays each array contains rows of ndarray?.. is possible convert this? when print train_output_data[0] this: https://ufile.io/fa816 assuming ip , op input list , output lists respectively, newinput = [ip[:,i] in range(ip.shape[0])] newoutput = [x x in op] if train_output_data , train_input_data lists of 2d numpy.ndarray 's, alternative can be newinput = [] ip in train_input_data: newinput.append([ip[:,i] in range(ip.shape[0])]) newoutput = [] op in train_output_data: newoutput.append([x x in op])

command line interface - Java console cursor movemenet -

can move cursor somehow in java console ? i print out whole page , move cursor , user can fill out form. for example: username: ....... password: ....... re-enter passwor: ....... when user first start typing supposed appear on first dotted line, presses enter, second dotted line , on. does has got solution this? (a single "return carriage" whole console more enough me) not easily. you'd need jcurses or similar library that. text mode isn't popular anymore, support kind of functionality poor. it's easier switch graphical environment instead.

mysql - SQL: COUNT() grouped results -

this current query: select locationname, eventid events group locationname order locationname asc as can see it's grouped locationname because there several rows same locationname. in output need list of "distinct" (grouped) locations behind every location there should total amount of each location. so if in "events" 4 locationsname "congress center nyc" output should "congress center nyc (4)". is there way expand query count()? thanks! this straightforward aggregate query. select locationname, count(*) number events group locationname order locationname if want specific formatting, can using first line of query. select concat(locationname, ' (', count(*), ')')

javascript - Run selenium script through proxy Python chrome -

i'm trying open chrome through proxy problem opens chrome correctly , can't access page proxy blocked or shows website not accesible works without proxy tho. code import mechanize import urllib urllib import urlopen import cookielib import beautifulsoup import html2text import re import sys import stringio urllib2 import httperror import os import time selenium import webdriver selenium.webdriver.common.keys import keys import requests import smtplib email.mime.text import mimetext import pickle ########################################################## adidasloginpage = "https://www.adidas.fr/on/demandware.store/sites-adidas-fr-site/fr_fr/myaccount-createorlogin" sleepseconds = 2 emailusername = "testadidasacc@gmail.com" emailpassword = "ya23" global threedigit ########################################################## chrome_option = webdriver.chromeoptions() chrome_option.add_argument("--prox...

c - Open() system call doesnt work in combination with DIR directory pointer -

open() system call doesn't work in code. however, work if not used combination directory pointer. here have used file->d_name access string base address open file doesn't work , prints error. #include<stdio.h> #include<string.h> #include<fcntl.h> #include<sys/stat.h> #include<dirent.h> #include<unistd.h> #include<sys/dir.h> int main() { dir* d=opendir("ddd"); struct dirent* file; int fd; char wbuffer[]="io os system calls\n"; char rbuffer[100001]; while((file=readdir(d))!=null) if(strlen(file->d_name)>=10) { if((fd=open(file->d_name,o_rdwr,0))==-1) printf("error\n"); read(fd,rbuffer,101); printf("%s",rbuffer); close(fd); } else if(strlen(file->d_name)>=3) { if((fd=open(file->d_name,o_rdwr,0))==-1) printf("error2\n"); write(fd,wbuffer,50); close(fd); } } f...

css - How to add a different color next to textbox in asp.net -

Image
probably title kinda hard understand meant that, trying archive this. i trying add in textbox little orange part next button. tried create other div visible when select textbox. didnt work. any suggestion? something simple do? button { border-left: 2px solid red; } <button>browse games</button>

how do i read a string from a file up to a set character (for example reading the words "hello world ¬ this is a string" up to the¬) in python 3 -

sorry if english off, making in python , need fixing problem have encountered. problem im having need able take information in txt file point signalled key character such ¬, , need able take next part of string after 1st ¬ next ¬ , on. reason because strings of various lengths can , change, if have string 'znpbb t7<)!\owk_fegtit:7{.¬zo9?s9$v9vpd}z#emkc¬' in note pad file need come out 'znpbb t7<)!\owk_fegtit:7{.' and when want 2nd one, should come out as 'zo9?s9$v9vpd}z#emkc' i use split: s = 'znpbb t7<)!\owk_fegtit:7{.¬zo9?s9$v9vpd}z#emkc¬' s.split('¬') # returns ['znpbb t7<)!\\owk_fegtit:7{.', 'zo9?s9$v9vpd}z#emkc', '']

javascript - Use ng2-material in angular 2.1.x project -

i'm trying use library in angular2 project looks trully amazing. i've managed set (and use) basic angular material library can't managed add ng2-material on top of it. think have problem systemconfig loader can't fix it: (index):19 error: (systemjs) xhr error (404 not found) loading http://localhost:3000/ng2-material(…) here package.json file: "dependencies": { "@angular/common": "~2.1.1", "@angular/compiler": "~2.1.1", "@angular/core": "~2.1.1", "@angular/forms": "~2.1.1", "@angular/http": "~2.1.1", "@angular/material": "^2.0.0-alpha.10", "@angular/platform-browser": "~2.1.1", "@angular/platform-browser-dynamic": "~2.1.1", "@angular/router": "~3.1.1", "@angular/upgrade": "~2.1.1", "@angular2-material/core...

Python 2.7 for loop and not printing the right time -

okay writing simple login system, here code import time counter in range(5): username=str(raw_input("please enter username")) password=str(raw_input("please enter password")) if username =="bros10": print "",username,"entered" time.sleep(4) print "you got username right" if password =="brosbros10": print "you got password right" print "welcome system" break else: print "try again" and happens when run print bit print "",username,"entered" after have entered password appreciated move this: print "",username,"entered" to before this: password=str(raw_input("please enter password")) now program ask username, repeat username entered (and tell user got right if entered bros10 ), ask password, sleep 4 seconds. alternatively, can place password= line right before ...

javascript - Angularjs nested controller called just one time -

i'm new in angularjs , have app, "projects", have local menu displayed on pages. index.html contains main navbar footer : <body ng-app="ysi-app" ng-controller="maincontroller"> <div class="page-content"> <div class="row"> <div class="col-md-2"> <div class="sidebar content-box" style="display: block;"> <ul class="nav"> <!-- main menu --> <li ng-if="isauthenticated()"><a href="#/">{{name}}</a></li> <li class="current"><a href="index.html">dashboard</a></li> <li><a href="#/project">projects</a></li> </ul> </div> <div ng-if="isauthenticated() && displayprojectmenu == true" ng-inclu...

c++ - Segmentation Fault On New -

i'm not sure if problem g++ or somehow compiler messed getting error on new @ start of program. have tested , instance of new gives me fault, simple this: int main(int argc, char *argv[]) { new char[12]; return 0; } stack trace: #0 0x7703636d in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #1 0x77035125 in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #2 0x77034fc2 in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #3 0x770cece6 in ntdll!rtlpntsetvaluekey () c:\windows\system32\ntdll.dll #4 0x77037656 in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #5 0x77035125 in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #6 0x77034fc2 in ntdll!rtlallocateheap () c:\windows\system32\ntdll.dll #7 0x765e79b0 in msvcrt!malloc () c:\windows\system32\msvcrt.dll #8 0x6fef4a79 in ?? () c:\mingw\bin\libstdc++-6.dll #9 0x6fef4a1f in ?? () c:\mingw\bin\libstdc++-6.dll #10 0x00401a5c in main (argc=2, argv=0x7679b0) @ c:\users\macken...