Posts

Showing posts from July, 2010

ios - Why a subView won't stay in the parent frame? -

i have view , inside there's uiimage . image isn't static , can move around if drag finger around (using drag events) problem picture moves outside of uiview frame. what's appropriate way keep inside parent frame bounds? --uiviewa --------uiviewb --------------uiimage --------------uibutton i want keep uiimage inside uiviewb - (ibaction)mybuttonsingletap:(uibutton *)sender { imdragging = yes; [_mybutton addtarget:self action:@selector(dragbegan:withevent:) forcontrolevents: uicontroleventtouchdown]; } - (ibaction)mybuttondraginside:(uibutton *)sender { [_mybutton addtarget:self action:@selector(draging:withevent:) forcontrolevents: uicontroleventtouchdraginside]; } - (void)dragbegan:(uicontrol *)c withevent:ev { uitouch *touch = [[ev alltouches] anyobject]; startingtouchpoint = [touch locationinview:self.view]; } - (void)draging:(uicontrol *)c withevent:ev { uitouch *touch = [[ev alltouches] anyobject]; currenttouchpoint = [...

iphone - determine angle between two points on a circle with respect to center -

i have ring(width 25px) uiview . when user selects on ring, want calculate angle between the points selected on fixed point on circle considering center of circle. have found few examples not taking center consideration. what optimum way ? you'll have handle code (i'm java developer), simplest way angle between 2 points on circle (measured against center) recall geometry of situation. triangle formed 2 points on circumference of circle , circle's center isosceles . an isosceles triangle, recall, has (at least) 2 sides of same length -- radial segments 2 points. bisecting angle results in radial segment perpendicular , bisects line connecting 2 points. forms pair of right triangles, radius hypotenuse, , half distance between 2 points 'opposite' side. moving factor of 2 denominator , recognizing twice radius is, calculate distance between 2 points (on circumference), , divide diameter. value sine of half-angle (you desire whole angle). take arcsin...

inheritance - Why people use prototype in javascript when it is easy to inherit using apply () and call () methods? -

shape inherited rectangle. inheritance can done many methods. here have used apply() , call (). when draw method child called, method draw method of base class called again. have done thing in 2 ways. 1 making prototype draw method of base class , other 1 using apply() , call() method. first method : function shape () { this.name='shape'; this.getname = function () { return this.name; }; this.draw = function () { alert("something"); }; } function rectangle () { shape.apply(this); var x=this.draw; this.name = 'rectangle'; this.id=500; this.draw = function () { x.call(this); }; } second method : function shape () { this.name='shape'; this.id=100; this.getname = function () { return this.name; }; } shape.prototype.draw = function() { alert("something"); }; function rectangle () { this.name = 'rectangle'; this.id=200; this.draw = function () { shape.prototype.draw.ca...

c# - Document sniffing via Load<>? -

i'm using ravendb asp.net web api , i've noticed, it's possible query other documents load<type> method. for example: public class person { public string id { get; set; } public string fullname { get; set; } /* other properties */ } public class pet { public string id { get; set; } public string fullname { get; set; } } [httpget] public person findbyid(string id) { using (idocumentsession session = _docstore.opensession()) { return session.load<person>(id); } } if call findbyid("pets/13") via ajax on web api method, i'm getting person object pet's entity data, because share common properties. how can avoid that? expose confidential data attackers. even if properties don't match, object null properties returned exposing existance of entity given id. my current workaround is: [httpget] public person findbyid(string id) { using (idocumentsession session = _docstore.opensession()) ...

c# - Sending SMS for a bulk of users -

i want send sms bulk of users(4000 user) put following method on loop : protected int sendsms(string url) { // send data. streamwriter writer = null; stringbuilder postdata = new stringbuilder(); uri myuri = new uri(url); postdata.append(httputility.parsequerystring(myuri.query).get("username")); postdata.append(httputility.parsequerystring(myuri.query).get("password")); postdata.append(httputility.parsequerystring(myuri.query).get("sender")); postdata.append(httputility.parsequerystring(myuri.query).get("recipients")); postdata.append(httputility.parsequerystring(myuri.query).get("messagedata")); string webpagecontent = string.empty; byte[] bytearray = encoding.utf8.getbytes(postdata.tostring()); httpwebrequest webrequest = (httpwebrequest)webrequest.create(url); ...

sql - Creating mining structures with DMX -

i´m using analysis service make data mining work. made predictions sql server data tools. wanted make same prediction dmx. i´m using next dmx code: create mining model [cassandra] ( [companynk] text key, [date] date key time, [total value mes] double continuous predict, [new items month] long continuous, [number branches] long continuous, [number clients] long continuous, [number salesman] long continuous ) using microsoft_time_series(auto_detect_periodicity = 0.8, forecast_method = 'mixed') drillthrough but following error: error (data mining): usage of non-key columns in 'cassandra' mining model must set predictonly. this should work, because in ssdt have 1 variable set "predict" , have none set "predict only". awesome. thanks in advance. helder borges ok... don't know problem was. shutting-down computer weekend appeared solve problem. didn't despite of turning computer on , compile, , w...

Haskell How to convert general tree to Data.Tree -

i have declared general tree follows data generaltree = emptytree | node [generaltree a] i have built instance of generaltree. want convert tree type declared in data.tree . how do it? i want write function follows type converttree :: generaltree -> tree but i'm having trouble dealing empty tree because there no counterpart in data.tree definition of tree. the maybe can use @ top level of tree, due definition of tree a . avoid conversion of 'pure' emptytree , sound there can't equivalent value in targeted type. said in first answer way accommodate later occurrence of emptytree take advantage of linear recursive nature of list allowing easy way skip them. finally, top node must wrap result maybe type avoid conversion of pure emptytree . then, can reasonably work on sub-forest without worry. this lead version, easiest follow. convertgtree :: generaltree -> maybe (tree a) convertgtree emptytree = nothing convertgtree (gn...

javascript - How to put this div in center and lock everything else with light blue background -

i have div, <div id="messagebox" style="display: none; cursor: default"> <asp:dropdownlist id="ddl" runat="server" enableviewstate="true" autopostback="true" onselectedindexchanged="ddl_selectedindexchanged"/> </div> on click event, showing div using, $('#messagebox').show(); how can put in center of screen , make background light dark, want dropdown list trigger code behind want disable except div, i edited html , added inside tabel. it's working fine , stay in center position on window resizing. check below demo http://jsfiddle.net/nnckt/9/

android - Use variable to any type and check type of this in Java? -

i have serious problems when implementing java library use in android. need global variables, i've solved applying singleton. but i need use variables without specifying type . solution found using object o. object o, how check type of o? o.isarray () // ok type array but know if int, double, ...? another solution using object or variable of type? for example: public string arraytostring (object o) { if (o.getclass (). isarray ()) { arrays.tostring return ((object []) o); else {} o.tostring return (); } } object [] = (object []) lib.getconf ("test"); a_edit [0] = "new value"; a_edit [1] = 2013; x.arraytostring ("test") / / return test x.arraytostring (1989) / / return 1989 x.arraytostring (a) / / return [new value, 2013] thanks you, use instanceof operator. for example: if (o instanceof integer) { //do } else if (o instanceof string) { //do else } else if (o instanceof object[])...

facebook ios api - How to send a synchronous graph request -

in ios 6 using facebook ios sdk 3.5 how can send graph request it's synchornious? or atleast how can synchronize response method? i'm using following method: +(void)hasusergrantedpermissions:(nsarray*)permissions andblock:(void (^)(bool))repeatblock{ [[fbrequest requestforgraphpath:@"/me/permissions"] startwithcompletionhandler:^(fbrequestconnection *connection, fbgraphobject* result, nserror *error) { if([[result valueforkey:@"data"] count] <1){ repeatblock(false); } fbgraphobject* grantedperms = [[result valueforkey:@"data"] objectatindex:0]; for(nsstring* requestedperm in permissions){ if (! [grantedperms valueforkey:requestedperm]){ repeatblock(true); } } }]; } how can alter method or request in such way becomes synchronous? thank you

flash - Multiple labels in a list item -

i want have more 1 labelfield in list pulling database below code: <s:list id="list2" includein="hurlingprofile" x="0" y="63" width="480" height="687" color="#000000" creationcomplete="list2_creationcompletehandler(event)" labelfield="name"> <s:asynclistview list="{getallprofilehurlingresult.lastresult}"/> </s:list> i have shown names need show date of births. i tried adding labels through design view 1 name not names in list. how can add label show in each list item. there several approaches can take: use datagrid if want have multiple columns use inline or separate itemrenderer use itemrendererfunction property of list for use, guess inline itemrenderer good.

java - Testing my sorting function -

i'm trying sort array of numbers using selectionsort , generics , i'm feeling lost. have interface public t[] sort , public void swap. have fix return sorted array of integers? my code is: package sorting; import java.lang.reflect.array; public class selectionsort<t extends comparable<t>> implements iselectionsort<t> { private t[] array; @override public t[] sort(t[] array) { (int = 0; < array.length; i++) { int k = i; (int j = 0; j < array.length; j++) { if ((array[j].compareto(array[k]) == -1)) k = j; } if (k != i) swap(array, i, k); } return null; } @override public void swap(t[] array, int i, int j) { t tmp = array[i]; array[i] = array[j]; array[j] = tmp; } public static void main(string[] args) { selectionsort<integer> ss = new selectionsort<integer>(); integer[] array = { 4, 2, 9, 8 }; system.out.println(ss.so...

spring - Bean definition is abstract Error on a Standalone Java application -

im trying create parentdao handle connection details standalone java application. when run program error below exception in thread "main" org.springframework.beans.factory.beanisabstractexception: error creating bean name 'parentdao': bean definition abstract what doing wrong? know abstract class following examples used abstract classes. abstract parentdao class , 1 dry spring bean im totally lost specially on how on standalone application. , initialize applicationcontext , how. below connection properties (bean.xml) <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="datasource" destroy-method="close" clas...

matlab - error in two dimensional secand method -

i want understand error in following code?code given below function x0=secand2d(f,g,x,dx,tol) % find solution of f(x,y)=0 , g(x,y)=0 i=1:20 x0=x; f0=[feval(f,x0),feval(g,x0)]; x0=x+[dx(1),0]; fx=[feval(f,x0),feval(g,x0)]; fx=(fx-f0)/dx(1); x0=x+[0 dx(2)]; fy=[feval(f,x0),feval(g,x0)]; fy=(fy-f0)/dx(2); a=[fx;fy]+eps; x=x+dx; dx=(-a\f0'-dx')'; if(norm(dx)<tol) ;return; end; end; disp(norm(dx)); pause; end which represents of 2 dimensional secant method,where function f , g defined following form f=@(x,y) (x-sin(x+y)); , g=@(x,y) y-cos(x-y); i have checked , these function works fine on it's parameters f(3,3) ans = 3.2794 and g(1,1) ans = 0 also x=[0.9 0.9]; dx=[0.1 0.1]; tol=1e-5; but following code generated such kind of errors secand2d(f,g,x,dx,tol) error using @(x,y)(x-sin(x+y)) not enough input arguments. error in secand2d (line 5) f0=[feval(f,x0),feval(g,x0)]; please me...

android - not able to extract the drawing cache with overlayed bitmap images -

i trying save canvas on sdcard. drawing 2 bitmaps (one on top of another) in ondraw(canvas canvas) method. when save file, bottom layered bitmap stored. posting code ondraw method here: paint paint = new paint(); paint.setcolor(color.black); //rectangle first image rct = new rect(10, 10, canvas.getwidth(), canvas.getheight()); // rectangle second image, secong image drawn user touches screen new_image = new rectf(touchx, touchy, touchx + secondbitmap.getwidth(), touchy + secondbitmap.getheight()); //this bitmap drawn first canvas.drawbitmap(firstbitmap, null, rct, paint); //this bitmap drawn on top of first bitmap on user touch canvas.drawbitmap(secondbitmap, null, new_image, paint); canvas.save(); the code saving canvas on sdcard written on mainactivity is: bitmap bm = canvas.getdrawingcache() // canvas in object of class extended view string path = environment.getexternalstoragedirectory() .ge...

8086 - Assembly CMP result differs depending on used register? -

i've been working on assembly project , came across fact can't understand. i have word-array called "lent" filled numbers. when print under 0 index shows ascii 0 (null). however, when use cmp check if value 0, trouble. here code: mov di,offset lent mov cx,0d cmp ds:[di],cx it returns not equal, if [di] did not contain zero. however: mov di,offset lent mov cl,0d cmp ds:[di],cl returns equal, , there makes me confused. need first case working in code. if lame question, sorry, not able find appropriate answer on internet. in advance sparky's answer correct. avoid confusion , detect bugs, try use size prefixes like mov di, offset lent mov cl, 0d cmp byte ptr [di], cl if try use word ptr prefix, like cmp word ptr [di], cl using debug.exe, show error msg.

java - Confusion in Builder plus Singleton pattern in example from fluffycat -

i tryingout builder examples fluffycat sodaimpsingleton sodaimpsingleton = new sodaimpsingleton(new cherrysodaimp()); system.out.println("testing medium soda on cherry platform"); mediumsoda mediumsoda = new mediumsoda(); mediumsoda.poursoda(); here there no relation between sodaimsingleton , mediumsuda, still when mediumsoda.poursoda() called prints cherrysodaimp.poursodaimp() how/why happening? there relationship. sodaimpsingleton instantiated cherrysodaimp . next, mediumsoda extends soda , in constructor calling method setsodaimp() , implemented sodaimpsingleton.getthesodaimp(); in abstract soda class, static method returns cherrysodaimp instance created on first line.

java - Eclipse and short circuit evaluation -

im trying use short-circuit evaluation simplify writing of check , eclipse calls "the local variable inherit may not have been initialized" in last statment of if clause, using evaluation method correctly ? can ide understand evaluation of statement ? if ((classname.startswith("svl")) && ((inherit = aast.findfirsttoken(tokentypes.extends_clause)) == null) || !(inherit.gettext().equals("servlet******"))) { log(aast.getlineno(), "error" + tokenident.gettext()); } you have got parentheses wrong, that's causing error. simplified, structure of boolean expression is (a && b) || c where in b assign inherit . if fails, (a && b) short-circuited false, b not evaluated, , c needs evaluated find out final result. clearly, inherit may not have been initialized when c evaluated. depending on after, can swap positions of , b. ensure b evaluated always. alternat...

PHP if statement. Display and image if true -

i'm accessing api returning value of array. want image displayed based on result. example if div contains "above average" display image called aboveaverage.png. echo $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']; this results "above average" how can display particular image correspond this? something -> if div "crime_level" = above average then: display aboveaverage.png i'm pretty new php, sorry i'm noob. use case selecting switch switch ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']) { case "above average": $image = "aboveaverage.png"; break; case "below average": $image = "belowaverage.png"; break; default: $image = "unknown.png"; }; echo ...

How to draw 10,000+ objects and move them and get 60fps+ in Vizard Python -

i trying create world in vizard 4.0 automatically generates 10,000+ objects in it. once these objects made, want fly through them or make them move @ speed in direction want. i have written code not giving me fps want. 7fps code , need go 60fps minimum. have tried both moving them , moving camera. both give same fps. have written part of moving balls move on own in 1 direction , make camera move need hold down either left mouse button or right mouse button or both. to run program first need install vizard worldviz. comes 90-day free trial. new vizard appreciated. thank you code below: enter code here import viz import vizact import vizshape import random import vizinfo import viztask #enable full screen anti-aliasing (fsaa) smooth edges viz.setmultisample(4) #start world viz.go(viz.fullscreen) #increase field of view viz.mainwindow.fov(60) #set location 8 meters 0,0,0 viz.move([0,0,-8]) def create_shape(number,x_pace,y_pace,z_pace,set_time) : #create array of ...

java - How to get the data list as JSON String -

inner lists not return json string.. first data list return... is there way data json string ? ------my method --------------------- @requestmapping(value="/mainreservationchart", method = requestmethod.get) public modelandview getmrchartdata(@modelattribute ("reservationsummaryrqdto") reservationsummaryrqdto search){ reservationsummarydto returndatadto = new reservationsummarydto(); mainreservationchartwsimpl wsimpl = mrwsutil.getinstance().getws_serviceport(); search.sethotelcode("bbh"); search.setreportdate(toxmldategmt(new date())); returndatadto = wsimpl.getreservationsummary(search); map<string, object> model = new hashmap<string, object>(); model.put("status", true); model.put("hotelcode", returndatadto.gethotelcode()); model.put("summary", returndatadto.getsummarymonth()); model.put("data", returndatadto); return new modelandview("js...

javascript - Using string based variables in knockouts controlflow templates -

i'm using knockout's containerless controlflow templates: <div data-bind="foreach: mydata" style="margin-top: 10px;"> <div> <a href="#" data-bind="attr: {href: url}" target="_blank"> <img src="http://www.google.com/s2/favicons?domain={{url}}" /> </a> </div> </div> getting url href working, want call url value again in image src. want keep beginning part of image source , add url end. how 1 using knockout template? for simple task don't need additional templating because ko lets write arbitrary expression in bindings string concatenation. so can build url right in attr binding: <div data-bind="foreach: mydata" style="margin-top: 10px;"> <div> <a href="#" data-bind="attr: {href: url}" target="_blank"> <img...

iphone - Post to Facebook and twitter when one button? -

can please me out, how connect facebook , twitter same button? example has written status update, , 1 button press sends both facebook , twitter?. thanks.. what can create service first connects , authenticates users facebook , twitter account. once done can call service post update. let me expand: there service called ifttt https://ifttt.com/ what service authenticates both facebook , twitter account (one one). once ifttt gets permission, whenever post on 1 these accounts, calls service , same on other account. so, can create recipe: if post on facebook, post on twitter well.

Include an existing CSS file in custom extjs theme -

i have existing css file include in extjs production build. i using custom theme. know can go myapp/packages/mycustomtheme/sass/etc/ , use @import in all.scss file. uses @import in production file. i'm hoping there way can existing css file compressed rest of app's css. to include custom css file in production build, can include stylesheet above <!-- <x-compile> --> comment in index.html . index.html should this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>yourappname</title> <link rel="stylesheet" href="link-to-custom.css"> <link rel="stylesheet" href="link-to-another-custom.css"> <!-- <x-compile> --> <!-- <x-bootstrap> --> <link rel="stylesheet" href="bootstrap.css"> <script src="ext/ext-dev.js...

ios - Passing managedobjectContext to tabbarcontroller with navigation controllers in modal view -

Image
for small app, have login screen. on auth, tab bar controller 2 views (one navigation controller) presented. following tutorial. uses core data. http://maybelost.com/2011/12/tutorial-storyboard-app-with-core-data/ tutorial calls segue. use presentmodalviewcontroller. works, except wondering how pass managedobjectcontext view inside navigation control inside tab bar controller. i read passing managedobjectcontext view controllers using storyboards root uitabbarcontroller , comments under second answer not right method. can tell me correct way it? looking know how reference view inside tabbar controller can set managedobjectcontext view. thanks edit in appdelegate.h: @interface appdelegate : uiresponder <uiapplicationdelegate> @property (readonly, strong, nonatomic) nsmanagedobjectcontext *managedobjectcontext; my appdelegate.m : - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { loginviewcontr...

linux - ps x shows weird command: -f html/index.php -

just went check 1 of homepages , greeted message: "cgiwrap error: real uid not changed!". went in via ssh , tried "ps x" showed me tons of processes that "-f " , path index.php or other site. after killing processes went normal. anyone know is? google did not @ all. -f file.php is bash command checks file exists , regular file. however, cannot give reason having tons of processes , blocking cgi.

Apache mod rewrite url htaccess -

i little bit confused , still learning on how rewrite in apache htaccess how can turn this: http://www.mydomain.com/dir1/post.php?%20id=1 into this: http://www.mydomain.com/category1/post/1 this reference, i'm not sure if doing correctly <a href='http://www.mydomain.com/dir1/post.php? id=$id'> you can use simple rewrite rule if need rewrite single url. rewriterule ^dir1/post.php?%20id=1 category1/post/1 [l] or may need replace %20 whitespace character regex rewriterule ^dir1/post.php?[\s]id=1 category1/post/1 [l] you need make sure mod_rewrite on ('rewriteengine on' in .htaccess). here tut: http://coding.smashingmagazine.com/2011/11/02/introduction-to-url-rewriting/

emacs - How do you switch between files when using prelude's projectile? -

Image
imagine have these files in project: a/b/first.png a/first.png if trigger projectile c-c p f , write first.png, , write first.png , show me both files. there way select next file? example: in image below, first file in list .document. without writing other letter, possible switch through list provided projectile? there combination cycle through file names, , press key combination , .gitignore selected? if correctly understand, projectile uses ido package file name completions, , other things. ido (and many other packages) uses c-s switch next file name, , c-r switch previous file. see "using ido" section in previous link

c++ - Designing an API to accept a generic output stream as a parameter -

i designing api using llvm library accept output stream 1 of constructor parameters. llvm coding standards dictate following: use raw_ostream llvm includes lightweight, simple, , efficient stream implementation in llvm/support/raw_ostream.h, provides of common features of std::ostream. new code should use raw_ostream instead of ostream. unlike std::ostream, raw_ostream not template , can forward declared class raw_ostream. public headers should not include raw_ostream header, use forward declarations , constant references raw_ostream instances. i must abide llvm coding standards, trying accept raw_ostream parameter in constructor. have tried passing raw_ostream reference , pointer, receive following error message @ compile time: note: candidate constructor not viable: no known conversion 'llvm::raw_ostream &()' 'llvm::raw_ostream &'... what should constructor accept parameter of type 'llvm::raw_ostream &()...

android - intent-filter for a service : using a custom mime type -

i want add custom mime android service or broadcastreceiver detect custom files. have seen answers questions how add custom mime type? , how add custom mime type? the answers here shown activity. modifications required service or broadcastreceiver? tried same code them, did not work. new android development. nice , detailed explanation welcome. possible? going wrong. the code used : <service android:name="xcardreceivedservice" android:exported="true" android:enabled="true"> <intent-filter> <!-- <action android:name="android.intent.action.view" /> <category android:name="android.intent.category.default" /> <category android:name="android.intent.category.browsable" /> --> <data android:scheme="file" /> <data an...

Convert time stamp to date in query select statment in google spreadsheet -

i importing data form data collection sheet , change timestamp date make easier me filter. what want able filter data based on dates provide example filter data between 4/20/2013 , 5/1/2013. time stamp in datetime format making difficult so. is there way can query(a:d,"select date(a), b, c",1) table has date not datetime or if set a1 = 4/20/2013, b1 = 5/1/2013, c1 = query(sheet1!a:d,"select a, b, c, d >= date'"""&a1&"""' , <= date'"""&b1&"""'",1) please me getting point thank you khokhar have @ todate() here . =query(sheet1!a:d,"select a, b, c, d todate(a) >= date'" &a1& "' , todate(a) <= date'" &b1& "'",1)

Sending cookie to Node.js -

i'm making request node.js server using postman plugin chrome. in headers have field called cookie , it's populated authsession cookie so: authsession="somekeyhere"; i've tried using set-cookie field well, honest don't know difference between two. here code that's supposed receive cookie, doesn't seem working. exports.add = function(req, res) { console.log(req.cookies['authsession']); } it keeps logging undefined. i'm doing wrong, i'm not sure what. verify first setting cookies working. use function below , load twice. first time it'll show existing cookie. second time it'll show cookie set first time. exports.add = function(req, res) { console.log(req.cookies['authsession']); res.cookie('authsession', 'somekeyhere'); res.send("<html><body>hello world</body></html>"); }

linux - Android Device Driver make node -

i have course project involves setting device driver on android. have worked device drivers in linux kernel , used 2 commands initialize device , make node: insmod , mknod now when launched emulator shell using adb shell , able use insmod mknod did not work. have tried find alternatives not lucky. from know, mknod in linux kernel lists device under /dev directory , allows user programs read/write using file ops. so alternative android? perhaps, android device you're using don't have mknod command. need supported rootfs, android rootfs built using busybox. probably, mknod dropped busybox config. possible option be, use custom android image you've mknod installed.

google app engine - Trouble importing the correct module in python in GAE -

how explicitly tell google app engine (python) import json python standard libraries? due poorly named file (that can not change or rename @ time) having trouble importing json. there json.py in same directory file working on. when try: import json it imports file in same directory. is there way can along lines of: from ../ import json to import native json library? edit: i have tried renaming offending file , replacing uses of file. i'm still not able import json standard lib through gae. attached error log: file "/users/admin/blah/dataaccess.py", line 13, in <module> classes import zendesk file "/users/admin/blah/classes/zendesk.py", line 10, in <module> import json file "/users/admin/googleappenginelauncher.app/contents/resources/googleappengine-default.bundle/contents/resources/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 892, in load_module raise importerror(...

sorting - Disable multiple sort in Django Admin >= 1.4 -

i using django non rel on app engine , problem feature of sort multiple columns in django admin, because need lot of indexes. recreate behavior in django 1.3, can sort column when click it. i tried googling , everything, couldn't find how. there's no "proper" way (in 1.4, not sure later versions) however, turned out quite simple disable in code. edit result_headers function in django/contrib/admin/templatetags/admin_list.py at line 149, insert following lines (just before yield statement): o_list_primary = [make_qs_param(new_order_type, i)] o_list_toggle = [make_qs_param(new_order_type, i)] why desirable disable multiple sort functionality? when using django-nonrel (e.g. on google app engine) each unique combination of sort orders requires own index. list 5 sortable columns, requires more maximum permitted number of indexes per entity (which 200)

ruby - How to work with an instance of a model without saving it to mongoid -

the users of rails app receiving lot of emails (lets represent signups new customers of users). when email received customer should created, , email should saved well. however, if customer exists (recognized email address of email), email email should not saved database. thought handled email.new , , save if email address recognized. seems email.new saves record database. how work email before deciding wether want save it? example code: class email include mongoid::document field :mail_address, type: string belongs_to :user, :inverse_of => :emails belongs_to :customer, :inverse_of => :emails def self.receive_email(user, mail) puts user.emails.size # => 0 email = email.new(mail_address: mail.fetch(:mail_address), user: user) # here want create new instance of email without saving puts user.emails.size # => 1 is_spam = email.test_if_spam ...

how to change the color of one portion of an image to another portion of the same image using MATLAB -

i have color image. image consists of object has shadow. have removed shadow shadow portion's color not similar background color .now how can match color using matlab coding? you can change matlab matrix (here called img) corresponds image. example, changed pixels of shadows -20. can indexes doing indexes = (img == -20) to change values background color, assumed equals 100 example, set doing img(indexes) = 100 since you're working color images, need 3 color matrices corresponds image. in case have background color each layer, repeat process indexes1 = (img(:, :, 1) == shadow_color_layer_1) indexes2 = (img(:, :, 2) == shadow_color_layer_2) indexes3 = (img(:, :, 3) == shadow_color_layer_3) img(indexes,1) = background_color_layer_1 img(indexes,2) = background_color_layer_2 img(indexes,3) = background_color_layer_3

ios - Strange Behavior in Scrolling UIScrollView to UITextView hidden by keyboard -

i have looked @ number of posts here on scrolling , unhiding uitextfield , believed same code should work uitextview, seems not case. first issue encountered sample app have ipad app supporting landscape orientation only. keyboard size returned notification had height , width of keyboard reversed. next, while can scrollview scroll textview, not reveal of , in fact amount of textview shown dependent on tap in textview. more scrolling cursor not want. here code using. taken example, real change uitextview used instead of uitextfield. if thing replace textview textfield works fine. - (void)keyboardwasshown:(nsnotification*)anotification { nsdictionary* info = [anotification userinfo]; cgsize kbsize = [[info objectforkey:uikeyboardframebeginuserinfokey] cgrectvalue].size; uiedgeinsets contentinsets = uiedgeinsetsmake(0.0, 0.0, kbsize.width, 0.0); _myscrollview.contentinset = contentinsets; _myscrollview.scrollindicatorinsets = contentinsets; cgrect arect =...

PHP| Mysql - Image next and previous button -

Image
i made image gallery, right have problem displaying pictures , 'next/previous' button. as can see below, bigger picture main picture 'view_gallery.php?id=??' while rest different picture. is there way make more neat? how make box/ table store images database, more neat, previous , next button. this screenshot imgur, rest of pictures stored in next box thingy my lecturer told me 'image-buffer'(i'm sure misheard said) ps. googled image-buffer , got adobe after effects stuffs. think that's not it.

html - How to embed PDF file with responsive width -

i'm embedding pdf files using this: <div class="graph-outline"> <object style="width:100%;" data="path/to/file.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0" type="application/pdf"> <embed src="path/to/file.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0" type="application/pdf" /> </object> </div> it works want set pdf width match width of containing div. shows iframe scrollbars, view entire pdf, have scroll right left. want pdf fit width of container. how fix this? i'm supporting ie8 , up. here jsfiddle: http://jsfiddle.net/s_d_p/ktkcj/ just simpl :- <object data="resume.pdf" type="application/pdf" width="100%" height="800px"> <p>it appears don't have pdf plugin browser. no biggie... can <a href="resume.pdf">click here download pdf file.</a><...

sql - Finding records sets with GROUP BY and SUM -

i'd query every groupid (which come in pairs) in both entries have value of 1 hasdata. |groupid | hasdata | |--------|---------| | 1 | 1 | | 1 | 1 | | 2 | 0 | | 2 | 1 | | 3 | 0 | | 3 | 0 | | 4 | 1 | | 4 | 1 | so result be: 1 4 here's i'm trying, can't seem right. whenever group by on groupid have access in selector select groupid table group groupid, hasdata having sum(hasdata) = 2 but following error message because hasdata acutally bit: operand data type bit invalid sum operator. can count of 2 both records true? just exclude group id's have record hasdata = 0. select distinct a.groupid table1 not exists(select * table1 b b.hasdata = 0 , b.groupid = a.groupid)

How to keep your data during ajax call in asp.net? -

in asp.net page, using ajax, , want know how keep variable data when doing ajax call. on page load, download lot of information database , display on page. during ajax call, want use data stored in variable, problem is, during ajax call, data goes away, , have re download data again. is there way keep during ajax call? in asp.net have many ways this, session["yournamehere"] have vale until sesion closed or viewstate["yournamehere"] have value in page until closed. some links using viewstate or using sesionstate hope help. edit using viewstate. first put serializable in class. [serializable] public class fruits { public string apple { get; set; }} save value: fruits fruit = yourmethod(); //yor method retrive data database* viewstate["fruit"] = fruit; when you'll use viewstate: fruits fruit = viewstate["fruit"]

how to copy linked file thru tcl -

i want copy file thru tcl proggraming , these files linked. code: if { [file type $sfile] == "link" } { set fget [file readlink $sfile ] } file copy -force $fget $dir it works if $sfile link. not work if source file of link link. how can recursively trace symbolic links? recursive. while {[file type $sfile] eq "link"]} { set newfile [file readlink $sfile] if {[string index $newfile 0] ne "/"} { set newfile [file dirname $sfile]/$newfile } set sfile $newfile } file copy -force $sfile $dir

Adobe air native extension application crashes on using FragmentActivity -

i trying work on air native extension android. far have worked on different type of stuff seems have hit roof. whenever try extend fragmentactivity rather normal activity application crashes activity starts. trying use actionbarsherlock, same thing happens. moment extend sherlockactivity, application crashed on starting activity. please please me this. package com.someone.mobile.android.extensions.aub; import android.support.v4.app.fragmentactivity; public class loginactivity extends fragmentactivity{ @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); } }

Wrapping C-enum in a Python module with Swig -

i have simple enum in c in myenum.h: enum myenum { one, two, 3 }; the problem when map python, can access enum through module name, not through myenum. values one, two, 3 included other functions define, instead of being contained myenum. my api.i file is: %module api %{ #include "myenum.h" %} %include "myenum.h" i generate swig swig -builtin -python api.i and import python import _api and have use enum values _api module: _api.one _api.two _api.three while want use them like _api.myenum.one _api.myenum.two _api.myenum.three does know how can accomplish this? there swig feature nspace want want, unfortunately isn't supported python yet. i've had define enum in struct show in manner desire in swig. example: %module tmp %inline %{ struct myenum { enum { a,b,c }; }; %} result: >>> import tmp >>> tmp.myenum.a 0 >>> tmp.myenum.b 1 >>> tmp.myenum.c 2

ruby on rails - Adding extra registration fields with Devise -

Image
i trying add fields registrations#new. since want data , not need different functionality, don't see why need override controllers etc. did modify registrations#new follows: to enable these fields through sanitizer, updated applicationcontroller follows: for reason, not working , fields go database nulls. i using ruby 2 , rails 4 rc1, devise 3.0.0.rc. it appear code sample in question not working because not setting before_filter call sanitizer. before_filter :configure_permitted_parameters, if: :devise_controller? with said, it's better override controller, shown in accepted answer, application controller isn't doing check of time. accepted answer can shortened code below. i've tested code application , works well. of documented in strong parameters section of readme in 3.0.0.rc tag. override controller: class registrationscontroller < devise::registrationscontroller before_filter :configure_permitted_parameters, :only => [:creat...

.net - C# new Form return Value not recognised by Mainform -

i open additional form through toolstrip enter username needed in mainform (and declared string in mainform) code of mainform: private void toolstripbutton6_click(object sender, eventargs e) { using (form frm = new form3()) { frm.formborderstyle = formborderstyle.fixeddialog; frm.startposition = formstartposition.centerparent; if (frm.showdialog() == dialogresult.ok) { username = frm.returnvalue1; } } } code of form3: public string returnvalue1 { { return textbox1.text; } } private void button1_click(object sender, eventargs e) { this.close(); } c# tells me there no frm.returnvalue1 :( you have declared form type form not form3 : using (form frm = new form3()) and class form doesn't have property returnvalue1 getting error. compiles because form3 subclass of form can assign vari...

MATLAB: Plot with For Loop Fixed Variables -

in matlab, have following output of data script: a1 = [1 2;3 4] a2 = [2 2; 4 5] a3 = [3 5; 7 8] i need create loop step through each variable , plot. like: for = 1:3 plot(a(i)) end so a1 generate plot. a2 generate plot. , a3 generate plot. thanks loop using eval (will emulate variable variable) , figure (will create figure each a): a1 = [1 2;3 4]; a2 = [2 2; 4 5]; a3 = [3 5; 7 8]; = 1:3 figure(i); eval(['plot(a' num2str(i) ');']) end if have many might want save plots automatically, inserting following line right after eval line in loop: print('-dpng','-r100',['a' int2str(i)])

Generating numbers with Gaussian function in a range using python -

i want use gaussian function in python generate numbers between specific range giving mean , variance so lets have range between 0 , 10 and want mean 3 , variance 4 mean = 3, variance = 4 how can ? use random.gauss . docs : random.gauss(mu, sigma) gaussian distribution. mu mean, , sigma standard deviation. faster normalvariate() function defined below. it seems me can clamp results of this, wouldn't make gaussian distribution. don't think can satisfy constraints simultaneously. if want clamp range [0, 10] , numbers: num = min(10, max(0, random.gauss(3, 4))) but resulting distribution of numbers won't gaussian. in case, seems can't have cake , eat it, too.

c++ - Makefile leads to compilation error -

i'm trying compile program (which isn't mine): make -f makefile ... using following makefile : # compiler .cpp files cpp = g++ # use nvcc compile .cu files nvcc = nvcc nvccflags = -arch sm_20 # fermi's in keeneland # add cuda paths icuda = /usr/lib/nvidia-cuda-toolkit/include lcuda = /usr/lib/nvidia-cuda-toolkit/lib64 # add cuda libraries link line lflags += -lcuda -lcudart -l$(lcuda) -lgomp # include standard optimization flags cppflags = -o3 -c -i $(icuda) -xcompiler -fopenmp -dthrust_device_backend=thrust_device_backend_omp # list of objects need objects = timer.o ar1.o kgrid.o vfinit.o parameters.o # rule tells make how make program objects main : main.o $(objects) $(cpp) -o main main.o $(objects) $(lflags) # rule tells make how turn .cu file .o %.o: %.cu $(nvcc) ${nvccflags} $(cppflags) -c $< # how make know how turn .cpp .o? it's built-in! # if wanted type out like: # %.o: %.cpp # $(cpp) $(cppflags) -c $< ...

html - Horizontal center a div with dynamic width using css -

i've seen million blog posts subject cannot find solution specific problem. set following: <div id="wrapper" style="position:absolute; max-width:500px; min-width:300px; width:100%"> </div> how can center wrapper using css. margin:auto won't work. its style position:absolute , you're either going have change this: style="position:absolute; max-width:500px; min-width:300px; width:100%" /* changes to: */ style="margin: 0px auto; max-width:500px; min-width:300px; width:50%" /* width changes there's room center */ or if want keep position:absolute , you'll have manually set x , y positions javascript. if mean want center stuff inside it, add text-align: center; .

php - how can I get xdebug to run in Windows -

Image
i apologize if not following protocol question; realize has been asked. however, have yet see answer (that works) i trying xdebug working on windows 7 box. whatever build try (and have tried more 5 point), message when run php -m : failed loading c:\php5\ext\php_xdebug-2.2.2-[compile + build].dll i have used "wizard" (it doesn't provide information) , module doesn't work. make xdebug works can little trick. but, after move through challenges, see benefits of find bugs , fix them. first of all, need find out version environment. tight related php version running , xdebug page place go figure out. xdebug wizard helps xdebug module compiled fit environment. if copy output of following command: php -i inside text box , hit button "analyse phpinfo() output" showed below: you see report xdebug version need. of times, link download available showed below. if link not show, version should have no compatibility xdebug after follow ...

php - Redirect to controller action in sub folder - Laravel 4 -

i'm new laravel. might simple unable find example or documentation. i need redirect user action in controller in sub folder. folder structure: **app** ---**controllers** ------**admin** ---------adminhomecontroller.php (extends admincontroller) ------admincontroller.php ------basecontroller.php ---**models** ---**views** ------**admin** ---------dashboard.php ------login.php routes.php route::get('/login', function() { return view::make('login'); }); route::group(array('before' => 'auth'), function() { route::resource('admin', 'adminhomecontroller'); }); route::post('/login', function() { auth::attempt( ['email' => input::get('email'), 'password' => input::get('password')] ); **return redirect::action('adminhomecontroller@showadmindashboard');** }); after login i'm wanting redirect action in adminhomecontroller called "showadmi...

python - Matrix multiplication in pandas -

i have numeric data stored in 2 dataframes x , y. inner product numpy works dot product pandas not. in [63]: x.shape out[63]: (1062, 36) in [64]: y.shape out[64]: (36, 36) in [65]: np.inner(x, y).shape out[65]: (1062l, 36l) in [66]: x.dot(y) --------------------------------------------------------------------------- valueerror traceback (most recent call last) <ipython-input-66-76c015be254b> in <module>() ----> 1 x.dot(y) c:\programs\winpython-64bit-2.7.3.3\python-2.7.3.amd64\lib\site-packages\pandas\core\frame.pyc in dot(self, other) 888 if (len(common) > len(self.columns) or 889 len(common) > len(other.index)): --> 890 raise valueerror('matrices not aligned') 891 892 left = self.reindex(columns=common, copy=false) valueerror: matrices not aligned is bug or using pandas wrong? not must shapes of x , y correct, column names ...

c++ - What does it mean to satisfy O(f(N)) for a given equation f(N)? -

this question on final review i'm still uncertain about. i've figured of other 74 out, 1 stumping me. think has finding c , k, don't remember how or means... , may not on right track there. the question i'm encountering "what minimum acceptable value n such definition o(f(n)) satisfied member function heap::insert(int v) ?" the code heap::insert(int v) follows: void insert(int v) { if (isfull()) return; int p=++count; while (h[p/2] > v) { h[p] = h[p/2]; p/= 2; } h[p] = v; } the possible answers given are: 32, 64, 128, 256 . i'm stumped , have take exam in morning. immensely appreciated. i admit question quite obscure, try give reasonable explanation. if call f(n) temporal complexity of operation executed code function of number of elements in heap, professor wanted remember f(n) = o(log(n)) binary heap insert, o(h) , h height of heap , assume complete (remember how heap works , can represented b...

ruby on rails - Modify filename before saving with Carrierwave -

i've uploader i've implement #filename method custom , unique filename looks method ignored before saving file (i'm uploading rackspace fog gem) here uploader: class myimageuploader < carrierwave::uploader::base include carrierwave::rmagick ... def filename if original_filename.present? "#{secure_token}.#{file.path.split('.').last.downcase}" else super end end ... private def secure_token var = :"@#{mounted_as}_secure_token" model.instance_variable_get(var) or model.instance_variable_set(var, securerandom.uuid) end end and here test in console (i'm testing issue large filenames thought solved custom #filename method): 1.9.3-p392 :002 > f = file.open('/users/myuser/desktop/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...

image - Drawing a curved line between two points in PHP -

Image
i want draw simple curved line between 2 points. more specifically, top left , bottom right corner of image of arbitrary size. i tried using imagearc, apparently that's not i'm looking for. illustrate mean: i can't find function me along, appreciated :) you use imagemagick instead of image gd. image gd has no build-in support curves. if don't have possibility use imagemagick, still use imagesetpixel , create own curve simple de casteljau algorithm

paypal transaction history creates an extra recurring payment -

Image
i'm using paypal recurring gem: https://github.com/fnando/paypal-recurring for ruby on rails application here's selected portion of code: def make_recurring process :request_payment if @plan create_units process :create_recurring_profile, period: @plan.recurring, amount: (@plan.price), frequency: 1, start_at: time.zone.now end end def process(action, options={}) not_recurring_amount = @cart.total_price not_recurring_amount += 19.95 if @plan #add activation price first payment options = options.reverse_merge( token: @order.paypal_payment_token, payer_id: @order.paypal_customer_token, description: "your product total below", amount: not_recurring_amount.round(2), currency: "usd" ) response = paypal::recurring.new(options).send(action) raise response.errors.inspect if response.errors.present? response end essentially, user buys product , gets c...

c# - Extracting the contents of a zipped tab delimited file from a byte array -

i've seen answers question posted, nothing struggling with, , i'm having trouble. basically, using api returns data in byte array so: byte[] file = api.getzippedreport(blah, blah); i'm trying figure out best way spit out contents of tab delimited file in c# can it. what simplest way data can use without having save file? in case .net 4.5 application can use newly introduced ziparchive class offers getentry() method: stream stream = new memorystream(file); // file byte[] ziparchive archive = new ziparchive(stream ) ziparchiveentry entry = archive.getentry("existingfile.txt"); // logic file entry.open() entry.lastwritetime = datetimeoffset.utcnow.localdatetime; see ziparchive class , ziparchive.getentry method . there property on ziparchive called entries contains entries in readonly collection: public readonlycollection<ziparchiveentry> entries { get; }