Posts

Showing posts from August, 2014

java - Making my computer prompt me with a predeterminedquestion whenever I open firefox -

i'm inspired reading john conway's wikipedia page: http://en.wikipedia.org/wiki/john_horton_conway#algorithmics i want have window pop whenever open firefox ask question code. i'd type in response in text box , upon hitting return display answer , whether i'm correct or not. i'm thinking of right i'd random number in centimeters between, say, 0 , 300 , try correct amount of inches corresponds to. i have no idea how start going this. how make program execute when click , turn on browser? have experience swing perhaps use i've looked through of swing library no avail. put java tag there because it's language i'm familiar solution in java best if possible. also, there resources learn how stuff this? i think main problem getting prewritten code run upon opening browser. rest can deal in swing i'm not sure. lastly, sorry non-space between predetermined , question, site doesn't let me use second word in title though makes sense here.

caliburn.micro - Is it possible to have Intellisense in XAML when using Caliburn automatic datacontext? -

when use caliburn, view gets datacontext set dynamically @ runtime convention. however, nice if set in designer vs , compiler verify , provide intellisense without interfering caliburn binding. if set myself, like: datacontext="myapp.mainviewmodel" i don't caliburn binding. is possible set designer? i think can take advantage of design-time support provided caliburn.micro. you have set desinger-datacontext , tell cm enable magic in view xaml: xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:caliburndesigntimedata.viewmodels" xmlns:cal="clr-namespace:caliburn.micro;assembly=caliburn.micro" mc:ignorable="d" d:datacontext="{d:designinstance type=vm:mainpageviewmodel, isdesigntimecreatable=true}" cal:bind.atdesigntime="true" for work, viewmodel must have default cons

c# - How to update a user? -

the goal update user's table consistently. the problem i have edit information of specific user , don't know how. firstly, there's users table on application stores information of user. secondly, can't think in recursive way this. there're multiple columns on users table , don't know how edit columns user requested. any idea? what want? i'm not executing query through c#. need database came via stored procedure. (except basics .select() , firstordefault() , etc.). in other words, need 2 things: a (mysql) recursive query syntax idea; i need c# method invoke stored procedure this: user user = new user("chiefmaster@test.com"); // target of update. updateuser (user.email => "masterchief@test.com", // old "chiefmaster@test.com" user.nickname => "masterchief" // old "chiefmaster"); as can see, i'm updating email , nickname of specific user — should not affect ot

jquery - Triggering audio on hover and triggering different audio on click of same div? -

i have div image in it. on hover of image want 1 audio play, on click of same image want audio play. code far, doesn't seem work? ideas? thanks <div id="one"> <img src="lib/images/check-mark-32.png" alt=""/></div> <audio id="sound-1a"> <source src="lib/sound/01 partitano.1.mp3"></source> <source src="lib/sound/01 partitano.1.ogg"></source> browser isn't invited super fun audio time. </audio> <audio id="sound-1"> <source src="lib/sound/01 solo piano - 1 - metamorphosis.mp3"></source> <source src="lib/sound/01_solo_piano_1_metamorphosis.ogg"></source> browser isn't invited super fun audio time. </audio> <script> var audio = $("#sound-1a")[0]; $("#one").mouseenter(function() { audio.play(); }); var audio = $("#sound-1")[0]; $("#one").click(functi

javascript - Need to hide a selected element based on conditions -

i have drop down menu various options new in progress ordered not ordered completed cancelled i have form need hide eta row when status new, enable other status. tried: var progress, ordered, unordered, completed, cancelled, reg, high, user, trimuser, etadate, etarow, etahour, etaminutes; function initiate() { //declaring necessary variables declaration() } function declaration(){ //declaration of variables status changes snew = $("option[value='new']"); progress = $("option[value='in progress']"); ordered = $("option[value='ordered']"); unordered = $("option[value='unordered']"); completed = $("option[value='completed']"); cancelled = $("option[value='cancelled']"); //declaring variables priority changes reg = $('input[value="ctl00"]'); high = $('input[value="ctl01"]');

c++ - Should I listen on different ports, or the same port? -

i'm writing c++ application mymasterapp (windows & mac) listening bunch of information coming different computers , applications. (osc via udp) i.e. mymasterapp listening tracking data coming number of tracker applications (which may or may not running on same computer, on same wired network). it's listening orientation data coming number of other applications (running on mobile devices, on same wifi). apps sending @ 30hz. so: /tracker/position1/[f] [f] [f] /tracker/position2/[f] [f] [f] /tracker/position3/[f] [f] [f] /mobile/orientation1/[f] [f] [f] [f] /mobile/orientation2/[f] [f] [f] [f] /mobile/orientation3/[f] [f] [f] [f] i'm wondering whether there difference (in network performance, collisions etc) if: mymasterapp should listen messages on port 8000, , tracker apps, , mobile apps send port 8000 vs mymaster listens to tracker messages on port 8000, , mobile messages on port 9000. both seem work fine, i'm wondering if there perfor

Sharepoint error logging by the system -

i have worked on php (lamp) , have started working on sharepoint. in case of php errors captured , shown in apache error log in case of sharepoint have use try , catch block , use code shown below capture error. working fine me. no issues it. downside - have vigilant enough make sure put try catch every possible place. i want php, i.e. log things automatically. please help. microsoft.sharepoint.spsecurity.runwithelevatedprivileges(delegate() { spdiagnosticsservice diagsvc = spdiagnosticsservice.local; spdiagnosticscategory cat = diagsvc.areas["sharepoint foundation"].categories["unknown"]; string format = "test trace logging gggg category {0} in area {1}"; diagsvc.writetrace(1, cat, traceseverity.medium, format, cat.name, cat.area.name); }); i'm afraid ahve deal errors yourself. sharepoint implements own logs things

distribution - Gaussian fit to discrete values -

Image
i'm new in c++ , i'm struggling this. have matrix discrete values adapt gaussian distribution. need algorithm in c++ define parameters of gaussian fit. suggestions or help?? 1 of vectors in data set {14, 3, 2, 83, 263, 236, 101, 27, 7, 13, 12, 8} increment 2 ns between each value. thanks lot as bathsheba said, that's needed characterize gaussian (a.k.a. normal) distribution mean , variance. can estimate these sample mean , sample variance s^2 of data, respectively. however, shouldn't so ! histogram , normal quantile plot of data show nothing gaussian distribution. gaussians should have histogram bell-shaped , symmetric. data, despite small sample size, skewed exponential distribution doesn't particularly fit. in normal quantile plot, if data gaussian points fall along relatively straight line (the red line best fit straight line values) , within dotted-line boundaries. data aren't vaguely close being fit normal distribution.

function evaluation order in C -

this question has answer here: why these constructs (using ++) undefined behavior? 12 answers increment values in printf [duplicate] 3 answers #include <stdio.h> print(int* a,int* b,int* c,int* d,int* e) { printf("\n%d %d %d %d %d\n",*a,*b,*c,*d,*e); } main() { static int arr[]={97,98,99,100,101,102,103,104}; int *ptr=arr+1; print(++ptr,ptr--,ptr,ptr++,++ptr); } output: 100 100 100 99 100 i little confused output. because of undefined evaluation order of function or there else missing?

c++ Pass quoted string as char array to a function -

so have function declared as: void writefile (unsigned char *filename, unsigned char *data) if call function this: writefile("f.txt", "test1"); is fine. if second call this: writefile("s.txt", "test2\nline"); the filename fine, data corrupted (the first 5 bytes messed up). if third call this: writefile("f.txt", "test3\r\nline"); the filename corrupted, , data has it's first 5 bytes messed up. what going on? i believe problem has using unsigned chars, when put code complains on compile it. may have unsigned char not being able use escape characters \n , can't sure. intellisense: argument of type "const char *" incompatible parameter of type "unsigned char *" is compile error get. when changed being regular char * parameters, worked fine.

html - Centering a div which contains images -

i'm trying centre images failed so. added margin: auto; images not working. when removing float: left; carousel, structure gets messed up. how can centre images? thanks <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var showing_default = true; var did_scroll = false; $(window).on("scroll", function (e) { did_scroll = true; }); window.setinterval(function () { if (did_scroll) { did_scroll = false; if (showing_default && $(document).scrolltop() >= 100) { showing_default =

javascript - Control table width with Jquery issue -

i have question regarding ie7 i want make every column of table has same width no matter contents have $("table").each(function(){ var column =0; var totalwidth = $(this).width(); $('tr:nth-child(1) td',this).each(function(){ column ++; }) var cellwidth = totalwidth / column; $('td', this).css('width', cellwidth); }) my codes work perfect on chrome , ff not ie 7. not sure why. can me it? lot! nth-child css3 selector , not supported ie 7. try else.

tags - Jquery Mixitup plugin help prevent handlers being destroyed -

update : error in console. uncaught exception: query function not defined select2 undefined i using code allow users add tags images. works fine. problem running when images sorted(using mixitup.io plugin). before sorting, script works perfect(popup,edit,save,db update). after user clicks few of sort buttons, script stops responding , popup not fire. please have below , me find problem is. :) working code: $('.tags').editable({ placement: 'top', select2: { tags: ['cookies', 'pie','cake'], tokenseparators: [","] }, display: function(value) { $.each(value,function(i){ value[i] = "<span class='tagbox'>" + $('<p>' + value[i] + '</p>').text() + "</span>"; }); $(this).html(value.join(" ")); } }); to prevent mixitup.io plugin destroying handler, says use "delegate()"

How do I customize the message displayed in a users Facebook friend request (invite)? -

i have this, , want 'check out app' displayed in users notification. fb.ui({method: 'apprequests', message: 'check out app', }); but message not displayed want: it says 'kamil has sent request.' http://cl.ly/image/1g3z0y0h1x0c sadly, apprequests 'message' visible if target user granted permissions application. this known facebook limitation avoid phishing , spam. there workaround (circa q1 2012), adding new_style_message: true fb.ui options parameter showed it. people reported still works them, (as of recent tests) it's not working anymore. cheers!

unix - Combine multiple scripts in an "index.html" like fashion? -

is there standard way in unixesque (sh/bash/zsh) system execute group of scripts if group of scripts 1 script? (think index.html) . point avoid additional helper scripts find , keep small programs self sufficient , easier maintain. say have 2 ( in bold ) ruby scripts. /bin /bin/foo_master /bin/foo_master/ main /bin/foo_master/ helper.rb so when execute foo_master seo@macbook ~ $ foo_master [/bin/foo_master/main]: make new friends, keep old. [/bin/foo_master/helper.rb]: 1 silver , other gold. if you're trying without creating helper script , typical way execute both (note: i'll use : $; represent shell prompt): : $; ./main; ./helper.rb now, if you're trying capture output of both file, say, can group these subshell , parenthesis, , capture output of subshell if single command, so: : $; (./main; ./helper.rb) > index.html is you're after? i'm little unclear on final goal is. if want make heavily repeatable thing,

IOS Push Notifications for multiple Apps from one server -

we have 2 apps setup push notifications. (a , b) there different profiles each (of course) , we've generated separate certs each. app receives push notifications fine, app b doesn't. both talking same server - , figure out app it's sending notifications , uses correct cert. i've noticed if install both apps on 1 device, both same token (which our server tracks per app.). when server sends msg in case, sends twice same token - once each cert. app receive msg, app b won't. when sending msgs both apps, apple server responds messages sent correctly no errors. msg never shows 1 app. any suggestions on look? after searching , looking, found question: iphone - multiple apps, different app id, same token it points out must use different .certsigningrequest each app. checked our appstore guy, , had used same 1 both certs. fixed that, , works!

ios - Go to next UITextField in different UITableViewCells -

i have uitableview x number of cells. in cells there x number uitextfields . want next-button on keyboard highlight next textfield. got working in same cell not when it's supposed jump textfield in different cell. first textfield in each cell has tag 0 , second tag 1 , on. code: - (bool)textfieldshouldreturn:(uitextfield *)textfield{ // fetch current cell uitableviewcell *cell = (uitableviewcell *)textfield.superview.superview; // tag next textfield nsinteger nexttag = textfield.tag + 1; uitextfield *nexttextfield; for(uitextfield *subview in cell.contentview.subviews){ if([subview iskindofclass:[uitextfield class]]){ if(subview.tag == nexttag){ nexttextfield = subview; break; } } } if(nexttextfield){ // go next textfield [nexttextfield becomefirstresponder]; } else{ // indexpath current cellen nsindexpath *indexpath = [tra

c - lcc printf floating point -

i have following program: #include <stdio.h> int main(int args, char *argv[]) { printf("%f\n", 0.99999); printf("%e\n", 0.99999); } the result is: 0.009990 9.999900e-001 why first number wrong? use windows xp, compiler "logiciels informatique lcc-win32 version 3.8. compilation date: nov 30 2012 19:38:03". that program correct, , output should be: 0.999990 9.999900e-01 or very similar that. (you don't use args or argv , , usual name first parameter of main argc rather args , neither of problem should affect program's behavior.) it looks you've found bug in implementation, in runtime library rather in compiler itself. brief google searches haven't turned reference particular bug (in fact, top hit question). i suggest contacting maintainer of lcc-win; contact information on web site . short description , link question should provide enough information, @ least start.

java - ViewPager and Sliding Menu swipe propagation -

in android app using sliding menu left: https://github.com/jfeinstein10/slidingmenu inside 1 of activity, have viewpager: <android.support.v4.view.viewpager android:id="@+id/image_pager" android:layout_width="match_parent" android:layout_height="match_parent" /> i load multiple images view in pager adapter scroll between them. however facing conflict in scrolling. when swipe left works fine, next image gets displayed. but when swipe right, sliding menu open, since behavior. can make in way swiping on view pager not propagate sliding menu? i tried return true in ontouchlistener of pager, sliding menu still opening, , slider doesn't work anymore. viewpager.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub return true; } }); thanks help check acce

docusignapi - Add permission profile through API -

is possible add permission profile user through docusign rest api? either when creating new user or afterwards? see can add user group, not permission profile. yes can both - can modify user profiles when adding new user, , can modify existing users - through docusign's apis. (you can manually set them through console ui) when adding new users account there high level settings set user, such name, email, company, etc., , there usersettings object contains (name,value) pairs settings such whether they're admin, if can send envelopes, if can send through api, etc. following page online rest api guide describes call , has separate section below lists potential name->value pairs , values. of them booleans strings. docusign rest api call - add members account next, see account settings set existing user, can make api call retrieve them: docusign rest api call - user settings lastly, modify settings of existing user, can make following call: docusi

ruby on rails - Active Admin before filter for namespace only -

i have namespace admin . apply before_filter namespace (not default one, superuser ). i can add following code in active_admin.rb ns.before_filter :is_subscribed? but then, superuser gets filter too. i tried adding before_filter inside namespace configuration : config.namespace :admin |ns| ... ns.before_filter :is_subscribed? end but rails throws error : undefined method `before_filter' #<activeadmin::namespace:0x007fa2e0f75f00> you add controller before_filter in controllers in namespace inherit controller? ie. adminbasecontroller.

How to get the string value of a parameter in Java? -

i'm trying save parameter property, parameter : testspeed ( = "20" ) , , have method : saveproperty(string parameter) which save value of parameter file, : saveproperty(testspeed); my property file looks : testspeed : 20 testheight : 300 my question : in java possible name of parameter, in case parameter passed saveproperty() testspeed , , it's name "testspeed" , how string inside of saveproperty() , don't have following save : saveproperty(string name,string value); and call : saveproperty("testspeed",testspeed) also, when need out property file, can call : getproperty(testspeed) i know how use property file, i'm using example, maybe caused confusion when mentioned property file. the essence of question : how name of parameter passed method. void somemethod(string parameter_xyz) { // in here if call somemethod(testspeed), how string "testspeed", // not it's value, it's name, // spe

WPF Listbox Items -

i have listbox control contains names of files inside directory. how iterate though controls , names? i've tried: for (int = 0; < listboxfilegroups.items.count; i++) { // don't want use properties start selected // here looking string textitem = listboxfilegroups.items[i].tostring(); } any suggestions? you may want explore mvvm approach. in 1 of view model classes, can have observablecollection<string> : public observablecollection<string> stuffforlistbox { get; set; } populate observablecollection want displayed in listbox. in code-behind of usercontrol or window in have listbox, set datacontext instance of class containing stuffforlistbox seen above. this.datacontext = new myclass(); alternatively create datatemplate usercontrol / window automagically wire datacontext view model. since mentioned want display files in directory (not including sub-directories), need bind itemssource stuffforlistbox. &l

python - creating small arrays in cython takes a humongous amount of time -

i writing new random number generator numpy produces random numbers according arbitrary distribution when came across weird behavior: this test.pyx #cython: boundscheck=false #cython: wraparound=false import numpy np cimport numpy np cimport cython def barebones(np.ndarray[double, ndim=1] a,np.ndarray[double, ndim=1] u,r): return u def untypedwithloop(a,u,r): cdef int i,j=0 in range(u.shape[0]): j+=i return u,j def bsreplacement(np.ndarray[double, ndim=1] a, np.ndarray[double, ndim=1] u): cdef np.ndarray[np.int_t, ndim=1] r=np.empty(u.shape[0],dtype=int) cdef int i,j=0 in range(u.shape[0]): j=i return r setup.py from distutils.core import setup cython.build import cythonize setup(name = "simple cython func",ext_modules = cythonize('test.pyx'),) profiling code #!/usr/bin/python __future__ import division import subprocess import timeit #compile cython modules before importing them subprocess.call([

Xcode 4.5 debugging skips section of a function when stepping through code, even with breakpoints set (c++) -

so have function here allegedly reads values .cfg file , file set correctly, values not being reflected changes make file. debug. problem skips on iterations value looked for! can't tell if it's accepting default value, or if else wrong. bool configreader::getbool(const std::string thesection, const std::string thename, const bool thedefault) const { bool anresult = thedefault; // line have breakpoint set // check if thesection exists std::map<const std::string, typenamevalue*>::const_iterator iter; iter = msections.find(thesection); if(iter != msections.end()) { // try obtain name, value pair typenamevalue* anmap = iter->second; if(null != anmap) { typenamevalueiter iternamevalue; iternamevalue = anmap->find(thename); if(iternamevalue != anmap->end()) { anresult = parsebool(iternamevalue->second, thedefault)

system - PHP shell_exec using UNC paths -

in php, can not execute command via shell_exec, system, or exec, when using unc paths. here example: what works: $command = shell_exec("dir c:\\"); echo $command; here not work. echo's nothing. $command = shell_exec("dir \\\\server\\dir"); echo $command; when run dir \\server\dir in windows command window or powershell executes fine. unc paths work, user php service running must have access share. i assume running php iis. if case, default user iusr_machinename . sure user has access share. if you're running apache, check task manager on server determine user running apache service. give user name access share.

php - No values in $_POST variable after Submit HTML form -

i have html form, sending data through post php-file, , php-file should process data (make looking structure) , send via mail. but $_post variable empty.... i have small html form: <form id="form" method="post" action="formmailer.php"> <div id="input1"> <input name="name" type="text" placeholder="ihr name"> <br> <input name="email" type="email" placeholder="ihre e-mail"> <br> </div> <div id="input2"> <textarea name="nachricht" rows="10" cols="30"></textarea> <br> <input type="submit" value="" name="submit" id="submit"> </div> </form> and formmailer.php uses these variables: <?php // if(isset($_p

Lotus Notes Field does not refresh automatically on document open -

one of fields in form in notes designer has following code: viewhire := @if(@ismember(@username; willnotify);@username; @ismember("[superuser]";@userroles);@username; @ismember("[finance]"; @userroles);@username;"invalid"); @name([abbreviate];viewhire) the problem code first person open document has username set in field. next time different user trys open same document name not appear in field till refreshes document username gets inserted in field. any ideas on come problem ? 1 way thought of if can insert code on "open document" solve not sure or know if possible ? i using domino designer 8.5 define field "computed display" rather "computed" , field calculated on document open properly. disadvantage field not stored in document though.

Trouble with static methods calling eachother c# -

i'm trying replace messagebox.show calls in applicaiton i've created static msgbox class 2 methods defined below: (one) public static messageboxresult show(window owner, string messageboxtext, string caption = "", messageboxbutton button = messageboxbutton.ok, messageboximage icon = messageboximage.none, messageboxresult defaultresult = messageboxresult.none) and 1 calls other (two) public static messageboxresult show(string messageboxtext, string caption = "", messageboxbutton button = messageboxbutton.ok, messageboximage icon = messageboximage.none, messageboxresult defaultresult = messageboxresult.none) { return show(application.current.mainwindow, messageboxtext, caption, but

Script hosting in .Net 4.5 -

we using ironruby in our applications simple scripting of biz logic , rules. we trying upgrade .net 4.5 - , our scriptruntime/ironruby code not happy that. not lok ironruby has had lot of traction lately, wondering scripting engine switch best supported .net 4.5 environment. prefer simple - less third-party stuff have bring in better. our scripts simple - not big effort convert. suggestions? if converting scripts c# isn't problem, recommend looking microsoft "roslyn" ctp , scripting api . because .net compiler developers rebuilding compilers in roslyn architecture , visual studio team intends consume roslyn compilers in future, it's safe bet support scenario remain quite time.

rspec2 - why controller.should_receive(:before_filter_name) fails in rspec? -

we uses controller.should_receive(:before_filter_name) in rspec pass before filter in our rails 3.2 rspec. before filter , rspec returns error. here def of before filter check_availability : def check_availability if find_config_const('sales_lead', 'customerx').nil? or find_config_const('sales_lead', 'customerx') == 'false' redirect_to authentify.signin_path, :notice => "quit!" end end in controller, before filter: before_filter :require_employee before_filter :load_customer before_filter :check_availability to by-pass check_availability , put following code in rspec controller: before(:each) controller.should_receive(:require_signin) controller.should_receive(:check_availability) end filter require_signin has no problem. 2nd filter, there error: 2) customerx::salesleadscontroller 'new' should redirect user without proper right ←[31mfailure/error:←[0m ←[3

c++ - Memory allocation - How 15 GB can be equal to 2GB? -

a major application of mine, crashing @ run time. i want find out if related memory allocation issue system. thus, created small test program allocate 1gb of memory , simultaneously ran 15 such processes, using 15gb of ram in total. however, when run program task manager shows has occupied 2gb of ram? how possible? i wrote sample code follows char *ptr[1024]; ( = 0 ; < 1024 ; ++i ) { ptr[i] = new char[1024 * 1024]; std::cout << " allocated 1024 mb" << << " th time " << std::endl; } try storing data in big arrays. memset fine. looking @ actual memory if don't touch these still in virtual memroy.

jquery - How to force the proper order with my javascript -

ok have javascript/jquery $('.next').click(function(e){ e.preventdefault(); var table = $('table.active'); var form = table.find('form'); form.submit(); window.location.href = '/some/location'; }); the problem in browsers safari being 1 of them form.submit() never gets called. my guess async request , never gets chance call. any ideas on how this. tried following form.submit(function(){ window.location.href = '/some/location'; }); but didnt work you need like $(function() { $('.next').click(function(e){ e.preventdefault(); var table = $('table.active'); var form = table.find('form'); $.post(form.attr("action"),function() { window.location.href = '/some/location'; }); }); }); with parameters try $.post(form.attr("action"),form.serializearray(),function() {

asp.net mvc 4 - Web-Api 400 BadRequest when search parameter is blank -

i using web-api mvc4 i making searching functionality, in cases if filter data remove textbox value , press search button, need show whole listing in case showing 400 bad request. search parameter blank, know if search parameter blank throw 400 error web-api. any 1 have proper solution please let me know. data: "currpage=" + jscurrpage + "&pagesize=" + parseint(pagesize) + "&buildtypename=" + $("#buildtypename").val(), here in cases buildtype blank. when search made //controller public httpresponsemessage getbuildtypelist(int currpage, int pagesize, string buildtypename) { } net -> xhr url : http://{parenturl}/api/buildtypewebapi/getbuildtypelist?currpage=1&pagesize=10&buildtypename= if allow currpage , pagesize empty, need accept nullable ints: public httpresponsemessage getbuildtypelist(int? currpage, int? pagesize, string buildtypename) then, you'll update query return en

function - Attempting to make a random choice in Lua -

this have far, seems everytime attempt run it, closes. function wait(seconds) local start = os.time() repeat until os.time() > start + seconds end function random(chance) if math.random() <= chance print ("yes") elseif math.random() > chance print ("no") end random(0.5) wait(5) end that full context. probably meant write this: function wait(seconds) local start = os.time() repeat until os.time() > start + seconds end function random(chance) if math.random() <= chance print ("yes") elseif math.random() > chance print ("no") end end random(0.5) wait(5)

java - How to remove duplicates from string (not array) without using StringBuilder? -

i working program , need remove repeated characters string given me user. referenced other questions, using stringbuilder remove duplicates. however, there way remove duplicates without turning string array, using stringbuilder , set ? i haven't learnt yet, don't understand them well. help? for example, if user types in happyrolling result should hapyroling . it seems example want remove repeated characters (not words ). you can use regex find repeats , remove them: str = str.replaceall("(.)\\1+", "$1"); this regex captures every character matches when followed same character using reference captured group. replacement captured character, example "xx" replaced "x"

r - When add a column to a data.table, what's then best way to add if else conditions? -

for example, like: dt[isflag, newcol:= a] dt[!isflag, newcol:=b] or should this? dt[, newcol:= b] dt[isflag, newcol:=a] or this? dt[, newcol:= if (isflag) else b] # works if isflag scalar or dt[, newcol:= ifelse(isflag, a, b)] # works if isflag vector what best way?

oop - Choice of inheritance from class or declaring fields -

say have class product {string name; double price;...} so if want implement seasonal or discounted product, can add declare ispromoted/isseasonal or can create new class promotedproduct : product {...}, seasonalproduct : product{} , more. i have been told beginners tend misuse inheritance , how evil. not sure if considered misusing in case. or maybe both wrong , using interface better etc. will products on promotion or not - ie - no actual promotion details (different rates, dates etc) - if you'll want first solution. otherwise you'll want relation promotions class store such details. hope helps. note: general programming answer having never used java personally.

HTML5: video source not working in the Firefox 21.0, Ubuntu -

i new "html5". when trying implement simple video tag got error "no video supported format , mime type found". code is <!doctype html> <html> <body> <video width="320" height="240" controls="controls"> <!source src="movie.ogg" type="video/ogg" /> <source src="http://video-js.zencoder.com/oceans-clip.mp4" type="video/mp4 codecs='avc1.42e01e,mp4a.40.2'" /> <!source src="movie.webm" type="video/webm" /> browser not support video tag. </video> </body> </html> please me using firefox version 21.0 browser , ubuntu ultimate edition 3.0 os firefox not support mp4 video format in html5. http://www.w3schools.com/html/html5_video.asp edit: looks firefox supports mp4 in cases (thanks @winterblood). if use firefox 21, mp4 should work windows 7+, android , firefox os .

gdi - Draw the screen to a window using StretchBlt() -

i'm working on program capture screen , draw on window. this drawing thread function: void drawfunc(void*hwnd) { hdc windowdc=getdc((hwnd)hwnd); hdc desktopdc=getdc(getdesktopwindow()); for(;;) { rect rect; getclientrect((hwnd)hwnd,&rect); stretchblt(windowdc,0,0,rect.right-rect.left,rect.bottom-rect.top,desktopdc,0,0,1920,1080,srccopy); } } the problem stretchblt slow(about 20 fps) should improve performance? thanks.

python - Error running google app engine: unrecognized arguments: admin_console_server -

i'm following 'getting started python app engine' tutorial , can't seem connect development server. keep getting following error log console when try running it. 2013-08-23 09:46:43 pm running command: "[u'/usr/bin/python', '/home/mathee/google_appengine/dev_appserver.py', '--admin_console_server=', '--port=8080', '/home/mathee/app']" usage: dev_appserver.py [-h] [--host host] [--port port] [--admin_host admin_host] [--admin_port admin_port] [--auth_domain auth_domain] [--storage_path path] [--log_level {debug,info,warning,critical,error}] [--max_module_instances max_module_instances] [--use_mtime_file_watcher [use_mtime_file_watcher]] [--php_executable_path path] [--php_remote_debugging [php_remote_debugging]] [--python_startup_script python_startup_script]

ios - NSManagedObjectControllers read only access on another thread -

i selecting core data entries , sorting them. straight forward enough because of calculations in sort distance wanted put in alternate thread. did usual way making new nsmanagedobjectcontroller other thread adding code within #ifdef threads sections below. now can fetch, sorting , organizing, without slowing user interface , table updated when ready. but, since doing fetch in local managed object context, fetched objects not valid on main thread - in fact disappear out of table view cells. so, questions are: 1) ok use main managed object context, since reading, , not create local context @ all? 2) should go through , re-fetch objects main managed object context on main thread using objectid values search managed object context objects after sorting , organizing? 3) should fetch on main managed object context performblockandwait keep sort , organize returned objects on searchq thread? 4) else have not thought of? - (void) fetchshoplocations { #ifdef threads dispatch_q

javascript - Attaching events after DOM manipulation using JQuery ajax -

how attach events after manipulating dom using ajax response. have ajax request html response fragment of html. fragment html have many buttons. want refresh dom declared , attached events applied fragment too. dont want keep on adding each events each button using jquery on(). how else it? you can use delegated event handling set ahead of time , can made apply newly added dom elements. delegated event handling done .on() , takes form of: $("static parent selector").on('click', 'selector dynamic element', fn); there no clean way run event installing code again , have apply newly added dom elements. have put code in function , code such never adds event handler more once , call function again after adding items dom. or, make function take argument parent object , add event handlers in newly added dom hierarchy. here's relevant answer delegated event handling: does jquery.on() work elements added after event handler created?

sql server - sql adjacency list children for node -

Image
given context: how copy node's children in adjacent list in adjacency list, how pick node , children? for example, see highlighted nodes below. try cte( about cte ): declare @selectednode int = 103; ;with nodes ( select node , parentnode , groupid , depth tablenodes node = @selectednode union select tn.node , tn.parentnode , tn.groupid , tn.depth tablenode tn inner join nodes n on n.node = tn.parentnode ) select * nodes;

java - Create source folder and project programmatically -

i trying create 1 java project source folder programmatically.i able create java project inside not able create source folder getting error below. java.lang.arraystoreexception @ java.util.abstractcollection.toarray(abstractcollection.java:171) @ org.eclipse.jdt.launching.javaruntime.getvminstalltypes(javaruntime.java:533) @ org.eclipse.jdt.launching.javaruntime.getvminstalltype(javaruntime.java:414) @ org.eclipse.jdt.internal.launching.vmdefinitionscontainer.populatevmtypes(vmdefinitionscontainer.java:483) @ org.eclipse.jdt.internal.launching.vmdefinitionscontainer.parsexmlintocontainer(vmdefinitionscontainer.java:467) @ org.eclipse.jdt.launching.javaruntime.addpersistedvms(javaruntime.java:1488) @ org.eclipse.jdt.launching.javaruntime.initializevms(javaruntime.java:2654) @ org.eclipse.jdt.launching.javaruntime.getdefaultvmid(javaruntime.java:541) @ org.eclipse.jdt.launching.javaruntime.getdefaultvminstall(javaruntime.java:486) i have tried

ios - How to implement auto publish to user's facebook timeline just like Instagram ? -

i building social app user can post app. data stores in our own server , display ios native app. trying make post user publish our app user's facebook timeline. know can post data server , let app use graph api publish data directly facebook timeline. double post , make transfer data double think might not practise. so want post server first , let server rest. shown in facebook docuement "auth on client, api calls server" https://developers.facebook.com/docs/facebook-login/access-tokens/ auth on client, api calls server http://img560.imageshack.us/img560/3814/sddz.png but wonder if case app. because shown in diagram "api calls forwarded server proxy facebook api calls" . , not case app. because api calls initiated in server side when user use client post new data. i wonder how app implement this.for example ,app such instagram , other social app. not sure if explain violate facebook term of usage . tia, kong your case suits mode

c - Reference to a pointer is lost -

this question has answer here: assignment of function parameter has no effect outside function 2 answers i trying understand why statement doesn't work. char resp[] = "123456789"; void getvalue(char *im) { im = resp; printf("\n%s\n",im); } int main(int argc, char *argv[]) { char imei[11] = {0}; getvalue(imei); printf("\nimei: %s\n",imei); return 0; } output: 123456789 imei: you can not assign = , use strcpy instead: #include <stdio.h> #include <string.h> char resp[] = "123456789"; void getvalue(char *im) { im = strcpy(im, resp); printf("\n%s\n",im); } int main(int argc, char *argv[]) { char imei[11] = {0}; getvalue(imei); printf("\nimei: %s\n",imei); return 0; } that's because imei array[11] (not pointer to), if want ass

android - disable gridview item onClick and enable only on child view -

hi have gridview imageview , textview in each gridview item. want disable onclick of grid view item , enable imageview. there way can achieved. have have lot of space between each grid view item , if have onclick enabled each gridview item ontimeclick listener called if click on empty spaces avoid planing have onclick imageview.... pls suggest how can done... you can give android:clickable="false" gridview in xml. and, can write onclick imageview inside custom adapter have populated gridview. also try, android:focusable="false" android:focusableintouchmode="false" for gridview in xml.

c++ - How to transform the several loops code of finding combination into recursive method? -

i trying convert code recursive method for(int i=0;i<25;++i) for(int j=i+1;j<25;++j) for(int k=j+1;k<25;++k) for(int l=k+1;l<25;++l) for(int m=l+1;m<25;++m) {//} the method finding 25c5 combinations. in recursive way have written this int soln[5]; void backtrack(int c) { if(c<5) { for(int i=c;i<25;++i) { soln[c] = i; backtrack(c+1); } } else { // } my soln wrong cause number of recursion 6 million actual should 50 thousand. how correct that? void backtrack(int start, int depth) { if (depth < 5) { (int = start; < 25; ++i) { backtrack(i + 1, depth + 1); } } } seems same nested loops.

python - Django REST Framework Auth Token -

i'm having little trouble token authentication in django rest framework. docs know matter of implementing following: from rest_framework.authtoken.models import token token = token.objects.create(user=...) print token.key now question is, goes in argument of token.objects.create(user=...) . answer here helps , says that provide token model foreign-keyed user. i'm not sure understand this. i have own model of users defined so: class users(models.model): userid = models.integerfield(primary_key=true) username = models.charfield(max_length=255l, unique=true, blank=true) email = models.charfield(max_length=255l, unique=true, blank=true) password = models.charfield(max_length=64l, blank=true) registeredip = models.charfield(max_length=255l, blank=true) dob = models.datefield(null=true, blank=true) firstname = models.charfield(max_length=255l, blank=true) lastname = models.charfield(max_length=255l, blank=true) joindate = models.date

html - Navbar not getting it's style right -

i want create navbar this page's. can see on website there's picture. in picture see black nav bar. want make same 1 not able that. here's code: css: @charset "utf-8"; @import url("base.css"); { } span, input, #small_navigation, nav, { display: inline-block; margin: 5px; } #wrapper { width: 100%; height: 100%; } /* large desktop */ @media (min-width: 1200px) { #header { width: 100%; height:50px; background-color: #f2e8e8; box-shadow: 0px 5px 5px 3px #aaa; } #right_side #small_navigation { margin-top: -150px; } #header #right_side { float: right; } #header #dropdown ul li ul{ text-align: center; } } html: <div id="wrapper"> <div id="header"> <span id="icon"><!-- <img src="icon_src.png" /> -->icon</span> <input type="search&qu

php - showing invalid message before uploading any image -

showing invalid error message on screen before uploading image on screen index.php <html><body> <form action="index.php" method="post" enctype="multipart/form-data"> <table align="center" cellspacing="0" cellpadding="6" bgcolor="#cccccc" border="1" bordercolor="#000000"> <tr> <td >firstname:</td><td><input type="text" name="fname" /></td></tr><br/><br/><br/> <tr> <td >regsternumber:</td><td><input type="text" name="regno"/></td></tr><br/> <tr> <td>uploadphoto:</td><td><input type="file" name="image" /></td></tr> </table> <br><br><br> <center> <input type="su

c# - how enter in TextBox only digits from interval -

i try make form (c#, winforms) small program reminder. during have problem - whant make filter textbox user must enter start time event. result got next - on keypress event add code, allow enter digits, want user can enter digits diapasone. code: private void startimetextbox_keypress(object sender, keypresseventargs e) { if ((e.keychar >= '0') && (e.keychar <= '9')) { return; } if (char.iscontrol(e.keychar)) { if (e.keychar == (char) (keys.enter)) starttimemmtextbox.focus(); } e.handled = true; } can using event or no? try this:- private void textbox1_keypress(object sender, keypresseventargs e) { e.handled = !char.isdigit(e.keychar) && !char.iscontrol(e.keychar); } note:- can use textbox's maxlength property restrict user enter 2 digits. display message user can use textchanged event of textbox.

Rails with activeadmin and devise - signed_in? -

i have installed devise , activeadmin. when login activeadmin rails thinks im signed_in user on page no current_user value. when go on pages without login user (with logged on activeadmin) statement: <% if signed_in? %> is true , rails try run script in it. how can tell rails activeadmin users isnt current_user whole site? you should tell signed_in? method user at: on regular user pages not want considered signed in when you're signed in admin, may want replace <% if signed_in? %> by <% if user_signed_in? %> where user name of devise resource (if have named differently, replace user actual name (ex: if devise user model enduser, should put end_user_signed_in?)

php - How to get custom attribute of select's option in angularjs? -

this how html looks like <select name="currency_advance" ng-model="currency" ng-change="put_currency()"> <?php foreach ($currency $c) { ?> <option data-type="<?php echo $c->symbol; ?>" value="<?php echo $c->alphacode; ?>" > <?php echo $c->alphacode; ?> - <?php echo $c->currency; ?> </option> <?php } ?> </select> now can option value in angularjs's controller using put_currency function, need custom attribute "data-type" value. how can accomplish this? please me? update now generating select field javascript. problem need set , value called symbol of currency. using custom tag data-type currency symbol. how can set , custom tag value in angularjs way? <select name="currency_advance" ng-model="currency" ng-options="data.code data.code + ' - ' + data.currency data in data&quo

php - Mod_ReWrite regex unknown variables count? -

i store uploaded files @ /storage/ way public-adam-luki-uploads-123783.jpg park-hanna-adel-propic-uploads-787689.jpg the '-' count unknown because slice pic description i want users able access as http://site.com/public/adam/luki/uploads/123783.jpg http://site.com/park/hanna/adel/propic/uploads/787689.jpg i think same problem here mod_rewrite unknown number of variables but can't because i'm new mod_rewrite module i hope can me guys right rewriterule the question link doesn't trying (although principle same) convert url get variables. if want convert / - can use simple rewrite rule run in loop: rewriterule ^(.*)/(.*)$ $1-$2 [l] there of course few caveats that... firstly, if trying real directory/file rule still switch out / , - , leave 404. can around adding conditions; stop rewriting real files: rewritecond %{request_filename} !-f you better limit matches images ( jpg s): rewritecond %{request_filename} !-f