Posts

Showing posts from March, 2010

ruby on rails - How to create method that converts attribute's value to new value -

i have form in users input number attribute :bytesize, has integer datatype. number represents amount of bytes object @catcher. i'd have method convert value of :bytesize megabytes. is, i'd able run @catcher.mbsize, , display number of megabytes object. i'm pretty new rails, apologies if seems obvious. conversion methods pretty straight-forward: class catcher def mbsize self.bytesize / (1 << 20) end end remember attributes internally stored instance variables, attr_accessor :bytesize stored in @bytesize .

c# - show existing selection for dynamic checkbox -

i creating checkboxes dynamically , want show existing selection or want check them dynamically.this code create checkboxes private void role() { systemuserdal dal = new systemuserdal(); var roles = dal.getroleslist(); foreach (keyvaluepair<guid, string> r in roles) { checkbox chk = new checkbox(); chk.id = r.value; chk.text = r.value; rolepanel.controls.add(chk); } } i have protected void page_load(object sender, eventargs e) { if (!ispostback) { systemuserdal dal = new systemuserdal(); var userid = guid.parse(request.querystring["id"].tostring()); var user = dal.getsystemuserbyid(userid); if (user != null) { role(); var role = user.roles; textuserid.text = user.userid.tostring(); user.roles has roles particular user assigne...

user interface - How change color of item in three.js gui -

how write item specific color in three.js gui menu. or add square or circle speficic color before item menu. thanks are referring dat.gui ? if so, separate software library three.js, , instead can read capabilities at: http://workshop.chromeexperiments.com/examples/gui/#1--basic-usage as far know, there no way add decorations mentioned dat.gui.

performance - Faster alternatives for calcOpticalFlowSF -

is there faster alternatives calcopticalflowsf? sooo slow , wanna run thing sequence of frames coming video. how can that? there several methods optical flow based motion estimation have consider several things: are restricted cpu implementation / gpu's implementation decrease drastically run-time do need dense motion fields or set of sparse motion vectors / sparse of methods more scalable , need less run-time accuracy / high accuracy of dense methods critical on motion boundaries. in many application approximate dense motion field grid of sparse motion vectors , can use sparse methods pyramidal lucas kanade (opencv) current libaries / methods are: dense methods: opencv 2.4.4 provides on gpu broxopticalflow fast too the flowlib of gpu4vision group provides high accurate gpu implementation gpu implementation of tv-l1 on gpu provided sparse methods: opencv since 2.4.2 provides pyramidal lucas kanade on gpu /earlier verions fast implementation on cp...

python - Django Rest Framework -

i have method grabs post data formated in json format this [{"username": "alexgv", "password": "secretpassword"}] here method def login(request, *args): data = request.data return response(data) """ try: m = user.objects.get(username=request.data['username']) if m.password == request.data['password']: request.session['member_id'] = m.id return httpresponse("testing") except user.doesnotexist: return httpresponse("your username , password didn't match.") """ i want able take 1 variable json post. example, maybe want grab username or password. how that? have tried variety of things cant seem work, , dont want use request.post.get because means have send post variables. btw using http://django-rest-framework.org/ . have read through docs cant seem find in there. appreciated. returns right everything. like so... us...

facebook - Error : The access token could not be decrypted -

since few days, when try use tokens publish in wall of user application have error : the access token not decrypted this first time got error , don't understand why. the tokens generated in march still working (i use long lived access , publish_actions). sure, create news tokens (from same application) now, , post fine on wall. (maybe error soon? don't know moment) so why have error tokens generate month (april), except tokens generate (for test)? maybe facebook has changed month in code post? i had similar issue , discovered reason our database stored limited access tokens 200 characters or less our access tokens getting truncated. widened database field 512 characters , things working again me. seems access tokens 219 characters long.

algorithm - Finding unique (as in only occurring once) element haskell -

i need function takes list , return unique element if exists or [] if doesn't. if many unique elements exists should return first 1 (without wasting time find others). additionally know elements in list come (small , known) set a. example function job ints: unique :: ord => [a] -> [a] unique li = first $ filter ((==1).length) ((group.sort) li) first [] = [] first (x:xs) = x ghci> unique [3,5,6,8,3,9,3,5,6,9,3,5,6,9,1,5,6,8,9,5,6,8,9] ghci> [1] this not enough because involves sorting (n log n) while done in linear time (because small). additionally requires type of list elements ord while should needed eq. nice if amount of comparisons small possible (ie if traverse list , encounter element el twice don't test subsequent elements equality el) this why example this: counting unique elements in list doesn't solve problem - answers involve either sorting or traversing whole list find count of elements. the question is: how correctly , e...

php - Is it possible to detect key type with json_encode? -

quite difficult explain, example have array: $lol = array( 'key' => 'value', 'key_1' => 'value 1', 'simple_value', '0' => 'lol', 'key_array' => array( 'key_in_second' => 'value_with_key_in_second', 'value_in_second_array', ) ); after json_encode {"key":"value","key_1":"value 1","0":"lol","key_array":{"key_in_second":"value_with_key_in_second","0":"value_in_second_array"}} so possible somehow detect if in php array had key or note? in example elements 'simple_value', '0' => 'lol' have same key. php doesn't care if number 0 in quotes or not. storing numeric 0, same 'value_in_second_array' 0, first element without key. basically, array('0'=>'lol') same a...

php - Return only matched occurrences with strstr() -

say have following string: $string = 'great @jason think @sally love too.' i'm using: $mentions = strstr($string, '@'); echo $mentions which outputs @jason think @sally love too. desired output @jason @sally i can't figure how in php, in js do: hashtags = /\@\w+/g; var matches = string.match(hashtags); alert(matches); preg_match() in php returns boolean, closest can strstr()... returns whole string after first match. you can use preg_match_all same regex: <?php $string = 'great @jason think @sally love too.'; preg_match_all("/@\w+/", $string, $matches); var_dump($matches); ?> demo: http://ideone.com/ngrrvh

c - Appending a string on different lines of a file? -

i learning c , had question. trying append string file. however, every time string appended has on next line (sort of println instead of print). i cannot make function append on next line. instead, keeps appending on same line. how do this? void filewriter(char *cmmd) { file *fp; fp = fopen("xxx.txt", "a"); fprintf(fp, "%s", cmmd); fclose(fp); } thanks! say this: fprintf(fp, "%s\n", cmmd); // ^^

linux - Why does bash execute 2 instances of my script when using a pipe inside of $() -

here bash script: #!/bin/bash $(find / -name "foo" | grep "bar") here ps has output: $ ps fx pid tty stat time command 2690 ? sl 1:04 gnome-terminal 5903 pts/8 ss 0:00 \_ bash 7003 pts/8 s 0:00 \_ bash -x ./test_script.sh 7004 pts/8 s 0:00 | \_ bash -x ./test_script.sh 7005 pts/8 s 0:00 | \_ find / -name foo 7006 pts/8 s 0:00 | \_ grep bar $ ps aux user pid %cpu %mem vsz rss tty stat start time command 1000 7003 0.0 0.0 5172 1108 pts/8 s 16:23 0:00 bash -x ./test_script.sh 1000 7004 0.0 0.0 5172 520 pts/8 s 16:23 0:00 bash -x ./test_script.sh 1000 7005 0.7 0.0 4720 1176 pts/8 s 16:23 0:00 find / -name foo 1000 7006 0.0 0.0 4368 824 pts/8 s 16:23 0:00 grep bar as can see there 2 instances of script being executed, can tell me bash doing here? why there 2 instances of scri...

Passing string array from ASP.NET to JavaScript -

i trying call server side javascript , pass string array javascript, running problems. // call server-side data. $.ajax({"url" : "mywebpage.aspx/getdata", "type" : "post", "data" : {"iddata" : iddata}, "datatype" : "json", "success": function (data) { // data. var responsearray = json.parse(data.response); // extract header , body components. var strheader = responsearray[0]; var strbody = responsearray[1]; // set data on form. document.getelementbyid("divheader").innerhtml = strheader; document.getelementbyid("divbody").innerhtml = strbody; } }); on asp.net server side, have: [webmethod] [scriptmethod(responseformat = responseformat.json)] public static object gettip(string idtip) { int iidtip = -1; string[] mydata ...

actionscript 3 - Bitmaps Being Cached As Bitmaps -

i have slideshow type portion of air mobile ios working on. there 4 pages user can scroll through. each page contains png (as large 1mb, after compression) loaded in using bitmap class , 2 textfield s. scrolling through them (using custom scroll framework works without issues throughout app), app caching each of png images bitmap come onto screen , unloading them when leave screen after period (most next gc, though seems less random gc). the act of caching pngs incredibly slow on ios, when happening while action (such scrolling) happening. produces ~1 sec delay while scrolling, unacceptable. there way either a) prevent caching or b) keep them cached longer/indefinitely until images eligible gc? i've triple checked code , nothing set cacheasbitmap. additionally, i've been using adobe scout pinpoint causing momentary freeze , caching images. i've eliminated transforms or scales or filters or might turn cacheasbitmap on in order operate , results remain same. ...

java - Duplicating Array and Acting Upon it -

i asked question earlier cloning array when change area/scale polygon etc... not change values of array (basics of encapsulation). after trying duplicating array another, using clone array, or using array list, still having problems. have suggestions how how duplicate array can make changes it, return value in method, still maintain integrity of original array passed constructor? point class defines values passed in. post well. polygon created of these methods. frustrated... public class point { private double x; private double y; public point(double x, double y) { this.x = x; this.y = y; } public double getx() { return x; } public double gety() { return y; } public point translate(double dx, double dy) { return new point(x+dx, y+dy); } public double distanceto(point p) { return math.sqrt((p.x - x)*(p.x -x) + (p.y-y)*(p.y-y)); } } import java.util.arraylist; import java.util.iterator; import java.util.list; public class polygonimpl implements...

android - why use simple_list_item_1 when calling ArrayAdapter -

i understand simple_list_item_1 pre written xml layout file use when creating listview. pass in 1 of parameters constructor of arrayadapter<>. why need middleman? android manual on constructor says parameter needs "the resource id layout file containing layout use when instantiating views." want understand why in examples i've seen, use simple_list_item_1, instead of passing in own layout file contains listview want populate. thanks most because easy use canned code readily available. if there's no need write own layout, why bother? if there need customization, make own layout , pass through instead. here's link tutorial sms app uses custom layout rows in listview: http://adilsoomro.blogspot.com/2012/12/android-listview-with-speech-bubble.html hope helps!

osx - How to translate Text to Binary with Cocoa? -

i'm making simple cocoa program can encode text binary , decode text. tried make script , not close accomplishing this. can me? has include 2 textboxes , 2 buttons or whatever best, thanks! there 2 parts this. the first encode characters of string bytes. sending string datausingencoding: message. encoding choose determine bytes gives each character. start nsutf8stringencoding , , experiment other encodings, such nsunicodestringencoding , once working. the second part convert every bit of every byte either '0' character or '1' character, that, example, letter a, encoded in utf-8 single byte, represented 01000001 . so, converting characters bytes, , converting bytes characters representing bits. these 2 completely separate tasks; second part should work correctly stream of bytes, including valid stream of encoded characters, invalid stream of encoded characters, , indeed isn't text @ all. the first part easy enough: - (nsstring *) strin...

shell - How do I merge all the cases into One -

how can merge following 2 case scripts? script 1 #!/bin/bash ver=0 n="192.168.1.20:/backup/b1" o1="192.168.1.20:/backup/b2" user="1234" echo "n latrest version" echo "o1 previous version n-1" echo "o2 previous version n-2" echo -n "which version want backup [n or p]? " read ver case "$ver" in (n|o1|o2) scp $user@${!n} . ;; (*) echo "unknown user" esac above script not working error cannot stat `1234@': no such file or directory script 2 user=0 av="34567" ma="4568" im="5678" mi="12345" pr="23456" echo "please select av ma ji im pr" echo -n "first 2 initial of name eg: [av ma ji im pr]? " read user case "$user" in (av|ma|pr|mi|im) scp ${!user}@$n . ;; (*) echo "unknown user" esac bit of mix between variables $n ...

actionscript 3 - How do I change a movie-clip's frame when it isn't on the current frame? AS3 -

i want able change movie clip frame off screen currently, on screen later. want frame change 1 2 on movie-clip if overall timeline reaches point. if timeline reaches frame 5 or specified frame, movie-clip change 1 2. so, when go frame movie-clip on it, stays on movie-clip 2. to explain trying do: named frame "index" has movie-clip , want parts viewer navigated movie-clip changes color or animation. when go index, movie-clip stay on second frame of animation. i sort of new action script , i've spent hours trying figure out how this, appreciated. i don't know how target isn't in current frame. you put movieclip: function checkparent(e:event):void { gotoandstop(1); if(parent && (parent movieclip).currentframe > 5) { gotoandstop(2); } } addeventlistener(event.enter_frame, checkparent);

python - While loop user input in range -

i have code want ask user number between 1-100 , if put number between these print (size: (input)) , break loop, if however, put in number outside 1-100 print (size: (input)), , proceed re-ask them number, have run problems though. c=100 while c<100: c=input("size: ") if c == 1 or 2 or 3: print ("size: "+c) break else: print ("size: "+c) print ("invalid input. try again.") this should it. c=input("size: ") while int(c)>100 or int(c)<1: #will repeat until number between 1 , 100, inclusively. #it skip loop if value between 1 , 100. print ("size: "+c) print ("invalid input. try again.") c=input("size: ") #once loop completed, code following loop run print ("size: "+c)

Creating indexed nodes on neo4j cypher via rest api -

i'm trying create indexed node in cypher, following syntax: neo4j-sh (?)$ start m=node:person(uid= "1") return m; ==> +------------+ ==> | m | ==> +------------+ ==> | node[64]{} | ==> +------------+ ==> 1 row ==> 0 ms ==> neo4j-sh (?)$ start n = node(64) return n.uid; ==> entitynotfoundexception: property 'uid' not exist on node[64] why node appears created, property i'm creating, , seems returned, not exist? is there easier way? used use py2neo's function: neo4j.graphdatabaseservice("http://localhost:7474/db/data/").get_or_create_indexed_node(index='person', key='uid', value=self.id, properties={'uid' : self.id}) but appears have been deprecated---it no longer works latest version of py2neo, not appear support properties argument longer (and future folks, index replaced index_name ). an index , property 2 different things. it seems have node in graph index...

ios - Objective-C with OpenSSL - Cannot set RSA Key -

i trying use add rsa encryption app using openssl, cannot certificate load. in app, public key certificate distributed server , need take key , use decrypt content encrypted barcodes app scan. the reason why choosing openssl on security library require ecdsa validation, unsupported natively. i have tried numerous methods key load. openssl pem_read_rsa_pubkey method requires file pointer. when run code below, crashes exc_bad_access attempt access key. nsstring * path = [[nsbundle mainbundle] pathforresource: @"public" oftype: @"pem"]; file *f = fopen([path cstringusingencoding:1],"r"); if (f == null) nslog(@"%@", [path stringbyappendingstring:@" not found"]); rsa *rsa = pem_read_rsa_pubkey(f,null,null,null); fclose(f); nslog (@"%d keycheck", rsa_check_key(rsa)); i have included following headers openssl library #include <openssl/opensslv.h> #include <openssl/crypto.h> #include <openssl/r...

c# - Convert a two-step LINQ query into a single LET query? -

i have following code: var data = /* enumerable containing rows in table */; var part = "x"; var items = new hashset<int>(data .where(x => x.partname == part) .select(x => x.itemname)); var query = data.where(x => items.contains(x.itemname)); items finds items in data specific partname . query returns records in data item. i need convert single let statement (or else) can use embedded in larger linq query. for example, if data follows (records): itemname partname 1 1 b 2 3 c and looking items part "a" need end result be: 1 1 b 2 one suggestion this: let = data.groupby(x => x.itemname) .where(g => g.any(x => x.partname == part)) .select(g => new { itemname = g.key, partnames = g.select(x => x.partname) }) however data returned in (let a) doesn't match ex...

javascript - Lazy Load for iframe is not working in IE7 -

<style> .desgin_iframe_dimn { background: white; height: 500px; width: 500px; } </style> <iframe scrolling="no" id="lazy" class="desgin_iframe_dimn" data-src="http://www.google.com"></iframe> <p class="lazy">click here</p> <script> function lazyloadiframe() { $('.lazy').click(function() { $('#lazy').attr('src', function() { return $(this).data('src'); }); }); $('#lazy').attr('data-src', function() { var src = $(this).attr('src'); $(this).removeattr('src'); return src; }); } lazyloadiframe(); </script> demo here jsfiddle above code works in other browsers in ie9 & ie8 not in ie7. how fix ? i don't know why have part in code: $('#lazy').attr('data-src', function() { var src = $(this).attr('src'); $(this).removeattr('src'); return...

Cannot push to Git repository on Bitbucket -

i created new repository , i'm running strange error. i've used git before on bitbucket reformatted , can't seem git work. after doing commit, had add email , name globals, committed fine. when try use command git push origin master it doesn't work. message: $ git push origin master permission denied (publickey). fatal: not read remote repository. please make sure have correct access rights , repository exists. i'm @ loss here. friend whom i'm sharing repository with, accessed fine , pushed fine, can't seem work. writing getting started git , bitbucket on windows & not familiar bash (since both common issue , high ranking google result when searching error message within question). for don't mind https , looking quick fix, scroll bottom of answer instructions under for lazy for looking solve actual problem, follow instructions below: fixing ssh issue fast possible this set of instructions derived url linked vonc. mo...

PHP mySQL Update page -

i'm trying make simple product page (no login or that) in php , mysql. far, shows on products page fine, can delete/add fine admin page. there i'm trying figure out how create edit function. made form populates mysql table based on productid convenience (edit2.php?id=x) posts edit.php , updates database. far, reusing old code isn't working, somehow hoping simple. this add product (which works) : <?php session_start(); if(isset($_post) && isset($_post['hp']) && empty($_post['hp'])) { if( isset($_session['token']) && $_session['token'] == $_post['token'] ) { mysql_connect('localhost', 'test_admin', 'test'); mysql_select_db('test_product'); $data = array_map('mysql_real_escape_string', $_post); $query = " insert products ( product_name, price, description, image ) values ( ...

oracle - performance issue with getting clob object as a string with java ResultSet -

i trying fetach clob object oracle db java application. clob object contains xml data. performance implication me consuming around 3 minutes of time process. if xml content becomes more, processing time reaching beyond accepted time intervels. is there other alternative xml content(clob object) db no performance issues? using oracle 10g. instead of storing xml in form of clob, can try using oracle xml db. check out more details @ : http://www.oracle.com/technetwork/database-features/xmldb/overview/index.html . using xml db using directly run queries on xml data, dont need bring whole of data in java layer time improve performance. edit: if xml db not option need make changes java implementation. based on question can see size of clob causing delay in fetching data. start background thread can load data in cache [you can create simple cache based on map] , instead of going db can check in cache first. can reduce time considerably you.

node.js - "Can't set headers after they are send" even though the code isn't doing it -

i'm using express 2.5.8 (not want to), , node 0.8.15 (again, i'd love upgrade). here's piece of code: unless apikey res.writehead 400, { "content-type": "text/plain" } res.end "api key must provided api access." return edit: broke writehead statuscode , setheader, , worked. know why? working code: unless apikey res.statuscode = 400 res.setheader "content-type", "text/plain" res.end "api key must provided api access." return end edit i know being executed, , return works, because when try unless apikey res.end('wtf') return res.writehead 400, { "content-type": "text/plain" } res.end "api key must provided api access." return i 'wtf' without server crashing. when try unless apikey res.writehead 400, { "content-type": "text/plain" } return res.end "api key must provided api access." ret...

php - How to solve mysql_fetch_array() issue -

here question ..can tell me details parameter , how resolve these types of problems ? warning: mysql_fetch_array() expects parameter 1 resource, boolean given in c:\wamp\www\bakeism\admin\manage-ads-cat.php thanks & regards this error means query getting failed (something goes wrong in query) & mysql_query has return false . have practice of mysql_error show exact error in query if any. mysql_query(...) or die(mysql_error()); note: please, don't use mysql_* functions in new code . no longer maintained and officially deprecated . see red box ? learn prepared statements instead, , use pdo or mysqli - this article decide which. if choose pdo, here tutorial .

Passing a vector of object pointers to a class (C++) -

i have vector of object pointers. std::vector<myobject *> listofobjects; and want pass them object needs access them. when try following: class needsobjects { public: needsobjects(std::vector<myobject *> &listofobjects) private: std::vector<myobject *> &listofobjects; }; and initialize vector in initialization list following errors: 'myobject' not declared in scope template argument 1 invalid template argument 2 invalid what doing wrong? want pass vector needsobjects class. you use pointers object, don't have define complete object structure, declare in file before using it: class myobject; // pre declaration, no need know size of class class needsobjects { public: needsobjects(std::vector<myobject *> &listofobjects) private: std::vector<myobject *> &listofobjects; };

database - Building a data driven asp.net web forms application -

i need create asp.net web forms application data driven using vs. application needs have login screen, customers , staff, product page can select product, go shopping cart. the staff need able update , edit products, , orders must processed in table. i'm finding confusing in order etc... in, please give me basic guide if dont mind order should in tips on how? any resources appreciated. :) thanks maybe start classic "contoso" sample starting point.

alembic/env.py target_metadata = metadata "No module name al_test.models" -

when use alembic control version of project's database,part of codes in env.py like: # add model's metadata object here # 'autogenerate' support # myapp import mymodel # target_metadata = mymodel.base.metadata al_test.models import metadata target_metadata = metadata when run 'alembic revision --autogenerate -m "added user table"', error : file "alembic/env.py", line 18, in al_test.models import metadata importerror: no module named al_test.models so how solve question? thanks! this might bit late, , may have figured out issue, guess problem alembic/ directory not part of system path. i.e. need like: import sys sys.path.append(path/to/al_test) al_test.models import metadata

silverlight - How to make Div Visible of Aspx page, After a Radwindow pops Up -

how make div visible of aspx page, after radwindow pops up.. looks light box. i have embedded silver light component in aspx page . , in silverlight component there images in thumbnail size . when , click on thumbnail radwindow opens original image , in big size. after pops , area under silverlight component gray color. i need whole window should have gary background color , s light box. so , need call div after rad window pops up. please visit: have shared 2 files. https://docs.google.com/file/d/0b5yo_3i2aewcbwfgb3fkwurzlvu/edit?usp=sharing https://docs.google.com/file/d/0b5yo_3i2aewczthfcuxub3juthm/edit?usp=sharing

asp.net - Crystalreports toolbar is missing when browsing through iis 7 -

i have designed web page in asp.net , vs 2008. in web application have pop crystal reports window .when run application through visual studio 2008 , browse in browser works fine. when deploy application on local computer through iis 7 toolbar of crystal report missing in firefox working in internet explorer , chrome. can 1 tell changes have done googling yesterday not found soultion. plz me !!!!. c:\inetpub\wwwroot\aspnet_client\system_web\2_0_50727 in path copy folder crystalreportwebformviewer4 , place in c:\windows\microsoft.net\framework\v2.0.50727\asp.netclientfiles tool bar come.

apache - Making Django Application localhost/appname Browsable through localhost -

my django application running on port 80 apache server , django, can browse typing hxxp://localhost/myapp want directly browse using hxxp://localhost. should configure browse directly using localhost instead of typing localhost/myapp xx=tt all urls of app in main urls.py or apps urls.py files. just edit main urls.py file from: urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^myapp/', include('myapp.urls')), ) to urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^', include('myapp.urls')), ) you have handle urls in myapp urls.py then... alan

Why won't Joomla render my PHP/Javascript tags on the front page? -

this first project on website development using joomla. trying make dashboard implementation. problem whenever edit script in article using source tags, changes not reflected on site immediately. have tried restarting wamp server, in vain. tips should follow? thanks. depending on joomla-version there different options check suppress stripping or filtering of tags <script> frontend. here hints: first of tags filtered out client-sided depending on editor selected. if use standard tinymce e.g. go extensions - plugins - tinymce find list of prohibited elements may include script . sure though, check should allowed enter script tags in article, major security risk if else administrator has right use them. option set editor administrator/author accout plain text , leave tinymce untouched. another filtering done server-sided joomla can controlled in "global configuration" -> "text filter". after standard installation groups use default black li...

c++ - Boost.Regex with icu/unicode support -

how build boost.regex icu/ unicode support? compiler gcc, , ide eclipse c++. how configure binary files eclipse? tried "bjam --shave_icu=1 toolset=gcc". did not work. when check if icu support enable "bjam -has_icu", still "has icu builds : no". i build boost against icu using -sicu_path=<icuroot> , -sicu_link="-l<iculibdir>" . i've seen boost fail detect icu well, , have needed patch file has_icu_test.cpp (simply return 0 it's main() function). work if know else set properly.

how to get individual array element from perl -

following output of dumper($resultset); $var1 = bless( { 'rows' => [ bless( { 'columns' => [ bless( { 'columnname' => 'tableschemaname', 'columnvalue' => 'from_perl' }, 'abc::tcolumn' ) ] }, 'abc::trow' ) ] }, 'abc::tresultset' ); how iterators on columns arrays. the data want access encapsulated in object of type abc::tresultset . class should have api allow access members. bad idea circumvent encapsulation, if quite easily. if weren't...

jsp - Mozilla iframe scrolling -

i have iframe , when web page calling inside scrolling not working mozilla firefox . it's working fine in internet explorer , google chrome . <iframe name="contentframe" id="contentframe" src="<c:out value='${content_frame_url}'/>" margin width=0 marginheight=0 vspace=0 hspace=0 scrolling=no width=780 height="350" frameborder="0" allowtransparency="true" style="position:absolute;overflow:hidden;border:none;"> </iframe> why doesn't mozilla firefox support this? crome interpreted <iframe name="contentframe" id="contentframe" src="empty.jsp" marginwidth="0" marginheight="0" scrolling="no" width="780" height="180%" frameborder="0" allowtransparency="true" style="position: absolute; overflow: hidden; border: none; height: 1003px;"> ...

c++ - How to define generic templated create function for subclass -

i working on cocos2dx game each subclass/scene need define something(macro) createcocos2dscene(customscenenamescreen);` following definition #define createcocos2dscene(t)\ \ static cocos2d::ccscene * scene()\ {cocos2d::ccscene * scene = new cocos2d::ccscene; scene->init(); t * layer = new t; layer->init();scene->addchild(layer); layer->release(); scene->autorelease(); return scene;} how can avoid specifying macro on each screen? don't use macro this, use inline template function: template <typename t> inline static cocos2d::ccscene* scene() { cocos2d::ccscene* scene = new cocos2d::ccscene; scene->init(); t * layer = new t; layer->init(); scene->addchild(layer); layer->release(); scene->autorelease(); return scene; }

java - Spring Dependency injection using interface with more than one implementation -

my question has been asked here in following link. spring: why autowire interface , not implemented class? what want know if use @qualifier inject bean purpose of autowiring interface ?? why not auto-wire same implementation class ?? by autowiring interface want take advantage of run-time polymorphism that's not achieved if follow approach of @qualifier . please suggest me standard way. following simple code if without spring. wonder how spring inject prepaidpaymentservice instance , postpaidpaymentservice instance?? public interface paymentservice{ public void processpayment(); } public class prepaidpaymentservice implements paymentservice{ public void processpayment(){ system.out.println("its prepaid payment service"); } } public class postpaidpaymentservice implements paymentservice{ public void processpayment(){ system.out.println("its postpaid payment service"); } } public class te...

ruby - Replace one matched value in a hash with another -

i have array of hashes: arr = [ {:key1=>"one", :key2=>"two", :key3=>"three"}, {:key1=>"four", :key2=>"five", :key3=>"six"}, {:key1=>"seven", :key2=>"eight", :key3=>"nine"} ] and search through , replace value of :key1 "replaced" if :key = "one" . the resultant array read: arr = [ {:key1=>"replaced", ;key2=>"two", :key3=>"three"}, {:key1=>"four", ;key2=>"five", :key3=>"six"}, {:key1=>"seven", ;key2=>"eight", :key3=>"nine"} ] can point me in right direction? try use following code see if solves problem arr.each{|item| item[:key1] = "replaced" if item[:key1]=="one"

oracle - SQL: Trouble in Check Constraint / Sequence -

Image
so created table, called "exam" 3 columns "name", "rollno" , "result p/f". want following: when name input (via '&name' syntax), automatically assigns first name roll number (rollno) 1501 , asks result, can enter either "p" or "f", pass or fail, respectively. when input next name, increments rollno 1502.. , on. about rollno part, have sequence called examsqn. looks like: about "result p/f" part, have check constraint. , how insert values table: insert exam (name, rollno, "result p/f") values ('&name', examsqn.nextval, '&result p/f') and way, how check constraint goes: 1 alter table exam 2* add constraint exam_result_ck check ("result p/f" in ('p','f')) so expect take p or , f, when asks result i asked name, , result right after error. how whole goes: enter value name: nikh enter value result: p old 2: values ('&n...

java - Object Serialization/Deserialization and FileInputStream.available() -

i thinking way around whole bad habit using infinite loop read in objects. algorithm involves iteratively checking if (fileinputstream("myfile.ser").available() != 0) , deserialize next object. otherwise, close file. i want know if correct way go this. i have read question's answers: may fileinputstream.available foolish me? , don't know if, empty, mean read pointer @ end-of-file. in other words, could trust fileinputstream.available() to check how data still available reading file? no, should never use inputstream.available() anything. method loosely defined (and implemented) mean anything. why infinite loop "bad habit"?

vbscript - VBS objFile.DateLastModified and Date Format Settings -

i'm trying date modify check file in vbs script. looks comparison operation depend on date format set on machine script runnnig. have diverse machines regioanal & date settings russian, english us, english uk , need run vbs against machines , being able compare date correctly. when i'm trying use if objfile.datelastmodified = cdate("19.10.2012 11:34:06") else else end if it seemingly works , doing correct comparison on machine russian formats setting, fails on machine english uk formats setting following error type mismatch: 'cdate' 800a000d if use following dateserial(2012,10,19) doesn't throw error fail compare dates correctly. what best , easiest way compare file modify date against predifined value vbs irrespectively of machine date format setting? long story short: don't use localized date formats when parsing dates. iso 8601 format works fine: if objfile.datelastmodified = cdate("2012-10-19 11:34:06") ...

timeout - Bash script that kills a output redirection after a period of time -

i'm looking lightweight solution kill command output redirection if hangs. current solution if [[ -w /tmp/mypipe ]]; timeout --kill-after 10 5 echo "1" > /tmp/mypipe fi works if left part of command not work correctly (e.g. no 1 read pipe). discovered situation, redirection hangs -- @ least issue of not synchronized tasks, can't solve now. there several related questions this , this or that . last 1 covers question, i'm still looking more slim solution. suggests work like ( cmdpid=$bashpid; \ (sleep 5; kill -9 $cmdpid >& /dev/null) & echo "1" > /tmp/mypipe ) but spawns 2 new bash processes. there more lightweight solution problem? keep in mind each spawned bash process share vast majority of memory parent process, it's not tripling memory usage top have believe. if still want try optimize, timeout 5 tee /tmp/mypipe <<< "1" > /dev/null spawn timeout , tee process instead.

command - Firebird isql error dont show in output file -

when run isql script file: isql.exe -q -e -i %1 -o %~n1.log then in output file see commands, error of commands see on screen when run. the error doesn't isn't written output file. command should use errors written output file? you have use -m(erge) command line switch in order send error messages output file.

dos - How can I copy a particular file from a source directory to a destination directory while recreating the folder structure -

i have use batch . destination folder should have copied file along directory structure of source directory (for file copied only). example : source: c:\folder1\folder2\folder3\text1.txt destination: c:\backup after command executed destination folder should : c:\backup\folder1\folder2\folder3\text1.txt i must use command c:\ (root directory) . in source there multiple files name ="text1.text" ,but different folder structure. want "text1.txt" copied path providing (source), , not files named "text1.txt" [this can achieved using--- xcopy source\text1.txt* destination /s /y].please help. @echo off setlocal :: command alone accomplish task using xcopy :: i'm changing directorynames suit system :: xcopy c:\sourcedir\a\b\text1.txt u:\backup\sourcedir\a\b\ :: :: or leave last xcopy out , batch same :: if supply parameter "c:\sourcedir\a\b\text1.txt" :: :: ie. @ prompt, enter :: :: thisbatchname "c:\sourcedir\a\b\text1.txt...

ember.js - Determining valueBinding for Ember.TextField at runtime -

i'm trying create generic editor page in ember.js app. i need create few textfields bind attributes on model, know @ runtime fields model has. controller has field called metadata, describes fields generic editor form. want iterate on contents of metadata , build form directly. i'm trying this: {{#each row in metadata.rows}} {{#each element in row.elements}} {{element.fieldname}}: {{view ember.textfield valuebindinding=model.get(fieldname) }}<br> {{/each}} {{/each}} this of course doesn't work textfield expecting reference model attribute can bind to. i have created fiddle here illustrates problem , attempt solve it: http://jsfiddle.net/ianpetzer/haecb/ thanks help i found solution problem. documented on here: https://stackoverflow.com/a/15053152/1369763 thanks @tess

objective c - Determining which action called a method -

i have button linked 2 actions touchdown , touchupinside. both these actions call same method. need know action called method, can execute different instructions when button pressed , released inside same method. i have tried looking @ buttons state property, doesn't seem change, or touchdown action firing event before button's state changes , touchupinside action firing after buttons state has changed back, resulting in state appearing not change. determining event called method not possible in ios. but, per requirement, first touchdown event call method , touchupinside event call method. based on order of events firing can able manage code inside method possible.

android - Posting on facebook wall using Request -

all day i'm trying figure how post on facebook wall of own account using own program. followed tutorials on facebook developer pages, didn't helped. have request code: bundle params = new bundle();params.putstring("app", "http://samples.ogp.me/##############"); // list<string> permissions = new arraylist<string>(); // permissions.add("publish_actions"); // session.getactivesession().requestnewpublishpermissions(new newpermissionsrequest(getmainactivity(), permissions)); request request = new request( session.getactivesession(), "me/appnamespace:test", params, httpmethod.post ); response response = request.executeandwait(); log.print("response: " + response.tostring()); all produce following error: response: {response: responsecode: 200, graphobject: null, error: {httpstatus: -1, errorcode: -1, errortype:...

c# - How to use a variable as a method name using dynamic objects -

in signalr there public property defined in hubconnectioncontext such: public dynamic { get; set; } this enables users call like: all.somemethodname(); brilliant. i call using incoming parameter in function. how can this? as in: all.<my variable method name>(); is there way of doing this? thanks edit example: public void acceptsignal(string methodtocall, string msg) { clients.all.somemethod(msg); // works clients.all.<methodtocall>(msg); // not work (but to!) } while love fun reflection answers, there's simpler , faster way invoke client hub methods using string method name. clients.all , clients.others , clients.caller , clients.allexcept(connectionids) , clients.group(groupname) , clients.othersingrouop(groupname) , , clients.client(connectionid) dynamic objects, implement iclientproxy interface. you can cast of these dynamic objects iclientproxy , , call invoke(methodname, args...) : publi...

extjs3 - Extjs LabelAlign=top is not working in panel -

i want display label on top of text field, not displaying. below code.(in fact below code displays label @ right side of text field).i using extjs 3.4, note : using form panel not working expected (have pasted code below) any appreciated. ext.onready(function () { var contentspanel = new ext.panel({ labelalign: 'top', renderto: ext.getbody(), layout: 'form', defaulttype: 'textfield', items: [{ fieldlabel: 'first name', name: 'first' }] }); contentspanel.show(); }); ext.onready(function () { var contentspanel = new ext.form.formpanel({ renderto: ext.getbody(), defaulttype: 'textfield', labelalign: 'top', items: [{ fieldlabel: 'first name', name: 'first', labelalign: 'top' }] }); contentspanel.show(); }); labelalign p...

Pick all subgraphs by a specific pattern from a graph -

so i'm looking forward pick lets triangle/square/../hexagon graph. what mean that: input keybord: a-b b-c c-a and output m-n-o, x-y-z, s-t-u (where each of subgraphs respect relation ship pattern of vertex) how solve this: has raw version not optimisations or other stuff, without backtracking / recursion. solution: transpose vertexes matrix , combinations in loops. the problem have: instance if want graph accept octogns, need make 8 in for's ?! own solution not best, suficient acomplish fallowing. acomplished combinatorics jar. hole helps @suppresswarnings("unchecked") public static void drawmatrix(graph g, int tempmatrixsize){ system.out.println(" "); system.out.println("matrix:"); arraylist<node> nodesset = new arraylist<>(); nodesset = (arraylist<node>) g.getnodes().clone(); int size = nodesset.size(); int[][] matrix = new int[size][size]; ...

python - Special characters in countVectorizer Scikit-learn -

consider runnable example: #coding: utf-8 sklearn.feature_extraction.text import countvectorizer vectorizer = countvectorizer() corpus = ['öåa hej ho' 'åter aba na', 'äs äp äl'] x = vectorizer.fit_transform(corpus) l = vectorizer.get_feature_names() u in l: print u the output be aba hej ho na ter why åäö removed? note vectorizer strip_accents=none default. grateful if me this. this intentional way reduce dimensionality while making vectorizer tolerant inputs authors not consistent use of accentuated chars. if want disable feature, pass strip_accents=none countvectorizer explained in documentation of class . >>> sklearn.feature_extraction.text import countvectorizer >>> countvectorizer(strip_accents='ascii').build_analyzer()(u'\xe9t\xe9') [u'ete'] >>> countvectorizer(strip_accents=false).build_analyzer()(u'\xe9t\xe9') [u'\xe9t\xe9'] >>> countvectorize...