Posts

Showing posts from June, 2015

python 2.7 - How to sort defaultdict(list) such that all lists are sorted based on one key? -

to amazing programmers, i know how can sort defaultdict(list) collection such sort order of 1 list (e.g. defaultdict(list)[list1]) applied remaining lists well. perhaps short description/example more useful. if there better way of doing ears. example problem: had .csv file consisting of many columns (different data types) , headerline. using defaultdict(list) import .csv file using: data = defaultdict(list) reader = csv.dictreader(open(filepath, 'r')) (k,v) in row.items(): data[k].append(v) now left defaultdict(list) named 'data' of structure: data = [('vara', <list of n time.struct_time items>), ('varb', <list of n other data type items>)', ('varc', <list of n other data type items>)'] each list (vara, varb, varc) has exact same number of items. assuming vara not ordered, how order data entries based on vara. i know sortorder = [i[0] in sorted(enumerate(data['vara']), key

jquery - Modal not appearing in Javascript, Using Bootstrap -

i want make modal appear when click on sign up. problem modal not appearing although have checked code many times. modal code when used without other content works fine. source code w3schools. sorry in advance way code occurs, how stackoverflow text editor works beyond me. new this,so please don't fry me if it's idiotic mistake <!doctype html> <html manifest="demo.htm.appcache"> <head> <link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet"> <link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css"> <link rel="stylesheet" href="main.css"> <link rel="icon" type="image.ico" href="airbnb logo.ico"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <s

javascript - Mongoose: retrieve data in same order as schema -

is there way retrieve mongoose db info in same order appears in schema? it seems group type when returns objects. example: //schema var data = { element1 : string, element2 : number, element3 : array, element4 : number, } //.find() returns var data = { element1 : string, element2 : number, element4 : number, element3 : array, } i need write file information in specific order appears in schema if possible retrieve in order save lot of code. if isn't possible, possible retrieve schema grab keys in order can match them when writing file? you have use array. an object member of type object. unordered collection of properties each of contains primitive value, object, or function. function stored in property of object called method. http://www.ecma-international.org/publications/files/ecma-st-arch/ecma-262,%203rd%20edition,%20december%201999.pdf

is it possible to stop php sessions carrying over from different folders -

i have file structure , use $_session['userid'] track logged in: main index (a hub websites) | |--/_lm/index.html (website 2) | |--/_da/index.html (website 3) | |--/_vm/index.html (website 4) i have found once logs into, example, website 2 - $_session['userid'] carry on other websites. what best way top happening? there way confine session data folder? dont use $_session['userid'] validate every session. once set works across site. so try this website 1 session $_session['userid1'] website 2 session $_session['userid2'] website 3 session $_session['userid3'] website 4 session $_session['userid4']

android - FragmentStatePageAdapter doesn't remove child fragments -

having problem fragmentstatepageradapter , screen change orientation (saving state guess). layout of app following: activity --> fragment fragment b (contains fragmentstatepageradapter) wich shows 2 fragments --> fragment b1 fragment b2 all fragments mentioned inherit basefragment class doesn't special keeping "global" vars need. when activity starts loads fragment a . menu replace fragment a fragment b . fragment b source following: public class fragment b extends basefragment { public static string tag = "b_fragment"; private mycustompageradapter adapter; private arraylist<string> tags = new arraylist<>(); private viewpager mviewpager; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); adapter = new mycustompageradapter(getfragmentmanager()); //adapter = ne

html - Stacking with position: relative -

i'm attempting stack divs (styled sticky-notes) part of divs on bottom hang out. considered okay, i'll style top-most div normally, , style parts can see bottom divs (as opposed making divs same width+height , stacking them). issue want style border-radius of divs same, , if non-stacking way, border-radius applied top div doesn't yield same design border-radius applied bottom divs (because width+height different top div, i'm guessing). <div class="stickynote1"> content <div> <div class="stickynote2"> content <div> <div class="stickynote3"> content <div> is there way fix border-radius issue without resizing divs same width+height? if resize divs same width+height, how can stack them? seems position:relative , z-index combination on divs won't work because position:relative created new container block, somehow making z-index not work other divs' new container blocks. if you,

php - Combining created columns in MySQL -

i have mysql query returns columns different tables, column i've customized through case statement. select table.column, case (...) new_column the thing is, want concatenate table.column , new_column in query, although can't independently call new_column since created in query. due database privileges, can't create tables on database. thoughts on how should approach this? you can wrap whole select concat() function: select concat(table.column, case(...)) new_column table; another way of approaching it, not recommend may little more readable, use current query subquery , concatenate parent one: select concat(column, new_column) new_column from( select table.column, case(...) new_column table ) tmp;

Weird things with C# events -

i'm learning events , delegates , decided write such console application. program should message me every 3 , 5 seconds. doesn't anything. i have class workingtimer : class workingtimer { private timer _timer = new timer(); private long _working_seconds = 0; public delegate void mydelegate(); public event mydelegate every3seconds; public event mydelegate every5seconds; public workingtimer() { _timer.interval = 1000; _timer.elapsed += _timer_elapsed; _timer.start(); } void _timer_elapsed(object sender, elapsedeventargs e) { _working_seconds++; if (every3seconds != null && _working_seconds % 3 == 0) every3seconds(); if (every5seconds != null && _working_seconds % 5 == 0) every5seconds(); } } and program: class program { static void main(string[] args) { workingtimer wt = new workingtimer();

javascript - Adding Legend on a basic chart -

i brand new d3.js , stackoverflow please pardon if ask basic. have basic donut chart modification of normal donut chart since can see there 1 on top of another. wondering if possible add label right on chart. able add legend , label outside chart want able add label right on chart itself. this code chart var dataset = { data1: [53245, 28479, 19697, 24037, 40245], data2: [53245, 28479, 19697, 24037, 40245] }; var width = 460, height = 300, cwidth = 45; var color = d3.scale.category20(); var pie = d3.layout.pie() .sort(null); var arc = d3.svg.arc(); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var gs = svg.selectall("g").data(d3.values(dataset)).enter().append("g"); var path = gs.selectall("path")

textbox - Inconsistencies in caret position, string length and matches index in C# -

i trying selected word in scintilla textbox using regex, , noticing inconsistencies between reported string length, matches index , caret position or start of selection: private keyvaluepair<int, string> get_current_word() { int cur_pos = scin_txt.selection.start; keyvaluepair<int, string> kvp_word = new keyvaluepair<int, string>(0, ""); matchcollection words = regex.matches(scin_txt.text, @"\b(?<word>\w+)\b"); foreach (match word in words) { int start = word.index; int end = start + word.length; if (start <= cur_pos && cur_pos <= end) { kvp_word = new keyvaluepair<int,string>(start, word.value); break; } } return kvp_word; } in short, splitting string in words , using matches indexes see if caret contained within word. unfortunately, numbers don't seem match properly: scin_txt contains string: "le clic dro

c++ - How to auto resize the text control in mfc -

i want put text in idc_text in mfc. want auto resize control input text. used code not work. me resolve it? cfont *m_font1 = new cfont; cstatic * m_label; m_font1->createpointfont(200, "time new roman"); m_label = (cstatic *)getdlgitem(idc_text); m_label->setfont(m_font1); m_label->setwindowtext( _t("") ); //display text in thread threadstruct* ts = (threadstruct*)param; cdc* vdc_txt; vdc_txt =ts->_this->getdlgitem(idc_text)->getdc(); ts->_this->getdlgitem(idc_text)->setwindowtexta(text.c_str()); //update length- ts->_this->getdlgitem(idc_text)->setwindowpos(null, 0, 0, 1000, 1000, swp_nomove | swp_noactivate | swp_nozorder); however, number (1000,1000) set hand. want auto change based on text size. have me solve it? update: if font size same, , text different, should able reuse old font: void changesize() { cwnd* dlgitem = getdlgitem(idc_static1); if (!dlgitem) return; cstring s;

Webpack progress using node.js API -

is there way access webpack's progress while using node.js api? i'm familiar --progress flag using cli. the webpack cli uses progressplugin log progress of compilation. var progressplugin = require('webpack/lib/progressplugin'); var compiler = webpack(config); compiler.apply(new progressplugin(function(percentage, msg) { console.log((percentage * 100) + '%', msg); })); compiler.run(function(err, stats) { // ... }); here link compiler documentation , progressplugin documentation .

C# Winform checkbox button text -

i have winform series of check boxes buttons. the datatype in sql it the checkbox bound when value true text on "button" says "true" when false says "false" i want text not change type in. ex; checkbox says "unit active?" when true changes true, want unit active? , turn green any suggestions? tia it looks binding text of checkbox. however, state don't want text change. i think should bind checked property instead.

javascript - Bootstrap nested accordian issue -

Image
we facing issue in using nested bootstrap accordians. on click of parent accordian paperless settings child element icons changing , vice versa happening too. should not happen , inner accordian other normal accordion. fiddle link: https://jsfiddle.net/6lspm1k1/ javascript: $('#accordion .collapse').on('shown.bs.collapse', function(){ $(this).parent().find(".fa-plus").removeclass("fa-plus").addclass("fa-nus"); }).on('hidden.bs.collapse', function(){ $(this).parent().find(".fa-minus").removeclass("fa-minus").addclass("fa- plus"); }); so problem due reason callback fires way accordion. one solution works , according me cleaner use css-selectors determine display: i've added each header has fa-plus , fa-minus , css hides / shows depending on class .collapsed html changed from: <span class="fa fa-minus"></span> to:

Is it possible to deploy to a Nexus Repository using Maven 1? -

some of our projects still use maven 1. possible deploy artifacts nexus maven 1 repository using "maven:deploy" goal? not find properties set username , password. we found work around sharing storage folder of nexus server , deploying directly folder using file protocol, not preferred solution. if you're using maven 2 (not maven 3) can deploy artifacts in maven 1 format adding "legacy distributionmanagment <distributionmanagement> <repository> <id>nexus</id> <name>release repository</name> <url>http://localhost:8081/nexus/content/repositories/maven1</url> <layout>legacy</layout> </repository> ... </distributionmanagement> this won't work maven 3, legacy layout support removed in version of maven.

Python script read serial port, output to text file -

i'm trying read output serial port , write text file. far connects , prints output, can't figure out how send output text file (preferrable csv file). #! /usr/bin/env python3 import serial import csv import sys import io #excel stuff #from time import gmtime, strftime #resultfile=open('mydata.csv','wb') #end excel stuff def scan(): """scan available ports. return list of tuples (num, name)""" available = [] in range(256): try: s = serial.serial(i) available.append( (i, s.portstr)) s.close() # explicit close 'cause of delayed gc in java except serial.serialexception: pass return available if __name__=='__main__': print ("found ports:") n,s in scan(): print ("(%d) %s" % (n,s)) selection = input("enter port number:") try: ser = serial.serial(eval(selection), 9600, timeout=1)

c# - Active Reports - Find out what page a control is on before the final print -

i need find out page control on after report data has been added. depending on how data has been added above (e.g. table rows), control on page 1, 2 or 3. reason needing page number find out if control straddles 2 pages. if want nudge down enough make sure not split on 2 pages as control in question dynamically added during reportstart event can't tell page end on report data hasn't been added yet. i'm pretty sure i'll able in detail_beforeprint event fires each page of report , this.pagenumber gives current page. inside detail_beforeprint can find control using: var mycontrol= this.detail.controls["mycontrol"]; but mycontrol not have properties might suggest page on. can help? i'm using active reports 6 , visual studio 2010 what you're asking not possible find out. can retrieve pagenumber report tell last page control print to. control not have page number because possible print on more 1 page. however said, possi

objective c - iPad App Landscape Mode broken iOS 8.3 -

Image
i have app ipad , app landscape right , left orientation..like printscreen: and i'm using following code rotate view landscape mode: - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { [[uiapplication sharedapplication] setstatusbarorientation:uiinterfaceorientationlandscaperight]; cgaffinetransform rotate = cgaffinetransformmakerotation(m_pi/2); [self.window settransform:rotate]; [self.window setframe:cgrectmake(0, 0, 768, 1024)]; } and xib: it worked fine..but in ios 8.3 doesn't work. appears wrong...see image: set auto layout constraints viewcontroller objects. , no need write code in didfinishlaunchingwithoptions [[uiapplication sharedapplication]setstatusbarorientation:uiinterfaceorientationlandscaperight]; cgaffinetransform rotate = cgaffinetransformmakerotation(m_pi/2); [self.window settransform:rotate]; [self.window setframe:cgrectmake(0, 0, 768, 1024)];

javascript - client connecting twice to server, Socket.io -

i trying log username of logged in users connecting socket.io passport.js using passport.socketio. successful logs username twice , after trying , searching fair amount of time stuck. the code sections follows: the server code: var server = http.createserver(app); var io = require('socket.io')(server); io.use(passportsocketio.authorize({ cookieparser: cookieparser, // same middleware registred in express key: 'connect.sid', // name of cookie express stores session_id secret: 'hello', // session_secret parse cookie store: new (require("connect-mongo")(esession))({ url: "mongodb://localhost/local" }), // need use sessionstore. no memorystore please success: onauthorizesuccess, // *optional* callback on success - read more below fail: onauthorizefail, // *optional* callback on fail/error - read more below })); function onauthorizesuccess(data, accept){

symfony - Sending a simple POST request from a controller symfony2 without cUrl -

i think there quite easy answer but, tried send post request rest api controller : use symfony\component\httpfoundation\request; ... $request = request::create('127.0.0.1', 'post', array('test' => 'this test')); but did nothing, there missing send or execute method ? lot by doing so, you're creating request object. no actual request sent out. to suggest use: buzz ultimately, may use sensiobuzzbundle in order have buzz service edit: forgot mention: believe buzz uses curl

mysql - Display things with time with php -

i want display gitfs specific timeslot, when try method, display old gifts . want display gifts dating there 1 week. $midnight = strtotime("now -7 days"); $message = ''; $user = xxx_variable $stmt = $this->conn->prepare("select * gifts to_user = ? , time > ? order time desc limit 1, 25"); $stmt->bindvalue(1, $user, pdo::param_str); $stmt->bindvalue(2, $midnight, pdo::param_str); try this.. you need use "unix_timestamp". unix_timestamp(current_date - interval 7 day) -- 7 days ago $stmt = $this->conn->prepare("select * gifts to_user = ? , time > ? order time desc limit 1, 25"); $stmt = $this->conn->prepare("select * gifts to_user = ? , time >= unix_timestamp(current_date - interval 7 day) order time desc limit 1, 25");

java - ConcurrentModificationException thrown by GlassFish 3.1.2.2 on commit of XA transaction -

we have singleton ejb bean deployed in glassfish 3.1.2.2 server following annotations: @concurrencymanagement(concurrencymanagementtype.bean) @singleton @startup @local(xxx.class) @transactionattribute(transactionattributetype.never) the bean injected servlet calls several methods on it. randomly, server.log shows there concurrentmodificationexception thrown random methods of bean on commit of xa transaction. javax.transaction.xa.xaexception: java.util.concurrentmodificationexception @ com.sun.enterprise.resource.connectorxaresource.handleresourceexception(connectorxaresource.java:115) @ com.sun.enterprise.resource.connectorxaresource.resetassociation(connectorxaresource.java:287) @ com.sun.enterprise.resource.connectorxaresource.commit(connectorxaresource.java:128) @ com.sun.enterprise.transaction.javaeetransactionimpl.commit(javaeetransactionimpl.java:501) @ com.sun.enterprise.transaction.javaeetransactionmanagersimplified.commit(javaeetransactionmanager

html - select menu inside <li> working on ios chrome but not on ios safari -

i working on responsive web app has menu of cities , under there many options. on desktop uses ul > li > a on smaller screens, hides <a> , make select/option menu visible . issue i'm facing is working fine in android. perfect in ios chrome. in ios safari have double tap list/select item open select/option menu . here code <ul> <li id="12"> <a href="/fashion-collections/2014/1-spring-summer/1-ready-to-wear/12-kiev">kiev</a> <select class="designer-mobile-dropdown"> <option> kiev </option> <option value="/anna-k-ready-to-wear-spring-summer-2014-kiev-4971"> anna k </option> <option value="/natasha-zinko-ready-to-wear-spring-summer-2014-kiev-4945"> natasha zinko </option> <option va

angularjs - protractor e2e testing Returning Promises from utility steps -

i'm new protractor , promises in general. i've had around, , although there's many posts out there returning promises, or results queued actions none of them make sense me, i'm after described answer hope simple question! i trying write protractor tests angularjs website. i using bootstrap , angular mainly, no other third party libraries, other occasional angular add-on such toaster, , bootstrap modal. i have several 'arrangement steps' before assertion part of test. let's : a) person logs in b) person accesses options form ( may or may not displayed on screen depending on external factors, if it's not present can open button press ). c) person performs action on options form. d) assert text box on form contains correct value. i can test pass quite when form on screen, bit that's getting me stuck step b) need check first if form active , click button if it's not pefore proceeding step c. i've tried return promise isdis

My Plone product doesn't show up in the quickinstaller -

i have plone site traditional product baseproduct (versioned directly in products filesystem directory of zope installation); rest of setup buildout -based. for fork of project, need product additionalproduct , made same way (i know it's not current state-of-the art method; that's how worked before me ...). now was able install additionalproduct using quickinstaller (for contains single skin directory single template only, change, of course). sadly, ceased work; product not shown in quickinstaller anymore. there no visible error; able pdb.set_trace() during instance startup, , there no error in error.log either. the profiles.zcml file looks this: <configure xmlns="http://namespaces.zope.org/zope" xmlns:genericsetup="http://namespaces.zope.org/genericsetup" i18n_domain="baseproduct"> <include package="products.genericsetup" file="meta.zcml" /> <genericsetup:registerprofile

How can I set the file output location in ogr2ogr? -

whenever use ogr2ogr convert files output saved following directory: c:\users[username]\appdata\local\virtualstore is there anyway can set directory else? you can set output file location adding ogr2ogr command arguments; example: ogr2ogr -f geojson -s_srs epsg:27700 -t_srs epsg:4326 c://somedirectory/outputfilename inputfilename

python - Cannot Redirect to URL after form post in django -

i creating user registration system in django1.8. when click register button on form, not redirect success url. not sure if right way save user information in database. please recommend if there better way approach user registration in django. models.py from django.db import models django.contrib.auth.models import user class userprofile(models.model): user = models.onetoonefield(user) age = models.integerfield(blank=true) gender_choices = (('m', 'male'), ('f', 'female')) gender = models.charfield(max_length=1, choices=gender_choices, default='male') forms.py from django import forms .models import userprofile class userprofileform(forms.modelform): class meta: model = userprofile exclude = ['user'] views.py from django.shortcuts import render, redirect django.core.urlresolvers import reverse django.contrib.auth.forms import usercreationform django.contrib.auth.models import user .f

sql server - Optimizing a dashboard query -

i'm building application , in app want show simple statistics number of items in system , in various states , i've created query while works fell though incredibly inefficient, honest i'm not sure how go making better. what have ended cute nothing more bunch of sub selects in order dashboard stats such: with cte_dashboard(active_employees, inactive_employees, linked_employees, total_employees, ongoing, completed, pending, cancelled, total_contracts) ( select (select count(id) [tam].[employees] isactive = 1) 'active', (select count(id) [tam].[employees] isactive = 0) 'inactive', (select count(id) [tam].[employees] userid not null) 'linked', (select count(id) [tam].[employees]) 'total', (select count(id) [tam].[contracts] status = 'ongoing') 'ongoing', (select count(id) [tam].[contracts] status = 'completed') 'completed', (selec

addeventlistener - How to trigger JavaScript custom events correctly -

i struggling understand how custom event type linked specific user action/trigger. documentation seems dispatch event without user interaction. in following example want event dispatched once user has been hovering on element 3 seconds. var img = document.createelement('img');img.src = 'http://placehold.it/100x100'; document.body.appendchild(img) var event = new customevent("hoveredforthreeseconds"); img.addeventlistener('hoveredforthreeseconds', function(e) { console.log(e.type)}, true); var thetrigger = function (element, event) { var timeout = null; element.addeventlistener('mouseover',function() { timeout = settimeout(element.dispatchevent(event), 3000); },true); element.addeventlistener('mouseout', function() { cleartimeout(timeout); },true); }; i have trigger no logical way of connecting event. i thinking creating object called customeventtrigger customevent has third parameter

android - INSTALL_REFERRER not received on production -

i'm not getting install referrer received on application installed play store. below androidmanifest.xml shows receiver inside <application> tag too. <receiver android:name="com.usplnew.getreferrer.customreceiver" android:exported="true" > <intent-filter> <action android:name="com.android.vending.install_referrer" /> </intent-filter> </receiver> and below code receiver public class customreceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { system.out.println("sgn received"); log.d("yes", "it works!!"); toast.maketext(context, "received intall referrer", toast.length_short) .show(); } } its working below command on emulator , device too adb shell broadcast -a com.android.vending.install_referrer -n com.uspl.getreff

model view controller - Session time out error -

my application expiring before 20 minutes , when working on expiring may know have change?.. public class checksessionoutattribute : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext filtercontext) { httpcontext ctx = httpcontext.current; if (ctx.session != null) { if (ctx.session.isnewsession) { string sessioncookie = ctx.request.headers["cookie"]; if ((null != sessioncookie) && (sessioncookie.indexof("asp.net_sessionid") >= 0)) { if (ctx.request.isauthenticated) { formsauthentication.signout(); httpcontext.current.session.clear(); redirectresult redirectingto = new redirectresult("~/account/timeout"); filtercontext.result = redirectingto; }

regex - why doesn't this simple html code work? (pattern) -

could tell me why simple code doesn't work? type random email address .com @ end , receive error address doesn't have right format. <!doctype html> <html> <body> <form action="demo_form.asp"> e-mail: <input type="email" name="email" pattern="\.com$"> <input type="submit"> </form> </body> </html> maybe works <form action="demo_form.asp"> e-mail: <input type="email" name="email" pattern="+\.com$"> <input type="submit"> </form>

javascript - parseInt vs unary plus - when to use which -

what differences between line: var = parseint("1", 10); // === 1 and line var = +"1"; // === 1 this jsperf test shows unary operator faster in current chrome version, assuming node.js!? if try convert strings not numbers both return nan : var b = parseint("test" 10); // b === nan var b = +"test"; // b === nan so when should prefer using parseint on unary plus (especially in node.js)??? edit : , what's difference double tilde operator ~~ ? please see this answer more complete set of cases well, here few differences know of: an empty string "" evaluates 0 , while parseint evaluates nan . imo, blank string should nan . +'' === 0; //true isnan(parseint('',10)); //true the unary + acts more parsefloat since accepts decimals. parseint on other hand stops parsing when sees non-numerical character, period intended decimal point . . +'2.3' === 2.3;

Drupal Feed Import module uninstall issue -

i tried disable , uninstall feed import module 7.x-3.4. after uninstallation, can still find in module list. should remove module list? thanks. you should delete files , folders associated it. depending on how installed, might in sites/all/modules.

Does the Cyclomatic Complexity extension exist for ReSharper 9.1? -

i trying resharper 9.1 , i've found no cyclomatic complexity setting ...i've searched on plugins far i've seen works powertoys till 8.3 am missing or has been removed? looks resharper powertoys: cyclomatic complexity extension has not been updated on year now. suggest contacting jetbrains , ask them if updated 9.1. in mean time use visual studio's analyze -> calculate code metrics solution show cyclomatic complexity.

javascript - How to open bootstrap dropdown by external button click -

i've read half of internet, find clear example on how this. bunch of "solutions" nothing works far.. here's tried: $('#openner').on('click', function(e){ e.preventdefault(); // nothing works bellow :( //$('.dropdown-toggle').trigger('click'); //$('.dropdown-toggle').click().parent().addclass('open'); //$('.dropdown-toggle').trigger('click.bs.dropdown''); $('.dropdown-toggle').click().addclass('open'); }); jsfiddle try: $('#openner').on('click', function(e){ $('ul[aria-labelledby="dropdownmenu1"]').toggle(); }); jsfiddle: http://jsfiddle.net/mluarcdc/4/

vb.net - Getting cross thread Error even Used Invoke -

getting cross thread error when executing tcviewer.tabpages.add(t) statement. code below. private function fff(t tabpage) tcviewer.tabpages.add(t) 'giving cross thread error end function function webbrowserthread() dim t tabpage = new tabpage((k + 1).tostring()) t.name = k.tostring() tcviewer.invoke(fff(t)) end function please guide. i think should move creation of new tabpage onto ui thread well: private function fff(k integer) dim t tabpage = new tabpage((k + 1).tostring()) t.name = k.tostring() tcviewer.tabpages.add(t) end function function webbrowserthread() tcviewer.invoke(fff(k)) end function when construct tabpage , reach call stack: system.windows.forms.dll!system.windows.forms.control.createhandle() system.windows.forms.dll!system.windows.forms.application.marshalingcontrol.marshalingcontrol() system.windows.forms.dll!system.windows.forms.application.threadcontext.marshalingcontrol.get() system.windows.forms.dl

Prevent inline onclick from external javascript file -

is there way prevent inline onclick attributes external js file? <button id="mybutton" type="button" onclick="alert('dont show me please!');" >click me</button> in script.js: var mybutton = document.getelementbyid("mybutton").addeventlistener("click", preventit); function preventit(e){ console.log('click event...'); e.preventdefault(); } assume can't change html markup. you remove onclick attribute so: document.getelementsbyid("mybutton").removeattribute("onclick");

How to concatenate and output unicode text variables in Python -

my title terms might not correct , may reason why can't find simple thing websites. i have list of string variables. how concatenate them , output real unicode sentence in python? base = ['280', '281', '282', '283'] end = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] unicodes = [u''.join(['\u', j, i]) j in base in end] u in unicodes: print u i strings '\u280f' not real character. if do: print u'\u280f' correct symbols shows up, is: ⠏ and i'm sure there more elegant way range of symbols u2800 u283f... conver strings integers (using int base 16), use unichr ( chr if you're using python 3.x) convert number unicode object. >>> int('280' + 'f', 16) # => 0x280f, 16: hexadecimal 10255 >>> unichr(int(

makefile - make error ignored - when it shouldn't -

in make file , given target , have cmd1 followed cmd2 structure is: ( there tab before cmd1 , cmd2 ) target: cmd1 cmd2 cmd1 fails , returning no 0 status code ( 231 ) , make should halt ( has been case ) for reason , i'm getting : make: [target] error 231 (ignored) and excution goes on any idea why?

servlets - Get configured url patterns in a Java Filter -

this question has answer here: what url-pattern in web.xml , how configure servlet 2 answers i cannot find way url-mapping information inside filter. for instance, web.xml: <filter> <filter-name>somefilter</filter-name> <filter-class>com.xxx.filter.somefilter</filter-class> </filter> <filter-mapping> <filter-name>somefilter</filter-name> <url-pattern>/ws/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>somefilter</filter-name> <url-pattern>/rest/*</url-pattern> </filter-mapping> then inside somefilter list of mappings ["/ws/ ","/rest/ "]. there way it? @override public void init(filterconfig filterconfig){ filterconfig.getxxx() // -> ["/ws/*","/rest/*"]??? }

Check if current time is 1 minute past previously-saved time in PHP -

i'm saving time variable called $time, using $time = time() , , later on, need able check see if current time greater 1 minute comparing current time previously-saved time. how can in php? you can save time database or session, how check $time = time(); if((time() - $time) > 60){ echo 'past 1 minute'; }

css3 - Add white space in HTML page -

i add white space in html page. use basic <br/> <br/> <br/> <br/> <br/> <br/> .... is there other way add white space in order add padding between components? div,p,span , every html element add padding , margin. like p {margin-bottom:15px;} div {padding-bottom:15px;} span {padding:15px 15px 15px 15px;} p {margin:15px 15px 15px 15px;}

javascript - Check if an element copy exists in the document -

i parsing document elements(specifically anchor tags) , pushing them array. when new elements added page via ajax run parser again collect elements , push them array again. problem facing is, want delete elements array when removed page, not have unique ids these elements, mere anchor tags. there unique element id attached jquery object of element? if so, can push copy jquery object array instead of standard js object. this not "check if element exists on page" question. have copy of element, , want check if original elements still exists on page or not, hope see difference between 2 questions.

angularjs - loadMore() is not being called on browser scroll in ngInfiniteScroll -

i trying implement infinite scroll angularjs app. acquainted usage of nginfinitescroll i using same example given in demos page. not working me, profile.ejs : <script src='../controllers/jquery.min.js'></script> <script src='../controllers/angular.min.js'></script> <script src='../controllers/ng-infinite-scroll.min.js'></script> <!-- other code --> <ul infinite-scroll='loadmore()' infinite-scroll-distance='1' > <div ng-repeat="item in images">item number {{$index}}: {{$item}}</div> </ul> <!-- other code --> profilecontroller.js $scope.images = [1, 2, 3, 4, 5, 6, 7, 8]; $scope.loadmore = function() { alert("called"); var last = $scope.images[$scope.images.length - 1]; for(var = 1; <= 2; i++) { $scope.images.push(last + i); } }; the alert("called") not

java - Artifactory environment variables on CentOS -

i'm going mad. /usr/lib/jvm/ has java-1.7.0-openjdk-1.7.0.65.x86_64 java-1.7.0-openjdk-1.7.0.79.x86_64 last night @ unfortunate possible time, contents of #65, artifactory apparently using, disappeared. java disappeared. maybe gone, new linux guys 'upgrading' machine, it's suspicious. now, issue artifactory cannot forget version 65. if type in env or set , we're golden. no mention of v65. artifactory lives in own world. [root@me]# service artifactory check checking arguments artifactory: artifactory_home = /var/opt/jfrog/artifactory artifactory_user = artifactory tomcat_home = /opt/jfrog/artifactory/tomcat artifactory_pid = /var/opt/jfrog/run/artifactory.pid java_home = java_options = -server -xms512m -xmx2g -xss256k -xx:permsize=128m -xx:maxpermsize=256m -xx:+useg1gc [root@me]# service artifactory start starting artifactory tomcat user artifactory... max number of open files: 32000 using artifa

arrays - How to get all possible paths through a graph of knots easily in php -

i want calculate costs each possible path through network (geographical). therefore need every possible combination of knots in network. we have simple case: knots 1-4 fixed startpoint @ 1 , condition every knot has part of path -> length every path equal 1->2->3->4 1->2->4->3 1->3->2->4 1->3->4->2 1->4->2->3 1->4->3->2 my preferred result should be: <?php $array = array( array(1,2,3,4), array(1,2,4,3), array(1,3,2,4), array(1,3,4,2), array(1,4,2,3), array(1,4,3,2) ) ?> can tell me how calculate possible paths through network given number of knots , fixed start? thanks in advance!

java - Using messageSelector with AbstractMessageListenerContainer Spring Framework -

i want use messageselector string inside class abstractmessagelistenercontainer.class , here xml configurations giving. <bean id="jmscontainer" class="org.springframework.jms.listener.defaultmessagelistenercontainer"> <property name="autostartup" value="${listener.setup}" /> <property name="connectionfactory" ref="connectionfactory" /> <property name="destination" ref="paymentresponsequeue" /> <property name="messagelistener" ref="myabstractlistener" /> </bean> <bean id="myabstractlistener" class="org.springframework.jms.listener.abstractmessagelistenercontainer"> <property name="autostartup" value="${listener.setup}" /> <property name="connectionfactory" ref="connectionfactory" /> <property name="destination" ref="

regex - php: preg_match and preg_replace -

i'm unsure of how following... i need search through string , match instances of forward slash , certain letters . word modifications users have ability input , want them able modify individual words. here example string hello, isn't weather absolutely beautiful today!? what i'd user able this hello, isn't /bo weather /it beautiful today!? take note of /bo , /it what i'd have preg_match , or preg_replace statement finds , replaces instances of /bo , /it , converts them instead html tags such bolded html tag , italics html tag (i cant type them here or converted actual html. wrap around word following /bo in example wind being hello, isn't <b>weather</b> <i>beautiful</i> today!? any ideas how regex ? once conversions done i'll standard sanitizing before inserting data database along prepared statements. $string = "hello, isn't /bo weather /it beautiful /bo today!?"; var_

I want to keep a function running continuously in my Winform C# project, until the form window is closed -

i want keep function running continuously in winform c# project, until form window closed. don't want put in long timer , call again , again. shall do? i need keep validating if form open or closed continuously: while(this.close() == false) { my_func(); } the above code wrong wrote give idea want. remember there formclosing , formclosed events can utilize on form. handling 1 of billion times more efficient continuously polling form's status...

c# - change the name column text of the current row when the selected index of drop down is changed -

Image
hello followed this link of mudassar , need few it. how change name column text of current row when selected index of drop down changed? ex:1st column text 2nd dropdown , when change dropdown want replace text value this gridview1.rows[currentrowindex.cells[0].text="xyz" here aspx file <form id="form11" runat="server"> <div> <asp:label id="label1" runat="server" text=" "></asp:label> <asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" onrowdatabound ="gridview1_rowdatabound"> <columns> <asp:boundfield datafield="input_metadata_id" headertext="input metadata id" readonly="true" sortexpression="input_metadata_id" visible="false"></asp:boundfield> <asp:boundfield datafield="input_id" headertext="input i

sql - MySQL Sleep time query -

how increase time queries auto kill themselves. should doing eliminate repeated error. i using prestashop , have been facing these queries crowding server reported server assistant. thu jun 18 09:56:15 +0000 2015 [info] killed_thread_id:11508142 user:pres102 host:localhost db:pres102 command:sleep time:21 query: these repeatedly being displayed in list of killed queries. in file make changes these queries resolved correctly? other changes in file should make kill other queries. not know file name in prestashop such queries , changes should made. please help.

loopbackjs - Loopback Custom Validation Throws Error -

while using validatable.validate() custom function throwing internal loopback error. var duplicateconnection = function(err, done, er) { connection.find({where: {userid: this.userid, nucleusid: this.nucleusid}}, function(bug, connection) { if (!_.isempty(connection)) {err();} }); }; connection.validate("userid", duplicateconnection); error: if (kind !== false) inst.errors.add(attr, message, code); ^ typeerror: undefined not function @ \node_modules\loopback-datasource-juggler\lib\validations.js:550:37

ruby - peter-murach/finite_machine restore persisted state -

using finite machine gem ruby piotr murach. would restore state machine persisted (stored) state. documentation teaches initial state, , restoring state , activerecord model. all i've been able find dsl lets me define initial state, or define event transitions initial state. both require me define initial state @ coding time. fm = finitemachine.define initial :red or fm = finitemachine.define events { event :start, :none => :red in practice, i'm defining "standalone" along lines of, class engine < finitemachine::definition initial :neutral what i'd define initial state in initializer class, like: class engine < finitemachine::definition def initialize(car, state) initial state target car end however not work. :none current state after initialization. found restore! method , section in doc persisting state activerecord. tried along lines of: class engine < finitemachine::definition