Posts

Showing posts from January, 2011

c# - Why is autofac registering all instances of apicontroller instead of just the one i specify -

im having trouble understand why classes derived apicontroller registered , accessible. have 2 apicontrollers: mastercontroller : apicontroller slavecontroller : apicontroller and here how setup server container action<iappbuilder> appbuilderaction = appbuilder => { var httpconf = new httpconfiguration(); httpconf.dependencyresolver = new autofacwebapidependencyresolver(container); httpconf.routes.maphttproute("defaultapi", "api/v1/{controller}/{action}", new { action = "get" }); appbuilder.usewebapi(httpconf); }; return webapp.start(baseaddress, appbuilderaction); the problem im having when creating nunit test though try register single controller, both of them accessible during test. if register mastercontroller instance, expect url valid (master) var response = await client.getasync(new uri(http://localhost:8080, "api/v1/master/mytest&q

vbscript - Calling one vb script to another Vb script file wont run in task scheduler -

hello , trying run vb script file in schedule task, works fine when set run administrator privileges in schedule task. when trying call second script, runs first script, second script wont run. tried run through batch file, runs first script, second script not getting call. following code first script. dim objshell set objshell = wscript.createobject("wscript.shell") objshell.run "testscript.vbs" not working when run through scheduler task. could make reply. solution appreciated here.. try specifying full path testscript.vbs . when scripts run scheduler, current directory windows system folder, not folder script being run from. alternatively, can set current directory before calling script. set objshell = createobject("wscript.shell") objshell.currentdirectory = "c:\scripts" objshell.run "testscript.vbs"

apache - How can we make a redirect in .htaccess for the “git” project? -

there project on “git”. there hosting service , document_root refers http_public. have no possible way change it. i clone repository http_public, web-tool located @ http_public/zzz. redirect htaccess: <ifmodule mod_rewrite.c> rewriteengine on rewritecond %{request_uri} !^zzz rewriterule ^(.*)$ zzz/$1 [l] </ifmodule> when refer website example.com, web-tool being opened. how can make website work referring example.com not working directly example.com/zzz/?

ios - Removing the text background of a label in a cell -

Image
noticed cell label got background around text, cell got bigger text others (probably because of background). there way remove kind of behaviour ? try use this: [cell.textlabel setbackgroundcolor:[uicolor clearcolor]];

Using PHP what is the best way to get multiple rows in one MySQL query? -

this question has answer here: mysql php - select id = array()? [duplicate] 6 answers which best way multiple rows in 1 mysql query. i have array of ids: $id_array = array('34','341','342','334','344','354','3234','33234','3234','3234'); i get title associated id's mysql database . i have 2 approaches: 1) example : foreach($id_array $id){ $query = mysqli_query($con, "select title content id = '$id'"); $id_db = mysqli_fetch_row($query); echo $id_db['title']; } 2) example : $query = mysqli_query($con, "select title content id = '$id_array[1]' , id = '$id_array[2]' , id = '$id_array[3]' , 'id = $id_array[4]' , id = '$id_array[5]'"); while($result = mysqli_fetch_assoc($query)){ ech

amazon web services - Elastic Beanstalk .ebextensions config file not getting deployed with git aws.push -

i've linked git branch elastic beanstalk environment , using git aws.push deploys correctly. i've added .extensions directory contains config script should creating couple of directories. however, nothing appears happening. i understand .extensions directory should copied across ec2 instance i'm not seeing it. i've checked eb-tools.log , it's not mentioned in upload. is there additional that's required? the script contains: commands: cache: command: mkdir /tmp/cache items: command: mkdir /tmp/cache/items chmod: command: chmod -r 644 /tmp you can find run logs @ /var/log/cfn-init.log . in here see mkdir commands had worked subsequently failed directory existed. turns out eb extensions run commands in alphabetical order had change commands to: 01command1: 02command2: etc. point on worked fine. something else confusing me .ebextensions directory in local git repo not appearing on target instance directory. beca

android - How set my ACTION BAR to support right to left -

this question has answer here: how handle rtl languages on pre 4.2 versions of android? 2 answers i new on android , want write application support rtl languages. wrote android:supportsrtl="true" on application part of manifest file , call forcerighttoleft on oncreate method of android. method have following body: @targetapi(build.version_codes.jelly_bean_mr1) private void forcertlifsupported() { if (build.version.sdk_int >= build.version_codes.jelly_bean_mr1) { getwindow().getdecorview().setlayoutdirection( view.layout_direction_rtl); } } but understand on sdk api 16(android 4.1) , version before didn't supported , action bar show left right. search couldn't find solution. please don't minus code let me know , delete if not true question. try bidi class see answer also.

sql server - why do Non-English words not saved correctly in SQL database? -

i working mssql server 2008r2 , have field of type nvarchar(255) had changed collation arabic_100_ci_as field still showing '???' instead of arabic words. i tried restart server after collation changed did not work ! note : old collation latin noote inserting directly db , if write query problem raise, if edit table directly , there no problem , arabic words displaying correctly ! should done ? thanks thanks adrianm solution prefixing text n such : n'myarabictext' thanks cooperation..

uiwebview - IOS print pdf in A4 Format -

i'm trying print pdf uiwebview , output pdf not fill a4 format. why? how resolve that? any appreciated =) if found solution avoid printing form iuwebview . directly download pdf in nsdata format. _data represente nsdata download request. if (_data) { uiprintinteractioncontroller *printcontroller = [uiprintinteractioncontroller sharedprintcontroller]; printcontroller.delegate = self; uiprintinfo *printinfo = [uiprintinfo printinfo]; printinfo.outputtype = uiprintinfooutputgeneral; //printinfo.jobname = [path lastpathcomponent]; printinfo.duplex = uiprintinfoduplexlongedge; printcontroller.printinfo = printinfo; printcontroller.showspagerange = yes; printcontroller.printingitem = _data; void (^completionhandler)(uiprintinteractioncontroller *, bool, nserror *) = ^(uiprintinteractioncontroller *printcontroller, bool completed, nserror *error) { if (!completed && error) { nslog(@"fail

How to show error line number in R studio -

Image
is possible see syntax error or runtime error line number (highlight also) generated after running code in r studio? i searched options couldn't find. first, have @ ?traceback . there many ways debug r code/script. 1 example. in rstudio, debug drop down menu option on error , choose error inspector (what think is) easiest debug mode finding line number of error/bug. can choose break in code show highlighted line of r script contains error. when error occurs, can click either of small areas marked show traceback , rerun debug . screen shot below shows effect of clicking "show traceback" (hence says "hide traceback"). tells me error occurred when r attempted call sample (the third call). length had not yet been defined.

Auto generate master-detail crud views based on a class in Android -

in same respect orm libraries sugarorm have black-boxed sqlite database operations, there similar library aids in creation of master-detail lists , edit screens based on class? that is, if have few pojos client or order follows: class order { private string foo; private string bar; /* .. other members ..*/ public orders() { ... } /* getters , setters */ } and class client { private string foo; private long bar; /* .. other members ..*/ public client() { ... } /* getters , setters */ } for example, might there method create editview private strings? well started project on github out in creating android view based on class. pojomojo

ios - CMMotionActivityManager ignores cycling -

i've been researching new m7 chip's cmmotionactivitymanager , determining whether user of device walking, running, in car, etc (see apple documentation ). seemed great step forward on trying determine previous using locationmanager , accelerometer data only. i notice cmmotionactivitymanager not have cycling activity, disappointing, , deal-breaker complete usage new activity manager. has else found convenient way use cmmotionactivitymanager cycling without having reincorporate cmlocationmanager + accelerometer try test cycling too? note, not include general transport options things train. instance, commute hour day on train. automotive made more generic @ least, similar how moves uses transport. cmmotionactivity has these defined motion types only: stationary walking running automotive unknown useful notes apple's code, not solve issue, helpful: cmmotionactivity an estimate of user's activity based on motion of device. the a

android - My game shows white textures using LIBGDX and AdMob -

i have succefully add , admob ad game. first time load it, , first time, after lock device or go home when open again game textures white rectangles game still running , can hear sounds , actors still working correctly ad showing fine. pd. discovered happens if open game after installing it. if finish instalation, close installation wizzard(?) , open normaly game problem not happen. i don´t know whats reason of this. my code follows: mainactivity.java public class mainactivity extends androidapplication { private adview adview; relativelayout layout; view gameview; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); androidapplicationconfiguration cfg = new androidapplicationconfiguration(); cfg.usegl20 = false; cfg.useaccelerometer = false; cfg.usecompass = false; // create layout layout = new relativelayout(this); // stuff initialize() requestwindowfeature(window.feature_no_title); ge

dictionary - How would you index a table that is being initialized? -

an example of desire: local x = {["alpha"] = 5, ["beta"] = this.alpha+3} print(x.beta) --> error: [string "stdin"]:1: attempt index global 'this' (a nil value) is there way working, or substitute can use without code bloat(i want presentable, fenv hacks out of picture) if wants take crack @ lua, repl.it testing webpage quick scripts no there no way because table not yet exist , there no notion of "self" in lua (except via syntactic sugar table methods). have in 2 steps: local x = {["alpha"] = 5} x["beta"] = x.alpha+3 note need square brackets if key not string or if string characters other of [a-z][a-z][0-9]_ . local x = {alpha = 5} x.beta = x.alpha+3 update: based on saw on pastebin, should differently: local alpha = 5 local x = { alpha = alpha, beta = alpha+3, gamma = somefunction(alpha), eta = alpha:method() } (obviously alpha has no method because in example nu

ios - UIImageView isn't showing completely on 3,5 screen -

Image
i'm trying show uiimageview images on iphone 4, doesn't appear completely. bottom part hidden...this result: i have tryed 0 constraints on left, right, top , bottom margins no effect... adding width 320 height allways 568px (4 inch screen height ) is not image aspect problem. i'm using aspect fill case , works good, imageview height 568px. if resize manually heigth 480px image ok. thanks lot! don't know can do... try use this, [imgview setcontentmode:uiviewcontentmodescaletofill]

java - How to know in log4j , that ERROR level is triggered? -

how know in log4j , error level triggered. in code have written if exception occurs i.e if error level triggered show log file path in console , wont show message other levels. in log4j can configure different levels in log4j.properties or xml file ever choose use. there predefined pattern error levels , runs lower upper. lowest id debug in sequence. 1.debug 2. warn 3. error etc so if want error messages configure error level error. wot debug , warn if configure debug everything ex. <logger name="org.springframework..."> <level value="error" /> </logger>

Android animate text when calling setText() -

i want animated text fade in , out when changing extending textswitcher in order define once since have many textswitcher objects. however keep on getting null pointer "java.lang.nullpointerexception android.widget.textswitcher.settext(textswitcher.java:80) when doing : hometeamtextview.settext("text"); i decided extend textswitcher class this: public class mytextswitcher extends textswitcher{ public mytextswitcher(context context, attributeset attrs) { super(context, attrs); // todo auto-generated constructor stub setinanimation(context,r.anim.fade_in); setoutanimation(context,r.anim.fade_out); }} activity private mytextswitcher hometeamtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); hometeamtextview = (mytextswitcher) findviewbyid(r.id.hometeam); awayscoretextview = (textview) findviewbyid(r.id.awayteamscore); ho

java - Adding a new object to an array according to loop returns -

i did research on subject (i'm quite new java excuse me poor/incorrect wording) , didn't find related answers, so, here goes. i'm working on program can print prime numbers , ran following problem. here's code: public class pnumba { public static void main(string[] args) { int pnlimit = 100; system.out.println("printing prime numbers"); (int numer = 2; numer <= pnlimit; numer++) { if (checkforprime(numer)) { system.out.println(numer); } } } public static boolean checkforprime(int numer) { (int = 2; < numer; i++) { if (numer % == 0) { return false; } } return true; } } my program prints prime numbers up 100 , not 100 of them. idea make array hold 100 prime numbers , break loop when said array reaches limit fix problem. my questions following: how make loop fill array when checkforprim

php - nette, lighttpd - url rewrite? -

i new nette framework , have no experience url rewriting, apologize question. the default syntax of nette's router is: <presenter>/<action>[/<id>] so urls in format localhost/mypage/articles/view/35 my question how configure lighttpd accept these urls , bind them valid content? i found configuration apache in documentation: http://doc.nette.org/en/2.1/troubleshooting#toc-how-to-allow-mod-rewrite try using magnet-module + lua script add magnet module lighttpd modules server.modules = ( ... "mod_magnet", ... ) lighttpd virtual host example: $http["host"] =~ "^(example.com)$" { server.document-root = "/var/www/example.com/document_root" magnet.attract-physical-path-to = ( server.document-root + "/rewrite.lua" ) } create rewrite.lua file in document_root folder (according setting above) attr = lighty.stat(lighty.env["physical.path"]) if (not attr) l

c++ - Getting memory address of class member variable (non-dynamic) -

i want print memory address (i.e. 0x7ffff0...) of variable in class, gives me value of object. i'm doing learn. don't think syntax incorrect. try 2 ways , neither works. appreciate on why doesn't work. #include <iostream> using namespace std; class test{ public: char i; }; int main(){ test x; x.i='w'; char * y = &(x.i); cout<<"address : " <<&x.i<<endl; cout<<"address : " <<y<<endl; } output: address : w address : w you should cast pointer void* before passing stream. you're passing char* interpreted null-terminated string.

Put jquery mobile autocomplete and select side by side -

i trying put jquerymobile mobile (using version 1.3) selectmenu , autocomplete side side, autocomplete search-box not aligned selectmenu , cut-off @ top. i've tried <div class="ui-grid-a"> <div class="ui-block-a" style="float:left;"> <label for="targettypelist" class="ui-hidden-accessible">all uses</label> <select name="targettypelist" id="targettypelist"> <option value="standard">standard: 7 day</option> <option value="rush">rush: 3 days</option> </select> </div> <div class="ui-block-b" style="float:left;"> <ul data-role="listview" data-inset="true" data-filter="true" data-filter-reveal="true" data-filter-placeholder="search cars..."> <li><a href="#">acura</a></li> <li><a href=&

OpenCV image conversion from RGB to Grayscale exception -

i'm getting strange exception (exception: cv::exception @ memory location 0x002eb6cc) when try convert rgb image grayscale. can me? const cv::mat img1 = cv::imread(filename, 0) cv::mat gs_rgb(img1.size(), cv_8uc1); cv::cvtcolor(img1, gs_rgb, cv_rgb2gray); you loading image gray scale , trying convert gray scale gray scale again. the line const cv::mat img1 = cv::imread(filename, 0) will load image where second argument =0->cv_load_image_grayscale->load gray scale =1->cv_load_image_color->load color <0->cv_load_image_anydepth->return loaded image (with alpha channel). so either load image gray scale , use like, const cv::mat img1 = cv::imread(filename, 0)//load gray or load color , convert gray scale like, const cv::mat img1 = cv::imread(filename, 1);//load color mat gray;//no need of allocation, allocate automatically. cv::cvtcolor(img1,gray, cv_bgr2gray);//opencv default color order bgr see more info here in i

vbscript - VBS: For-each loop (sometimes) iterates through file collection indefinitely -

the goal of following vbscript prepend user-defined string files particular extension within specified directory: directory = "c:\users\xxxxxxxx\desktop\test\" 'include final backslash extension = ".doc" 'include period, ex: ".tab" '''''''''''''''''''''''''''''''''''''''''' addstr = inputbox("enter text prepend:", , "xxxxxxxx_xxxxxxxxxx_x_xx_xxx_") set objfso = createobject("scripting.filesystemobject") set objfolder = objfso.getfolder(directory) set colfiles = objfolder.files each file in colfiles abspath = objfso.getabsolutepathname(file) currentextension = objfso.getextensionname(abspath) if strcomp(currentextension, mid(extension, 2)) = 0 file.name = addstr & objfso.getfilename(file) end if next the script

crash - Android app crashes when any math parser is included -

Image
i trying develop app crashes when include sort of math parser. app works fine otherwise when comment out math parser. tried other parsers, still same problem. ideas why happening? below screen shots. manifest mainactivity file project explorer logcat 04-24 01:13:15.440: d/androidruntime(3481): shutting down vm 04-24 01:13:15.440: w/dalvikvm(3481): threadid=1: thread exiting uncaught exception (group=0xb1a74ba8) 04-24 01:13:15.460: e/androidruntime(3481): fatal exception: main 04-24 01:13:15.460: e/androidruntime(3481): process: com.example.calculator, pid: 3481 04-24 01:13:15.460: e/androidruntime(3481): java.lang.runtimeexception: unable start activity componentinfo{com.example.calculator/com.example.calculator.mainactivity}: java.util.regex.patternsyntaxexception: syntax error in regexp pattern near index 1: 04-24 01:13:15.460: e/androidruntime(3481): } 04-24 01:13:15.460: e/androidruntime(3481): ^ 04-24 01:13:15.460: e/androidruntime(3481): @ android.app.activi

java - Difference in functionality between instance created by classloader and new keyword -

i little bit confused in class loading , initializing concept 1: class.forname("test.employee").newinstance(); 2: classloader.getsystemclassloader().loadclass("test.employee").newinstance(); 3: new test.employee(); every line of above written code creating instance of employee class don't understand difference in 3 methods. the core differences between 3 approaches come down how classes located @ runtime , can them. for example... class.forname("test.employee").newinstance(); will use current class's classloader search class named employee in test package. allow discover classes might not available @ compile time , loaded dynamically same class loader context. search it's parent class loaders if class not found within current context... classloader.getsystemclassloader().loadclass("test.employee").newinstance(); this use "system" classloader , typically 1 launched main application. using e

LoginIn check using Session PHP -

i applying check on login page whenever user clicks on login page previous location gets saved session , $_session['httpreferer']=$_server['http_referer']; now if user clicks on login page more 1 time have store location first time bacause after logging in redirecting user page came using location have saved in $_session['httpreferer']. problem have tried empty() , have tried isset() have tried null() on $_session['htttpreferr'] nothing working .it keeps on storing location again , again in session .the check not working. if( empty($_session['httpreferer'])) { $_session['httpreferer']=$_server['http_referer']; } please little help.thanks !

windows - Teamcity pipe command line output to a file -

is possible call command line program in teamcity , pipe output command line program file? yes of course - can use powershell build step , pipe console output file, here practical example: git rev-parse head > gitrevision.txt note question/answer unrelated teamcity - powershell (you can achieve same using command line)

r - How to avoid using global variables in this case -

the following code tries build simple binary tree. non-leaf node contains left child 'lchild' , right child 'rchild'. leaf node contains nothing. nodes generated 1 one, first left branch right. nodes numbered time generated. node information including lchild , rchild , added bitree grow tree. question is, how can achieve goal avoiding defining 'bitree' , 'i' global? since cause ## rm(list=ls()) ## anti-social set.seed(1234) ##this part generate dataset numvar <- 40 ##number of variables numsamples <- 400 ##number of samples class <- sample(c(0,1), replace = 1, numsamples) ##categorical outcome '0' or '1' predictor <- matrix( sample(c(-1,0,1), replace=1, numsamples*numvar), ncol=numvar) data <- data.frame(predictor, class) ##bitree list storing nodes information, reprenting tree, defined global bitree <- array( list(null), dim = 15 ) ##set global variable store id of each node on tree, defiend global <- 1

java - Android devices connected with NSD, how to send messages using sockets (Client-Client)? -

i've setup p2p communication within app in couple of devices guide: http://developer.android.com/training/connect-devices-wirelessly/nsd.html so, can find other devices in network thats running app. want send messages between clients. can 1,2 or more clients messages go 1 client @ time, more ping request text. i've been reading sockets , seems way go (will communicate ios devices in nearby future). but.. in examples , tutorials found there server in group of clients messages go through. want send message client - - client. basically want: list devices/clients in network running app, done! (is having ipadress, port etc of them) click 1 client , send ping/message any hints or examples at? should client devices have "server" also? regards, kristoffer so figured out @ last. i studying sockets little more in detail. ex: http://docs.oracle.com/javase/tutorial/networking/sockets/clientserver.html and realized needed server on clients work pr

python - OpenCV 2 raising exceptions on read() with different resolutions -

what might reasons of cv2.videocapture.read() exception? i have app shows live feed of camera (preview frames) , after button press takes snapshot higher resolution. the preview frames, @ 640x360 read no problems, after running time starts raise exceptions whenever try retrieve image 1920x1080 resolution. exception: null object passed py_buildvalue . ok .set(3, 640) .set(4, 360) error .set(3, 1920) .set(4, 1080) cam.read() can't return false in tuple, crashes. related code: # timer self.timer = qtimer() self.timer.timeout.connect(self.__countdown) self.timer.start(100) def __countdown(self): self.__grabframe() if self.counter == 1: # show background image elif self.counter % 10 == 0: # show countdown on screen elif self.counter == 29: self.timer.stop() self.counter = 0 self.camcapture.set(3, 1920) self.camcapture.set(4, 1080) self.__takepicture() self.counter += 1 def __grabframe(self): # grab frame, tran

Can typescript external modules have circular dependencies? -

it looks not allowed. requirejs throwing error on following ( this post different resolved internal modules): element.ts: import runproperties = require('./run-properties'); export class element { public static factory (element : ielement) : element { switch (element.type) { case type.run_properties : return new runproperties.runproperties().deserialize(<runproperties.irunproperties>element); } return null; } } run-properties.ts: import element = require('./element'); export class runproperties extends element.element implements irunproperties { } no, modules can't have circular dependencies unless in same file. each file being processed in sequence, synchronously, full file definition (including of exports example) hasn't been completed when goes second file, tries require/reference first file, , on. normally, can break circular dependency introducing interface or base cl

HTML Table from jQuery .load() doesn't render in Firefox -

i have html table want insert multiple html pages. i've used jquery this, except in firefox. here's html file i'm attempting insert table html file (this simplified example, not actual code i'm working with). <!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <meta content="ie=edge" http-equiv="x-ua-compatible"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script> $(document).ready(function() { $('#tablecontainer').load('ipsumtable.htm'); }); </script> </head> <body> <h2>here table</h2> <div id="tablecontainer"></div> </body> </html> the page meant show simple header table underneath. ipsumtable.htm file includes simple html table, so:

immutability - Mutability of arrays in java -

if method returns object particular array index, , object modified, object modified locally or object in array modified? is there way force each case? the object in array modified. works way because, although java pass value, it's passing value of object reference . in end array has copy of reference , whatever gets result has copy of reference. when modify object itself, you're modifying thing both "point" to. both see change. the way make not true make copy of element before return it. alternatively, if make object immutable, don't have worry these details because can't change object in first place.

javascript - Sending JSON jQuery to ASHX - Success Callback not Triggering -

i sending data form via jquery ajax json formatted data. file processing on server ashx handler. below - code snippet: // jquery ajax json ... $.ajax({ type: "post", url: "handler.ashx", data: $.tojson(formdata), datatype: "json", contenttype: "application/json; charset=utf-8", success: function(response) { $('#ajax-loader').hide(); $('#msg').html("ok!"); }, error: function(response) { $('#ajax-loader').hide(); $('#msg').html("error!"); } }); // handler.ashx... public void processrequest(httpcontext context) { context.response.contenttype = "text/plain"; string json = requestbody(context.request); javascriptserializer js = new javascriptserializer(); formdata formdata = js.deserializ

html - Why doesn't an absolutely positioned element position itself relative to its parent if the parent is static? -

i've heard absolutely positioned element positions relative first non-statically-positioned ancestor. there more holistic reason this? or arbitrary choice made, wouldn't true static elements. i guess i'm wondering if there's unified theory of css, speak, i.e. 1 that's perhaps complicated, less complex. 1 outlines behavior of position , static , absolute in such way interaction comes out of natural consequence. i can't find explicit reference rule in css spec; might help. simply because forcing people position elements relative parent element needless limitation. if want position element relative <body> ? if want position element relative specific ancestor? well, set position: relative on target parent. without this, i'd need use js. of course, don't think best way implemented. if wrote spec self, i'd make it: position: absolute(selector); but of course, don't write spec.

arrays - PHP Shopping Cart Variable and Object errors -

i need eliminate errors im getting. have shopping cart displayed on products page way of cart update page. below pair of errors (notices) every product listed: notice: undefined variable: obj in c:\xampp\htdocs\project2\browseproducts.php on line 89 notice: trying property of non-object in c:\xampp\htdocs\project2\browseproducts.php on line 89 when click on of add cart buttons, nothing added cart , get: notice: undefined index: stock in c:\xampp\htdocs\project2\cart_update.php on line 25 my code is: <?php $user = "root"; $password = ""; $database = "webstore"; mysql_connect("localhost", $user, $password); @mysql_select_db($database) or die("unable select database"); $current_url = base64_encode("http://".$_server['http_host'].$_server['request_uri']); $query = "select * products order category";

php - I'm receiving Undefined offset error -

why receive undefined offset error ? i'm trying add 10,20,20 each element in array. please help. in advance <?php $arr = array("a","b","c"); $counter = 0; $status = array(); foreach($arr $a){ $status[$counter] += 10; $status[$counter] += 20; $status[$counter] += 20; echo $status[$counter]."<br>"; $counter ++; } ?> error: notice: undefined offset: 0 in c:\xampp\htdocs\test\index.php on line 6 300 notice: undefined offset: 1 in c:\xampp\htdocs\test\index.php on line 6 300 notice: undefined offset: 2 in c:\xampp\htdocs\test\index.php on line 6 300 ` in code, $status empty array, when attempt add undefined index see notice (only first time). to initialize $status array values 0 based on number of elements in $arr : $status = array_fill(0, count($arr), 0);

ruby on rails - how to restrict active admin to admin users only? -

i have user model rolify gem. in app using active_admin admin interface. have can restrict active_admin admin users only? try putting rolify role check in same place mentioned in active admin documentation's example getting access current user : class onlyadmins < activeadmin::authorizationadapter def authorized?(action, subject = nil) # rolify check here user.has_role? :admin end end

javascript - How to get part of URL current? -

my url looks like: http://google.com/stackoverflow/post/1 now, want part of url: http://google.com/stackoverflow/ , add code: post . how ? ! updated: using javascript: var url = "http://google.com/stackoverflow/post/1"; // or var url = window.location; var matches = url.match(/^http\:\/\/([\w\.]+)\/(\w+)\/.+/); if( matches ){ var newurl = "http://" + matches[1] + "/" + matches[2] + "/"; alert( newurl ); } document.getelementbyid('post_link').href = newurl; html: <a id="post_link">post</a> see jsfiddle

iphone - iOS Tableviewcell separators looks weird -

Image
i using uitabelviewcontroller , static cells in ios 7.1 . seeing desired separator in storyboard , not in simulator . drives me crazy. storyboard screenshot simulator screenshot i don't want white line before separator inset . still need separator way showing in storyboard screenshot. how remove white line? appreciated. i set black color tableview background. still no improvement. cells static , custom cells. thanks other answers here. found out causes bug. - (void)tableview:(uitableview *)tableview willdisplaycell:(uitableviewcell *)cell forrowatindexpath:(nsindexpath *)indexpath { [cell setbackgroundcolor:[uicolor clearcolor]]; } here bug described in ios 7 versions. https://stackoverflow.com/a/18878259/1083859

What is the difference between stemming and synonyms in Amazon CloudSearch? -

i'm looking @ how can tailor cloudsearch analysis scheme provide more relevant search results. (i think) understand conceptual difference between stem , synonym. stems either derivatives, "walk, walking, walked", or depluralisations "company, companies", might want treat same term search point of view. synonyms of course words have same meaning (or meaning that's close enough users might mix , match terms), perhaps "company, enterprise, business", or "email, message". please correct me on above if i'm wrong. i'm more wondering, functional point of view, when index built , search performed, how stem treated differently synonym? have derivatives "walk, walking, walked" in synonyms list , have no difference in functionality?

clang - Xcode bigobj option -

hi xcode 5 failed compile file in 32-bit due size of object file. tried add -bigobj flag doe not change anything. tried change optimization settings without success. the error : "fatal error: error in backend: section large, can't encode r_address (0x1001a97) 24 bits of scattered relocation entry." there no problems when compiling in 64-bit. does have idea ? thanks

php - Copying joomla site to new server but maintaining the new servers admin password -

i ftped files new server (except configuration.php remained same didn't need updating), exported database without table _user, , imported new servers database. i thought because did able log in username , password created when installed joomla on new server i'm getting error message when try log in backend 'failed authenticate'. any idea have done wrong? not migrating users table reason why can't log in. if looking easy way migrate joomla installation between servers akeeba extension. you can't pick , choose tables migrate joomla core relies on of them.

api - Why application user token need be used for mobile applications -

in wso2 apim, according documentation on generating user access token [1]: https://docs.wso2.org/display/am140/generating+access+tokens+to+invoke+apis , says ' user-level tokens allow users invoke api third-party application mobile app'. are these user access tokens used avoid client_id , client_secret exposed via untrusted mobile applications? if so, when creating application user token, token api [2]: https://docs.wso2.org/display/am160/token+api , in below request curl -k -d "grant_type=password&username=&password=&scope=production" -h "authorization: basic svpzswk2seriqjvlofzlzfpbblvpx2zam2y4ytphbtbisjzvv1y4zkm1t1fmtgxdnmpzbefdvzhh, content-type: application/x-www-form-urlencoded" username , password , encoded string of client_id:client_secret sent create new token. mean user_name, password , encoded client_id:client_secret need have saved in mobile application? if so, since mobile application can decompiled , extract these inf

jsf - <f:selectItems is not returning value in <p:selectOneMenu> -

i have problem getting value of f:selectitems returning label. here code; <p:selectonemenu>. <p:outputlabel value="major diseases"></p:outputlabel> <p:selectonemenu value="#{datamigeration.mdid}"> <f:selectitem itemlabel="select one" itemvalue="" /> <f:selectitems var="t" value="#{datamigeration.majordiseas}" itemlabel="#{t.value.mdname}" itemvalue="#{t.value}"/> <p:ajax listener="#{datamigeration.getsubdiseasesbymojardisease(datamigeration.mdid)}" event="change" update="datamigration"/> </p:selectonemenu> here datamigeration class @managedbean(name="datamigeration") @sessionscoped public class datamigeration{ string mdid; private list<selectitem> majordiseas = new array

python - Adding up contents of list - project euler 1 -

i'm trying project euler problem 1 in python ( http://projecteuler.net./problem=1 ) , i'm using while loop loop 1000: from collections import counter x = 0 target = 1000 correctmultiples = list() while x < target: x += 1 if x % 3 == 0 or x % 5 == 0: correctmultiples.append(x) print(str(correctmultiples) + ' multiples of 3 or 5') print('the sum of multiples of 3 or 5 under 1000 is, ' + str(sum(correctmultiples))) # reason, 1000 over, answer 233168 not 234168 this works answer i'm getting 1000 over. 234168 instead of 233168. i've tried checking duplicates: (following how find duplicate elements in array using loop in python? ) duplicates = counter(correctmultiples) print([i in duplicates if duplicates[i] > 1]) but don't think there can duplicates can they? becuase i'm using if x % 3 or ... i know isn't efficient method, still... why doesn't work? can me find why answer 1000 over? thanks yo

android - When should a soft keyboard show an enter key? -

this separate whether app has requested editor action: editor action displayed replacement enter key, it's possible input method offer both alternatives. the simple answer is, of course, "when it's possible enter newline". when textview in single-line mode , it's not possible enter newline if keyboard shows key: found in this answer , android treats key editor action , substitutes zero-width space newlines added textview . how can input method tell whether newlines respected, or otherwise whether it's appropriate show enter key (as alternative specified editor action)? your best bet check editorinfo object returned using getcurrentinputeditorinfo() , take best guess if showing enter key apt or not.

javascript - D3 linking and nodes and dynamic data -

my problem when download data, 2 nodes in left-top corner of svg , have lot of errors saying "invalid value attribute y1="nan"" (and more this, according variable x1, y1, y2). how make work properly? my code js is: <!doctype html> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <style> .link { fill: none; stroke: #666; stroke-width: 1.5px; } .node circle { fill: #ccc; stroke: #fff; stroke-width: 1.5px; } text { font: 10px sans-serif; pointer-events: none; } </style> <body> <script> var links = []; var nodes = []; var width = 960, height = 500; var svg = d3.select("body").append("svg"

mysql - Safety of not catching SQL Exception -

let's have program puts email addresses database email attribute primary key. if have duplicate email address, deal in 2 ways. 1) run "select email table" query. if email in there, don't add it. 2) don't check if email in table. catch(sqlexception e), don't print stack trace, skip on it. way, if i'm inserting duplicate ignores it. granted method 1, i'm executing simple select query (no joins or fancy) performance isn't huge issue. if wanted optimize performance, method 2 viable, safe way of doing this? instead of running "select ..." every time, add it. are there safety issues skipping on exception? java example (with jdbc): try { string sql = "insert emails values(?)"; preparedstatement pstmt = conn.preparestatement(sql); pstmt.setstring(1, email); pstmt.execute(); return true; } catch(sqlexception e) { // e.printstacktrace(); // skip; don't print out error return false; }

java - How to get DataSource connection from a Groovy Class with this groovy code? -

i used have java class in grails app, needed connection datasource.groovy passed groovy class, , made getting context application. how can connect that datasource code?: def datasource = ctx.getbean('datasource_executer') // auto injected , referenced datasource connection conn = null; statement stmt = null; class.forname('driver'); conn = drivermanager.getconnection(datasource);// here it's trouble i need because need metadata of result query this: stmt = conn.createstatement(); def rs = stmt.executequery('query'); def rsmd = rs.getmetadata(); num = rsmd.getcolumncount(); and control while: while(rs.next()){..........} i use groovy.sql package this. import groovy.sql.groovyrowresult import groovy.sql.sql def datasource = ctx.getbean('datasource_executer') def connection = new sql(datasource) def results = connection.rows('select ...') results.each { r -> println r['columnname'] ... } you can

php - Symfony 2.5 receive a segmentation fault periodically on errors -

this has been tough 1 troubleshoot. on error type there chance page crash segmentation fault [fri apr 25 17:45:52.141251 2014] [core:notice] [pid 23298] ah00052: child pid 23367 exit signal segmentation fault (11) . i'm running on symfony framework 2.5, basic page route , controller uses request object. route form_core_page_loader_homepage: path: / defaults: { _controller: formcorepageloaderbundle:default:index } controller use symfony\component\httpfoundation\request; // controller extends symfony's , adds getstore() function , others... use formcore\pageloaderbundle\controller\sessionstorecontroller controller; use formcore\pageloaderbundle\controller\stylesessionstorecontrollertrait; class defaultcontroller extends controller { use stylesessionstorecontrollertrait; public function indexaction(request $request) { $store = $this->getstore(); if (!$store->initrequest($request)) { throw $this->creat

c# - Connection to Site folder via SSL -

ok 1 hard me head around let me explain happening. have sharepoint (maybe irrelevant) site uses https. wrote c# program download files folder site. path folder is string patha = @"\\mysite.com@ssl\davwwwroot\sites\abc\lists\images\screen slides\"; so issue when boot machine, code throw error: folder not found. workaround getting c# program open folder takes 2 steps not know how code. open url run command cannot connect first try. run again connect. takes 2 run commands connect folder. after c# program have not issues finding , accessing folder. my guess need use sort of credentials c# code connect folder without doing work around. looking way connect site code users not have change settings on machine. thanks edit: here code compare ssl folder local directoy. there download or delete files string patha = @"\\mysite.com@ssl\davwwwroot\sites\abc\lists\images\screen slides\"; string pathb = imagepath; system.io.directoryinfo dir1 = new system.io.directo

io - java: converting capital chars to ints -

i working on usaco problem (ride) , trying convert capital char (i.e.'a') it's respective int (for 'a' 1) , not seem working. doing is: for(char c1 : st1ch) { int charint = (int)c1; totalcharsum1 = totalcharsum1*charint; } ..in order convert read string file (which converted array of chars) int counterparts. assumed , read (int)"a" etc. 1. however, code not produce right result apparently. believe problem can see no other problems. have found no guide problem. of course mistake may elsewhere ill post code below anyway: import java.io.*; class ride { public static void main(string[] arg) throws ioexception{ bufferedreader reader = new bufferedreader(new filereader ("ride.in")); string st1 = reader.readline(); string st2 = reader.readline(); int totalcharsum1 = 1; int totalcharsum2 = 1; char[] st1ch = st1.tochararray(); char[] st2ch = st2.tochararray(); for(

c# - How to move cursor in windows form application? -

i'm writing application need move cursor programmatically. i've tried writing: cursor.position = new point(50, 50); but doesn't work. im writing windows form application in c#. i hope can me :) in advance :) assuming want button click: first add interopservices namespace: using system.runtime.interopservices; then create button click event [dllimport("user32.dll")] public static extern long setcursorpos(int x, int y); private void button1_click(object sender, eventargs e) { setcursorpos(50,50); } take @ this: [ https://stackoverflow.com/questions/647236/moving-mouse-cursor-programmatically][1]

ios - SpriteKit circle particle effect -

in ios spritekit. trying create sk particle emitter particle effect circle radius r. ideas how that? thanks! the way achieved using color ramp, starting color 0 opacity, color 1% opacity near end of range , having third color 100% opacity actual circle. here parameters used: particles: 800, maximum:0 lifetime: 1.1, range 0.2 (play , location of colors on color ramp set radius) position range: x=5, y=5 (not must) speed: 30 (should around value) acceleration: x=10, y=10 (small values here) alpha: start=0.3, range=1, speed: 0.1 (play these)

javascript - Mixing in jQuery's UI widget with my topNav kills horizontal alignment -

in web application using jquery , jquery ui (1.10.2 , 1.10.4 respectively), use css in jquery css in /js/jquery-ui-1.10.4/css/ui-lightness/jquery-ui-1.10.4.min.css of zip file jquery site. had topnav bar before got jquery-based autocomplete function work: myprofile link1 link2 | search box | logout my search box 300px , fonts 12px, , width of div container above 700px , before added jquery autocomplete support, this: <div class="topnav"> <div class="left"> <a href...>myprofile</a>>&nbsp&nbsp <a href...>link1</a>>&nbsp&nbsp <a href...>link2</a>>&nbsp&nbsp </div> <input id="searchbox" name="searchbox" type="search" > <div class="right"> <a href...>logout</a> </div> </div> it aligned (all of topnav