Posts

Showing posts from March, 2011

r - Mixture of Gaussian and Gamma distribution -

Image
i'm looking script/package in r (python too) find out component distribution parameters mixture of gaussian , gamma distributions. i've far used r package "mixtools" model data mixture of gaussians, think can better modeled gamma plus gaussian. thanks here's 1 possibility: define utility functions: rnormgammamix <- function(n,shape,rate,mean,sd,prob) { ifelse(runif(n)<prob, rgamma(n,shape,rate), rnorm(n,mean,sd)) } (this made little bit more efficient ...) dnormgammamix <- function(x,shape,rate,mean,sd,prob,log=false) { r <- prob*dgamma(x,shape,rate)+(1-prob)*dnorm(x,mean,sd) if (log) log(r) else r } generate fake data: set.seed(101) r <- rnormgammamix(1000,1.5,2,3,2,0.5) d <- data.frame(r) approach #1: bbmle package. fit shape, rate, standard deviation on log scale, prob on logit scale. library("bbmle") m1 <- mle2(r~dnormgammamix(exp(logshape),exp(lograte),mean,exp(l

VB.NET: Populating ComboBox Using MySQL Query -

i trying populate combobox mysql database; don't anything. below code. table: class columns: code, state sqlstr = "select * class state= not started" dbcmd = new mysql.data.mysqlclient.mysqlcommand(sqlstr, dbconn) dbdr = dbcmd.executereader while (dbdr.read()) cb_class.items.add(dbdr("code")) end while dbcmd.dispose() dbdr.close() i believe result wrong, because there @ least 2 records state values set "not started". wrong? there wrong way i've written "state= not started" ? the command text doesn't seems correct. lacks single quote around string search sqlstr = "select * class state='not started'" ^ ^ if state string field every search on should enclosed in single quotes. beware of potential problems when string search contains single quote. in simple case use directly string constant, if render search dynamic user input should use para

ios - UILabel alignment to other UILabels -

i have cell prototype i'm trying add 2 labels to. have 2 labels right next each other, size of labels dynamic, want second label able shift depending on size of first label. basically, want there fixed gap between 2 labels, 2 labels' sizes dynamic. how do that? edit: actually found out how via storyboard. if select 2 labels want have fixed gap between, command select both of them , go corner of storyboard , click pin menu, little 'h' looking thing in group of buttons near zoom in/zoom out in bottom right corner of storyboard screen. get label size method: - (cgsize)sizewithfont:(uifont *)font https://developer.apple.com/library/ios/#documentation/uikit/reference/nsstring_uikit_additions/reference/reference.html . then set label's textalignment nstextalignmentleft , nstextalignmentright, , set frames string size , other offset.

c# - When using MVC code first with data annotations how do you include html markup in the display name? -

i converting paper form mvc 4 web form. have questions paragraph worth of text include superscript numbers link footnotes. trying do: public class paperformmodel { [display(name = "full paragraph of question text copied straight off of paper form<a href="#footnote1"><sup>footnote 1</sup></a> , needs include formatted superscript and/or link footnote text.")] public string question1 { get; set; } // more properties go here ... } after creating model generated controller , related views. works except html markup in display name converted html encoded text (i.e. &lt;sup&gt;1&lt;/sup&gt;). code in view.cshtml used display property automatically generated code: <div class="editor-label"> @html.labelfor(model => model.question1) </div> <div class="editor-field"> @html.editorfor(model => model.question1) @html.validationme

c# - How can I determine why my mobile .net application is freezing after the device awakes from sleep mode? -

i have .net compact mobile application (device os windows mobile 6.0 using sdk 2.0) running on motorola device. if application running , leave device alone 20 minutes in sleep mode. sometimes, after wake tapping power button, device wakes fine, application frozen, unresponsive. can still see last form page on, can't it. the rest of device responsive, though. trying to close application task manager fails. application remains "active" in frozen state. is there way can diagnose this? like, there special way can log problem or find out via device happened? there's no simple, direct way, no. device comes out of suspend , resumes processing code left off. if app freezing, it's waiting on handle that's been invalidated suspend/resume cycle, way find try twofold approach: instrument code logging when freezes can narrow down "where" in code it's happening. at same time, remove functionality (services, threads, whatever code ba

python - jinja: TemplateSyntaxError: expected token 'name', got 'string' -

have 2 files in flask application: base.html <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="../static/main.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css"> <title>title</title> </head> <body> <div id="content"> {% marker "content" %} </div> </body> </html> upload.html , extends base.html {% extends "base.html" %} {% block "content " %} <title>upload new file</title> <h1>upload new file</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input

C# AutoResetEvent WaitOne stopped by dispatcher -

private void waitfordrivetobecomeready() { autoresetevent syncevent = new autoresetevent(false); //set wait signal use later //dispatcher able change stuff in xaml within thread action action1 = new action(delegate() { grdmain.children.add(notification); }); action action2 = new action(delegate() { grdmain.children.remove(notification); }); thread restorethread1 = new thread(()=>{ grdmain.dispatcher.invoke(system.windows.threading.dispatcherpriority.background, action1); //show notification thread.sleep(1500); //sleep bit... grdmain.dispatcher.invoke(system.windows.threading.dispatcherpriority.background, action2); //hide notification syncevent.set(); //signal continue @ *.waitone() }); restorethread1.start(); syncevent.waitone(); //let main thread wait until *.set(); called } the above code works perfect if comment out 2 grdmain.dispatcher.invoke(...);. works perfekt if comment out *.set(); , *.waitone(); wh

c++ - Boost Asio GCC Link Error -

i've installed clean vm xubuntu 12.10 , i'm trying port on c++ code works on windows. first off, i've installed virtualbox guest additions , gcc , can compile code. i've downloaded boost library internet (boost_1_52) , i've dropped in asio library asio website (boost_asio_1_4_8) , i've installed multi-threading, shared link version using these instructions: ./bootstrap.sh --prefix=/usr && ./b2 stage threading=multi link=shared root: i know fact boost works because i've been able compile test application here (linking lboost_regex) , works perfectly: #include <boost/regex.hpp> #include <iostream> #include <string> int main() { std::string line; boost::regex pat( "^subject: (re: |aw: )*(.*)" ); while (std::cin) { std::getline(std::cin, line); boost::smatch matches; if (boost::regex_match(line, matches, pat)) std::cout << matches[2] << std::endl;

java - Printing Substrings -

i'm print out substrings of word, however; can't last output. import java.util.scanner; public class printer { public static void main(string[] args) { scanner scan = new scanner(system.in); system.out.println("enter word"); string s = scan.nextline(); int i; int j; (i=1; i<s.length(); i++) { (j=0; j+i<=s.length(); j++) { string ss = s.substring(j, j+i); system.out.println(ss); } } } } input thunder output t h u n d e r th hu un nd de er thu hun und nde der thun hund unde nder thunde hunder (missing thunder) sure put system.out.println(s); @ end, want finish loop change outer loop condition i<=s.length

multithreading - The Programming Theory Gods Strike: What is target = foo in Python 2.x? -

often have been browsing q & site, answers use multi-threading , processing have told me use format goes this: (target=foo, args=(bar, baz)) it used in multiprocessing , multithreading (at least limited knowledge.) my question is, what target mean, , can explain how used? i have not been able find explanation in docs or elsewhere. the keyword argument target in threading.thread 's constructor sets entry-point of new thread. can function or object has __call__ method. here's example using function: import threading def foo(number, name): print 'hello new thread' print 'here arguments:', number, name thread = threading.thread(target=foo, args=(5,'bar')) thread.start() thread.join()

clojure - how to separate concerns in the below fn -

the function below 2 things - checks if atom nil or fetch-agin true, , fetches data. it processes data calling (add-date-strings). what better pattern separate out above 2 concerns ? (def retrieved-data (atom nil)) (defn fetch-it! [fetch-again?] (if (or fetch-again? (nil? @retrieved-data)) (->> (exec-services) (map #(add-date-strings (:time %))) (reset! retrieved-data)) @retrieved-data)) one possible refactoring be: (def retrieved-data (atom nil)) (defn fetch [] (->> (exec-services) (map #(add-date-strings (:time %))))) (defn fetch-it! ([] (fetch-it! false)) ([force] (if (or force (nil? @retrieved-data)) (reset! retrieved-data (fetch)) @retrieved-data))) by way, pattern seperate out concerns called "functions" :)

regex - Regular expression forums in python with examples -

i'm new python , i'm working code requires me make use of regular expressions substantially. i've gone through python documentation regular expressions ( http://docs.python.org/2/library/re.html ) however, since i'm new python find hard implement functions specified within documentation data need work with. i wondering if there's forum out there explains regular expressions in python multiple examples each function , possible variations. more merrier. i've found ( http://docs.python.org/2/howto/regex.html ) , ( http://flockhart.virtualave.net/rbif0100/regexp.html ) far. i've found them useful wondering if there out there that's better. you can try pythonregex , python specific , generates python code regular expressions. enjoy!

javascript - Set dojox.grid.datagrid header column width dynamically -

i have declarative dojox.grid.datagrid initial header column width. , have textbox. need is in ui, if user enters value textbox, value should set dynamic width of column's header. <div class="claro" id="dfgdfgd" name="datagrid" onclick="setwidgetproperty(this.id,'xy','inner__dfgdfgd');" ondblclick="editcustomgrid(this.id)" onmouseup="setdocstyle(this.id)" style="height:200px; left:42px; position:absolute; top:89px; width:950px;"> <table class="claro" dojotype="dojox.grid.datagrid" id="inner__dfgdfgd" rowselector="10px" style="height: 180px; width: 300px;"> <thead> <tr> <th field="column1" id="column1" noresize="true" width="100px"> <label id="column1" onclick="getcustomgridcolname(this.id,'inner_

c - Assigning static/same IP address to the Server everytime it logs in -

i working on udp server/client applicataion. since communicating server, clients must know ip address , port number of server. purpose, have hard coded ip , port number of server clients everytime, client connects same ip , port number. (found ip address of server machine using ipconfig command.) now, problem working on dhcp network, , there chance everytime sever machine restarted, new ip address may assigned (different ip address known clients @ connect.) so, want ip address hard coded @ client side assigned server machine, everytime logs in. there way it? have no idea it. searched internet couldn't find relevant. looking forward :( assuming clients local server, why not abandon hard-coded server ip address, , borrow page dhcp , use kind of service discovery method: your clients broadcast "where server" message when first come online. server responds "i @ ip address x.x.x.x" when server comes up, broadcasts "server @ ip address y.y.y

sql - postgresql-8.4 text search is not working -

i tried implement full/partial text search using postgresql-8.4 & django select * fts body_tsvector @@ plainto_tsquery('english','hello welcome') available records are 'hello world' 'hello old world' 'hi welcome' but result of query not expected,which displays 0 records,.how partial/full text search possible using plainto_tsquery?thanks in advance. it looks expecting plainto_tsquery perform | (or) query. the docs state: plainto_tsquery transforms unformatted text querytext tsquery. text parsed , normalized to_tsvector, & (and) boolean operator inserted between surviving words. so want must parse text yourself, create ts_query | operator. select * fts body_tsvector @@ to_tsquery('english','hello | welcome');

ios - iPhone/iPad different view orientations in different views , and apple approval process -

i force app's home screen portrait , other views landscape. apple rejects app if this? if not , how force first screen launch in portrait mode? , force other screens launch in landscape. this not duplicate question search every possible answer in website. i force app's home screen portrait , other views landscape. apple rejects app if this? no apple not reject app this. have lot of apps doesn't support orientation. forcing on 1 screen won't cause app reject. if not , how force first screen launch in portrait mode? , force other screens launch in landscape. can on write : -(nsuinteger)supportedinterfaceorientations; function.

asp.net mvc - jquery code working in every browser except ie8 -

this scenario. creating image upload using iframe. situation this, if hovers on iframe, div opens on has 2 buttons. 1 button select image clear image present in iframe. this code of view: @using (html.beginform("index", "landingsetting", formmethod.post, new { enctype = "multipart/form-data" })) { @html.validationsummary(true) <div id="menu" class="tip_trigger"> <iframe width="731" height="335" src="@viewdata[" htmlloc "]"></iframe> <div id="inner" class="hover-text"> <table> <tr> <td width="50%" align="center" valign="middle"> <img id="slctbtn" src="../../images/landing/s_btn.png" /> </td>

ruby on rails - rake task return on calling task -

i return rake task in calling task. possible? something in example, able call task 1 , 1 independantly 1 , 2 sequentially. task: 1 work if work ok task.return true else puts "task 1 ko" task.return false end end task: 2 work if work ok task.return true else puts "task 2 ko" task.return false end end task: rake::task["one"].invoke rake::task["two"].invoke end i not able return in "all" task. , "return" , abort("message") quit script. solution : tasks lambda blocks that's why have use "next" instead "return".

performance - R: performence, memory use. Writing a text file or keeping all the information in R objects? -

through iteration construct big matrix , in order speed these iterations split matrix chunks put in list. would have better save chunks of matrix text file , append new chunk on same text file instead of keeping them in list. change in terms of memory use , performence (time run simulation) ? second question: there way know memory size of r object (without having save .rdata file) thank in advance ! retain matrix in ram if possible. else can bigmemory package . and latest version of r has better support large vectors. helpful if have 64-bit machine large amounts of ram. note:since talking performance, practice pre-allocate matrix (instead of frequent use of rbind / cbind)

Custom password field with devise (ruby) -

i'm using database shared between 2 rails apps. a webapp using bcrypt , has_secure_password authenticate user, , app, rest api, using devise authenticate users. password hash same. so, use field password_digest instead of encrypted_password authenticate via devise , don't know how ! (i'm seeking in documentation find nothing). so, have copy / paste password hash password_digest encrypted_password yet. here session controller code : class sessionscontroller < devise::sessionscontroller before_filter :ensure_params_exist def create build_resource resource = user.find_for_database_authentication(:email => params[:email]) return invalid_login_attempt unless resource if resource.valid_password?(params[:password]) #resource.ensure_authentication_token! #make sure user has token generated sign_in("user", resource) render :json => { :authentication_token => resource.authentication_token, :lastname => r

java - Browse Servlet for CKEditor to Browse Database items -

i have database entities called category, article, poll etc.. need write browse servlet ckeditor through should able browse db table rows link text in editor. please let me know whether possible. if possible please give me way proceed.

jQuery code works differently on different servers -

i have following jquery snippet: $('#something').hover( function () { $(this).stop().animate({'width':'220px'},1000, 'easeoutexpo').css('overflow','hidden'); $('.faded').stop().fadeto('slow', 1); }, function () { $(this).stop().animate({'width':'40px'},1000, 'easeoutexpo').css('overflow','visible'); $('.faded').stop().fadeto('slow', 0); } ); for following html: < li id="something">< href="someurl" title="a thing">< span class="faded">some text< /span>< /a>< /li> this works charm on local server , online server, on client server snippet of code gets ignored totally , css :hover works instead though other function in same .js file

c# - Calendar Extender date picking and converting into correct format -

i picking value calender extender in textbox , getting value in format {"mm/dd/yyyy"} want in format {"dd/mm/yyyy"} in textbox ( txt_actualrightformat.text ) code shown below datetime wrongformat = datetime.parse(textbox4.text); string rightformat = string.format("{0:dd/mm/yyyy}", wrongformat.date); txt_actualrightformat.text = rightformat.tostring(); datetime irespective of format, format displaying purpose. if not getting right date in wrongformat can use datetime.parseexact format. , txt_actualrightformat.text = wrongformat.tostring("dd/mm/yyyy"); edit: use datetime.parseexcat like: datetime dt = datetime.parseexact(textbox4.text, "mm/dd/yyyy", cultureinfo.invariantculture); txt_actualrightformat = dt.tostring("dd/mm/yyyy");

php - How to pass variables in URL and page? -

my code in index.php: <?php $keyword = ($_get['keyword']); $adid = $_get['adid']; header("location: http://www.tracking.com/base.php?asdf&keyword=&ad=" .$keyword .$adid); ?> the tracking link supposed end with: &keyword={keyword}&ad={adid} i need pass keyword , adid through url onto landing page redirects , pass both variables tracking link. this url trying: www.example.com/?keyword={keyword}&ad={adid} i don't think can test if format above correct unless run search traffic it. i need on getting codes right , getting url pass them correctly. edit: did format url pass variables correctly? change this header("location: http://www.tracking.com/base.php?asdf&keyword=&ad=" .$keyword .$adid); to header("location: http://www.tracking.com/base.php?keyword=$keyword&ad=$adid");

windows phone 7 - WP7, WP8 How to set several ResourceDictionaries to use custom FontFamilies -

i want set custom fonts controls, if set font inside one resourcedictionary , use in styles works fine . approach not fine me, because need have font declarations in separate dictionary styles using them. in app.xaml have made several resource dictionaries <application ...> <application.resources> <resourcedictionary> <resourcedictionary.mergeddictionaries> <resourcedictionary source="resources/resourceagencydictionary.xaml"/> <resourcedictionary source="resources/resourcecommondictionary.xaml"/> </resourcedictionary.mergeddictionaries> </resourcedictionary> </application.resources> .... </application> in resourceagencydictionary.xaml have myfontfamilynormal declaration <resourcedictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schem

java - Using this.var during var's initialization -

this question has answer here: recursive initializer works when add “this”? 3 answers while researching another question , surprised discover following java code compiles without errors: public class clazz { int var = this.var + 1; } in jdk6, var gets initialized 1 . does above code have well-defined semantics, or behaviour undefined? if it's well-defined, please quote relevant parts of jls . it mentioned in passing in example 8.3.2.3-1 in section 8.3.2.3 . in text example class z { static int peek() { return j; } static int = peek(); static int j = 1; } class test { public static void main(string[] args) { system.out.println(z.i); } } the caption says: ... variable initializer uses class method peek access value of variable j before j has been initialized variable initializer, @ point still has default v

size - C++: BOOST-ASIO async_read_some does not return number of packet bytes? -

i tried using following code read number of available bytes in socket (on server side) , variable packet_bytes not anything. expecting number of bytes used packet read packet_bytes doesn't seem work. std::size_t packet_bytes = 0; socket_.async_read_some(boost::asio::buffer(data_, max_length), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, packet_bytes)); i tried std::size_t packet_bytes = socket_.available(); , didn't return either. entire code . the packet_bytes argument in bind call should placeholder: socket_.async_read_some(boost::asio::buffer(data_, max_length), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); then in handler function argument amount of bytes read. see e.g. example in manual .

algorithm - Bidirectional Bubble sort c# -

i have homework assignment of coding bidirectional bubble sort. can please see if logic correct respect it. don't want code want figure out myself. want logic check of how understand it. as understand bidirectional bubble sort implement 2 loops 1 starting @ position 1 in list , performing normal bubble sort. first loop reaches end second 1 implemented working in reverse. don't understand terminating conditions each loop be. would loop conditions follows? loop 1 - for(i = 0; < count -i; i++) loop 2 - for(j = count - i; j > i; j--) in each loop swap conditions specified. thanks the "classic" bubble sort goes through entire array on each iteration, loops should be for(i = 0; < count - 1; i++) and for(j = count - 1; j > 0; j--) both loops skip 1 index: first loop skips last index, while second loop skips initial one. code safely compare data[i] data[i+1] , , data[j] data[j-1] . edit "optimized" bubble sort skips

java Extracting Zip file -

i'm looking way extract zip file. far have tried java.util.zip , org.apache.commons.compress, both gave corrupted output. basically, input zip file contain 1 single .doc file. java.util.zip: output corrupted. org.apache.commons.compress: output blank file, 2 mb size. so far commercial software winrar work perfectly. there java library make use of this? this method using java.util library: public void extractzipnative(file filezip) { zipinputstream zis; stringbuilder sb; try { zis = new zipinputstream(new fileinputstream(filezip)); zipentry ze = zis.getnextentry(); byte[] buffer = new byte[(int) ze.getsize()]; fileoutputstream fos = new fileoutputstream(this.tempfolderpath+ze.getname()); int len; while ((len=zis.read(buffer))>0) { fos.write(buffer); } fos.flush(); fos.close(); } catch (filenotfoundexception e) { // todo auto-generated catch block

Microsoft Dynamics CRM 2011. Generic method to get entity by ID -

in crm 4.0 had generic method in repository: public t getentitybyid(guid id) { var entities = e in m_context.getentities(typeof (t).name) e.getpropertyvalue<guid>(identityfieldname) == id select e; return (t) entities.firstordefault(); } but crm 2011? icrmentity getpropertyvalue method missed... what alternate generic entity id? something (t) m_context.retrieve(typeof (t).name, id, new columnset()) . see here

ios - Notification bar in iPhone apps -

Image
i create notice bar, active-phone-call notice bar, whenever user losses connection server. is there easy way this? can't find in api, there must supported way - or should program manually? example: difference being want active while in app , want define text myself. there no direct api available doing this, can change status bar color this self.window.backgroundcolor = [uicolor colorwithred:0.78f green:0.13f blue:0.11f alpha:1]; [[uiapplication sharedapplication] setstatusbarstyle:uistatusbarstyleblacktranslucent]; and add view below custom text. or, if want put information in status bar custom color, take @ kgstatusbar or mtstatusbaroverlay .

css - Display four lists horizonally -

how display 4 (4) unordered lists horizontally? lists.html <!doctype html> <html lang='en'> <head> <meta charset="utf-8" /> <title> html lists </title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <h1> html lists </h1> <div id="container"> <ul id="k"> <li>katakana</li> <li>katakana</li> <li>katakana</li> <li>katakana</li> <li>katakana</li> </ul> <ul id="ki"> <li>katakana-iroha</li> <li>katakana-iroha</li> <li>katakana-iroha</li> <li>katakana-iroha</li> <li>katakana-iroha</li> </ul> <ul id="h"> <li&g

python - Remove Duplicates from Text File -

i want remove duplicate word text file. i have text file contain such following: none_none confighandler_56663624 confighandler_56663624 confighandler_56663624 confighandler_56663624 none_none columnconverter_56963312 columnconverter_56963312 predicatesfactory_56963424 predicatesfactory_56963424 predicateconverter_56963648 predicateconverter_56963648 confighandler_80134888 confighandler_80134888 confighandler_80134888 confighandler_80134888 the resulted output needs be: none_none confighandler_56663624 columnconverter_56963312 predicatesfactory_56963424 predicateconverter_56963648 confighandler_80134888 i have used command: en=set(open('file.txt') not work. could me how extract unique set file thank here's option preserves order (unlike set), still has same behaviour (note eol character deliberately stripped , blank lines ignored)... from collections import ordereddict open('/home/jon/testdata.txt') fin: lines = (line.rst

c# - Get records on the base of one field which should distinct -

Image
i have query like select distinct(a.createdon), a.id id , u1.firstname createdbyfirstname, u1.lastname auditdetail left join userprofile u1 on a.createdby = u1.userprofileid left join userprofile u2 on a.updatedby = u2.userprofileid this shows me records. , distinct createdon repeated in each records because records comming. want if createdon same in records first record or single record should come not all. i'm wrong? you can use ranking function such row_number() give rank on each record every group. with recordlist ( select a.createdon, a.id id , u1.firstname createdbyfirstname, u1.lastname, row_number() over(partition a.createdon order a.createdon) rn auditdetail left join userprofile u1 on a.createdby = u1.userprofileid left join userprofile u2 on a.updatedby = u2.userprofileid ) select createdon, id,

javascript - Geolocation with PhoneGap on Android -

i work on application using phonegap. moment, test on android. have several pages in application need geolocation feature. so made js handle line of code (of course it's not unique line of code) : navigator.geolocation.watchposition(successgeolocation, errorgeolocation, {maximumage: 5000, enablehighaccuracy: true}); the geolocation need accurate possible use gps , can take time have gps fix. the problem when user navigates 1 page another. watchposition stop (it's normal because user load other page) , when recall gps need fix again. it's annoying , search solution keep gps active. has idea me ? maybe plugin or native android loc can keep active during application life ? thanks. first step should create android plugin give api receiving location data. creating plugin quite easy , explained here: plugin development guide , developing plugin on android . can see example of creating cordova plugin here . next, create location monitor class. can make

.net - Detecting the time when the program was installed -

Image
this question has answer here: get install date managed code 5 answers can somehow detect time when program installed using .net or win32 api or other way? this date of installation, i'm not sure of can time string registry_key = @"software\microsoft\windows\currentversion\uninstall"; using(microsoft.win32.registrykey key = registry.localmachine.opensubkey(registry_key)) { foreach(string subkey_name in key.getsubkeynames()) { using(registrykey subkey = key.opensubkey(subkey_name)) { console.writeline(subkey.getvalue("displayname")); console.writeline(subkey.getvalue("installdate")); } } } you can use these fields for more info refer this answer. you can time using windows installer api! function used msigetproductinfo , property name installproperty_inst

c++ - Displaying the function call stack in vim -

is there way display in vim/gvim call stack of function while editing (not while running) code? using linux , c++. suppose example of code below void foo3(){} void foo2(){} void foo1(){ foo2(){ foo3(){ } } } i looking vim command or plugin able display list below foo1() foo2() foo3() i suggest have @ http://www.vim.org/scripts/script.php?script_id=2368 , descent , serve purpose me.

jquery - Mouseover Grayscale not working in IE9 -

i having issues mouseover state in ie9 , hoping me. this element various sizes , why reluctant use background image sprite. my issue when hover on item image turns grey, when hover on tick in middle gray scale effect lost, guessing ie9 thinks no longer hovering on item, when am. http://www.tindlemanor.co.uk/jtest/cameron/11.html i have played mouse on example on jquery , works in ie9, guesing doing bit stupid. it works in other browsers, including ie8 , ie7, if happened in 7 understand , let slide, fact in 9, means need address this. thanking in advance. cameron the issue may caused conflict between :hover pseudo class in css , onmouseover , onmouseout events in jquery. think have found solution background losing filter when hover on green tick though: jsfiddle appears work in ie9 , chrome still. jsfiddle doesn't work in firefox, think that's down other reasons. i restructured jquery onmouseover , onmouseout events hover() event (i doubt

jquery - Using delegate to swap classes -

i using jquery delegate function toggle classes no success , want toggle class of <li class="unselected-values"> to <li class="<li class="unselected-values"> when client clicks on label, ideas m getting wrong , suggestion or assistance appreciated. thnx <ul class="option-list swatch pockets"> @foreach (var pvavalue in attribute.values) { <li class="unselected-values"> <input id="@(controlid)_@(pvavalue.id)" type="checkbox" value="@pvavalue.id" checked="@pvavalue.ispreselected" /> <label for="@(controlid)_@(pvavalue.id)" style="background-image:url(@(pvavalue.menuicon))">@pvavalue.name</label> &

forms - HTML - use of the onbeforesubmit attribute -

i found form event attribute called onbeforesubmit processes given function/request before form submitted. while found useful, seems strange me no 'official' documentation found event attribute, vague reference microsoft web page , forums. no w3schools or w3 reference (not far have looked up). is old/deprecated event attribute or maybe experimental one? have tested google chrome far. its , old attribute . work can replaced onsubmit. can write code in manner of want execution , cal on onsubmit

java - Queuing requests to have just a single user "working" -

basically i'm trying build java webapp interface arduino. due "phisical" limitation have 1 user @ time working microcontroller. i create queue requests , set limit (i.e. 20 seconds) , go next user. there in future option have 2 users connected "interact" each other. how can implement infrastructure? jms? other ways? i've used other mqs kestrel "strings", , i've no clue on how use in case. : / (i use jboss if relevant, or helpful) thanks in advance! there rxtx java library comes arduno , suggest use arduno interface.

c# - ControllerColliderHit makes position change in unity 3d -

Image
i attached script character controller. when character controller hit on collider, transform positon of character controller changes. void oncontrollercolliderhit(controllercolliderhit hit) { if(hit.collider.gameobject.name =="point"){ print("hit point"); } else { startcoroutine( "gameover" ); } } why happen so. solution escape issue?

vba - Using excels named range in a sql string in VBScript -

i have searched on here , google still cannot solve issue. trying use excel's named range equivalently in .vbs file. below works in vba in excel cannot work in *.vbs file. thisworkbook.sheets(1).range("a1:b" & range("b" & rows.count).end(xlup).row).name = "data" strsql = "select * data" so, have tried different variations of referencing named range data no luck. have now: set rng = ws.range("a1:b2") rng = "data" strsql = "select * data" some different variations involved: taking parameter byval, using rng instead of data (string type), select * " & rng, etc.. the error msg when running: microsoft (r) windows script host version 5.8 copyright (c) microsoft corporation. rights reserved. c:\users\admin\desktop\updatesourcetbl.vbs(119, 5) microsoft jet databas e engine: microsoft jet database engine not find object 'data'. m ake sure object exists , spe

tomcat - TomeEE Java Version 5 -

i installed tomee plus version 1.5.1. has tomcat version 7. can tomee used tomcat 6? possible? having quick search on google, doesn't give back. consider openejb instead of tomee. manual installation

java - Intent.createChooser android QR code reader -

i want user choose qr reader installed apps. done using intent.createchooser. when picture taken qr reader, qr code should sent application. ive tried far: intent intent = new intent(intent.action_send); intent.settype("text/plain"); intent.addflags(intent.flag_activity_clear_when_task_reset); intent.putextra("scan_mode", "qr_code_mode"); string title = (string) getresources().gettext(r.string.chooser_title); intent chooser = intent.createchooser(intent, title); startactivityforresult(chooser, custom_request_qr_scanner); the scanner doens't start correctly, shows sample qr code. have feeling intent.settype("text/plain") might wrong? type qr reader? or how start qr reader way correctly? i have activityresult when qr app done: @override public void onactivityresult(int requestcode, int resultcode, intent intent) { if (requestcode == custom_request

Java Servlet - Observer Pattern causing null Response object -

i have java httpservlet. servlet contains set of objects make use of observer pattern in order return data through servlet's response object. here simplified version of doget() method in httpservlet: protected void doget(final httpservletrequest request, final httpservletresponse response) myprocess process = new myprocess(); // following method spawns few threads, use listener receive completion event. process.performasynchronousmethod(request, new mylistener() { public void processcomplete(data) { response.getwriter().print(data.tostring()); } } } as example shows, have process execute, spawns variety of threads in order produce final dataset. process can take anywhere seconds minute. problem is, appears doget() method completes, response object becomes null. when processcomplete() called, response object null - preventing me writing data out. it appears if servlet closing connection asynchronous method called. is there bett

sql - check if the column value exists in subquery -

i have 3 tables product category , productcategory. product table: productid productname 1 p1 2 p2 3 p3 category table: categoryid categoryname 1 c1 2 c2 3 c3 productcategory: productid categoryid 1 1 1 2 1 3 2 3 3 1 3 2 i need query returns products fall under more 1 categories. based on table data above result be: productid productname 1 p1 3 p3 so wrote query fetch productid's have more 1 categoryid's below: select productid,count(categoryid) productcategory group productid having count(categoryid)>1) but when try display product details using below query error: select * product productid in ( select productid,count(categoryid) productcategory group productid having count(categoryid)>1)) is query wrong? how required product details

perl - Using Spreadsheet::WriteExcel -

i want extract information 1 excel sheet , re-format one. data structure looks like: col1 col2 row1 school 1 row2 dean john row3 no.stu. 55 row4 irrelevant stuff row5 school2 2 row6 dean tony row7 no. stu. 60 row8 irrelevant stuff row9 school 3 row10 dean james row11 no.stu. 56 row12 no. teacher 20 the output achieve is: col1 col2 col3 row1 school dean no.stu. no. teacher row2 1 john 55 row3 2 tony 60 row4 3 james 56 20 and code have been advised use extract information excel following (thanks hdb perlmonks ). use strict; use warnings; use spreadsheet::parseexcel; ($infile) = @argv; $parser = spreadsheet::parseexcel->new(); $workbook = $parser->parse($infile); die $parser->error unless defined $workbook; ($worksheet) = $workbook->worksheets(); %data; # accumulate data here $row = 0; $school = 0; while (1) { $cell = $worksheet->get_cell($row, 0); last unless defined($

c++ - Floating point comparison -

this question has answer here: floating point inaccuracy examples 7 answers int main() { float = 0.7; float b = 0.5; if (a < 0.7) { if (b < 0.5) printf("2 right"); else printf("1 right"); } else printf("0 right"); } i have expected output of code 0 right . dismay output 1 right why? int main() { float = 0.7, b = 0.5; // these floats if(a < .7) // double { if(b < .5) // double printf("2 right"); else printf("1 right"); } else printf("0 right"); } floats promoted doubles during comparison, , since floats less precise doubles, 0.7 float not same 0.7 double. in case, 0.7 float becomes inferior 0.7 double when gets promoted. , christian said, 0.5 being power of 2 r

ios - restricting autorotation on certain views -

Image
my app contains 2 table view controllers. in first 1 want view able rotated left , right (in addition portrait mode), in second table view controller ( navigate after tapping cell first table) want viewed in portrait mode. tried code didn't work, keeps on rotating. - (nsuinteger)supportedinterfaceorientations { return uiinterfaceorientationmaskportrait; } - (bool) shouldautorotate { return no; } note: did enabled left/right/portrait orientation summary tab of project target. fix? create category uinavigationcontroller include following methods: (works both ios 6 , ios 5) - (bool)shouldautorotate { return self.topviewcontroller.shouldautorotate; } - (nsuinteger)supportedinterfaceorientations { return self.topviewcontroller.supportedinterfaceorientations; } - (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)tointerfaceorientation { return [self.topviewcontroller shouldautorotatetointer

symfony - Use placeholders in translation using tags -

in symfony / twig, use tags using percentages in translated block. example: hello {{nickname}} would become {% trans %}hello %nickname%{% endtrans %} this works expected. array placeholders pass twig, automatically mapped %placeholder%. no work involved. works php array controller being: array('nickname' => 'rolandow') when want use nickname inside translation block, have surround percentages %. unfortunately, doesn't seem work when pass trans . now translate whole block of text, using tags. can't figure out how can use tags in translation. so, twig this: {{ say.hello|trans }} and translation snippet <trans-unit id="1"> <source>say.hello</source> <target>hello %nickname%, how doing today? lots-of-text-here</target> </trans-unit> i got working using in template, feels doing things twice. need put array of placeholder trans function again. example: {{ say.hello|trans('%nickname%&#

ruby - rvm system install, bins not properly symlinked -

i'm on ubuntu 12.04 , installed rvm system wide with: $ \curl -l https://get.rvm.io | sudo bash -s stable so far i've performed single user installs , honest i'm quite confused results of system wide install. did put rvm bin directory in path, symlinked binaries names can't directly used. mean should symlink them 1 one? did go wrong? defalt behaviour? appusr@server-name:/usr/local/rvm/bin$ ll total 60 drwxrwsr-x 2 root rvm 4096 apr 5 13:11 ./ drwxrwsr-x 23 root rvm 4096 apr 5 13:04 ../ -rwxrwxr-x 1 root rvm 578 apr 5 13:04 bundle* lrwxrwxrwx 1 appusr rvm 41 apr 5 13:11 erb-ruby-2.0.0-p0 -> /usr/local/rvm/wrappers/ruby-2.0.0-p0/erb* lrwxrwxrwx 1 appusr rvm 48 apr 5 13:11 erb-ruby-2.0.0-p0@global -> /usr/local/rvm/wrappers/ruby-2.0.0-p0@global/erb* lrwxrwxrwx 1 appusr rvm 41 apr 5 13:11 gem-ruby-2.0.0-p0 -> /usr/local/rvm/wrappers/ruby-2.0.0-p0/gem* lrwxrwxrwx 1 appusr rvm 48 apr 5 13:11 gem-ru

c++ - "No known conversion" from const when passing "this" as a parameter -

i making game utilizes state stack manager keeps track of different game states, main menu. however, have encountered problem can't seem solve. this state class, stripped down contain offending code: class statemanager; namespace first { namespace second { class state { friend class statemanager; protected: /** * associates state specified state manager instance. * @param statemanager instance associate state */ void associatewithmanager(statemanager *statemanager) { mstatemanager = statemanager; } private: statemanager *mstatemanager; }; } // second } // first the following state manager, stripped down: namespace first { namespace second { class statemanager { public: /** * adds state stack. * @param state state add */ state &add(state &state) { state.associatewithmanager(this); return state; } }; } // second } // first when try compile this, following error (line numbe