Posts

Showing posts from July, 2014

android - onCreateView ListView is Empty. Items Missing -

Image
resolved. see singularhum's answer below. i have sliding menu option points fragment. fragment inflates layout using oncreateview . update values of list in onactivitycreated . here source. my listview public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { this.dateformat = new simpledateformat("dd/mm/yyyy hh:mm", locale.getdefault()); this.portfolio = new portfolio(); this.portfolio.addcompanynoupdate("yhoo"); // specify fragment layout file fragment class view view = inflater.inflate(r.layout.fragment_stock, container, false); progresstext = (textview) view.findviewbyid(r.id.progresstextview); // assign our cursoradapter adapter = new quoteadapter(getactivity(), portfolio.getquotes()); listview list = (listview) view.findviewbyid(r.id.list); list.setadapter(adapter); adapter.notifydatasetchanged(); return view; } then have onactivitycreated doing u

php - Is unsetting is worth on large arrays? -

i working xml imports. xml files 6 mb max, loop through simplexml arrays , write appropriate records in database nothing difficult , no big worries performance or ram usage. 1 of xml files different. big 145 mb file 50k+ products. so have few questions: 1) better loop through file same way have done smaller files or product indexes small 3mb file , request other information form remote server 50k times? there no limit on product requests, concerned performance , ram usage here. my guess requests better idea, want hear more experienced people. 2) second question ram usage , performance. asked other programmer (i intern) , said need unset big array after these operations. truth? there ton of information insetting variables , arrays, not impact on hardware.. after doing research on question on own found using simplexml on large xml not best idea. xmlreader stream based xml parser looking for. here quite resource on topic in opinion: http://yashwanthbm.com/parsing-

python - Grid Detection with Scipy -

Image
i want identify points in image arranged in regular 4 x 5 grid: with dynamic thresholding , opening , closing, have labeled image: extracting centroids gives me set of points. want fit 4 x 5 grid image, , transform image make grid square , flat. can suggest how might go this? looked @ hough transform that's lines rather points. any suggestions appreciated.

memory management - C++ unique_ptr and observer pattern best practices -

i'm trying write correct c++11 application, , i'm faced problem of memory management observer design pattern. my emitter , listeners owned same class, stored in std::unique_ptr . code think write should this: class listener { emitter &myemitter; public: listener(emitter &emiter): myemitter(emitter) { myemitter.register(*this); } virtual ~listener() { myemitter.unregister(*this); } } class emitter { std::vector<listener*> mylisteners; public: void register(listener &listener) { mylisteners.push_back(&listener); } void unregister(listener &listener) { mylisteners.erase(std::remove(mylisteners.begin(), mylisteners.end(), &listener)); } } class owner { std::unique_ptr<listener> thelistener; std::unique_ptr<emitter> theemitter; } is correct approach ?

c# - Code to check 30 days trial for my application -

hi have developed application using c# , wish restrict use 30days , after 30 days user should not able use application.i got following code online. what code should add in elseif(days<30) restrict use #region using directives using system; using system.collections.generic; using system.linq; using system.text; using system.windows.forms; #endregion namespace coder24 { class trialtimemanager { /// <summary> /// temporary variable. /// </summary> private string temp = ""; /// <summary> /// constructor. /// </summary> public trialtimemanager() { } /// <summary> /// sets new date +31 days add trial. /// </summary> public void setnewdate() { datetime newdate = datetime.now.adddays(31); temp = newdate.tolongdatestring(); storedate(temp); } /// <summary

html - Floating label on top inputs -

i trying float label on top of input it's not working correctly? maybe messed css? appreciated, thanks! heres looks @ moment: http://prntscr.com/37hw30 html: <form id="loginformitem" name="loginformitem" method="post" style="float:right"> <label for="username">username</label> <input type="text" name="log_username" class="logintext" id="username" placeholder="username" style="margin-left:100px"> <label for="password">password</label> <input type="password" name="log_password" class="logintext" id="password" placeholder="password"> <button type="submit" class="loginbutton" name="login" >login now</button> </form> css: .logintext { margin-right: 10px; border: 2px soli

c# - Open Partial View on button click inside a modal asp.net mvc? -

function simpleajaxcall() { $.ajax({ url: "/account/register", success: function (result) { $("#modalsignupbody").html(result); $('#signup').modal({ backdrop: 'static', keyboard: true }, 'show'); } }); } button call: <button id="signupbtn" class="btn btn-warning" onclick="simpleajaxcall();">sign up</button> modal: <div class="modal fade" id="signin" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal&q

matlab - fwrite write the numbers in reverse Byte order -

i'm writing binary values file using fwrite function. problem when write numbers larger 1 byte, writes each byte in reverse order, examples: fwrite(fid,3,'int32'); writes file 03 00 00 00 instead of 00 00 00 03 . fwrite (fid,5076,'int32'); writes file d4 13 00 00 instead of 00 00 13 d4 . how make function write bytes in correct order? you should use machine format parameter , switch litle endian (x86 proccessor (intel amd default value suppose) big endian. look @ http://en.wikipedia.org/wiki/endianness understand endianess mean edit : in link give have put fwrite(fileid, a, precision, skip, machineformat) // replace machine format 'b' in case : fwrite(fid,3,'int32',0,'b');

javascript - Angularjs Date format not constistant on browsers? -

i have following code: app.filter('mydateformat',function mydateformat($filter){ return function(text){ var tempdate= new date(text.replace(/-/g,"/")); return $filter('date')(tempdate, "dd-mm-yyyy hh:mm:ss"); } }); which takes date database , puts correct format. here html: <li ng-repeat="rows in latestqs | limitto:12"> <a href="#pubres/{{ rows._id }}"> {{ rows.title }} </a> <br> <small>by {{ rows.group_name }} @ {{ rows._createdat | mydateformat }}</small> </li> this works fine on chrome, on ie9, displays as: nan-nan-nan-0nan nan:nan:nan where on chrome, its: 19-03-2014 14:00:19 any ideas how can round ? use momentjs in filter, best date library out there... app.filter('mydateformat',function mydateformat($filter){ return function(text){ var moment = moment(text); if(moment.isvalid) { v

ios - How to select row in FMDB? -

friends used fmdb , working well, tryed select single row gives me error this code fmresultset *fresult= [db executequery:@"select * contents id = 1"]; [fresult next]; nslog(@"%@",[fresult stringforcolumn:@"title"]); thank you you should check results. example: fmresultset *rs = [db executequery:@"select * contents id = 1"]; if (!rs) { nslog(@"%s: executequery failed: %@", __function__, [db lasterrormessage]); return; } if ([rs next]) { nsstring *title = [rs stringforcolumn:@"title"]; nslog(@"title = %@", title); } else { nslog(@"%s: no record found", __function__); } [rs close]; you flying blind if don't (a) check executequery return code; , (b) if failed, examine lasterrormessage know why didn't work.

Searching through the protocol buffer file -

i'm new protocol buffers , wondering whether possible search protocol buffers binary file , read data in structured format. example if message in .proto file has 4 fields serialize message , write multiple messages file , search particular field in file. if find field read message in same structured format written. possible protocol buffers ? if possible sample code or examples helpful. thank you you should treat protobuf library 1 serialization protocol, not all-in-one library supports complex operations (such querying, indexing, picking particular data). google has various libraries on top of open-sourced portion of protobuf so, not released open source, tied unique infrastructure. being said, want possible, yet need write code. anyhow, of requirements are: one file contains various serialized binaries. search particular field in each serialized binary , extract chunk. there several ways achieve them. the popular way serial read/write file contains series

java - Time and space complexity of this function to print binary tree level by level -

this algorithm printing common binary tree level level. what time complexity , space complexity of printspecificlevel_bt() , printbt_lbl() ? i think printspecificlevel_bt 's time complexity o(lg n) , , space complexity o(lg n) . think printbt_lbl() 's time complexity o((lgn)^2) , , space complexity o((lgn)^2) . is correct? // print specific level of binary tree. public static void printspecificlevel_bt (node root, int level) { if (root == null) return; if (level == 0) system.out.print(string.format("%-6d", root.data)); // base case. // recrusion. printspecificlevel_bt(root.leftch, level - 1); printspecificlevel_bt(root.rightch, level - 1); } // height of binary tree. public static int getheight_bt (node root) { if (root == null || (root.leftch == null && root.rightch == null)) return 0; // base case. return 1 + math.max (getheight_bt(root.leftch), getheight_bt(root.rightch)); } // print binary tree level level. publi

php - Hide Simple Social Buttons plugin output in custom post type -

Image
i'm working in custom post type , need hide output generated simple social buttons plugin. tried code: remove_filter('the_content', 'plugin_action_links', 100); in single-magazine_post_type.php below get_header() didn't work. advice? ps: exists plugin can work on without need touch code time? there function in simple social plugin called insert_buttons in simple-social-buttons/simple-social-buttons.php . function puts social buttons content. can make exception there like; function insert_buttons($content) { global $post; if ( !empty( $post ) ) { if ( get_post_type( $post ) == "your_post_type") { return $content; } } ...... } edit: how that? 1) open plugin editor in admin panel 2) select simple social buttons list 3) select buttons/simple-social-buttons.php list 4) update insert_buttons function mentioned above

javascript - Drop down menu not work -

i'm developing easy web application, , i'm using 2 js libraries: dat.gui , three.js. my problem drop down menu locked. can't open it. // gui initialization (dat.gui) function initgui() { var options = function() { this.tenda = 'bar'; }; config = new options(); var gui = new dat.gui(); var subgui = gui.addfolder('setting'); subgui.open(); // callbacks subgui.add( config, 'tenda', ['bar', 'pie', 'area']). onchange( function() { if (config.tenda === 'bar') { ... } else if (config.tenda === 'pie') { ... } else if (config.tenda === 'area') { ... } } ); }; reading on web, seems known issue, in examples, see drop down menus working well. i'm new js, , thought "maybe there scoping issue", put initialization process inside function work. problem remains. i&#

c# - ASP.net, Redirect fine on localhost, but won't redirect on webhost -

i facing strange problem. i trying navigate page after session timeout. it's working on localhost, it's able redirect choosen page. won't on webhost :/ anyone can help? here code: if (remainingtime >= 0) { displaysessiontimeout() } else { pagemethods.sendstatustodb(onsuccess); function onsuccess() { clearinterval(intervalhandle); window.location = "http://zaghilionheart.com/greenhousehomepage.aspx"; } }

java Error while running class -

this question has answer here: what “could not find or load main class” mean? 35 answers my directory structure this /models/beamcalculate.java /lib/*.jar ---------all jar files here. the beamcalculate.java -- package models; import com.fasterxml.jackson.databind.objectmapper; public class beamcalculate{ private double width; private double depth; private double m; private double mcap; public static void main(string args[]){ objectmapper = new objectmapper(); } } the thing gets compiled command -- javac -cp "lib/*" models/beamcalculate.java this generates beamcalculate.class file in models/ but when try run using command -- java -cp "lib/*" models/beamcalculate.class error - error: not find or load main class models.beamcalculate.class what causing this? you don't add .class suffix when r

html - level 2 DOM handling not working javascript -

hello i'm having trouble using level 2 dom handle events, i've looked around don't quite understand how works, , allways end doing simple code like: <element onclick = " code" > </element> instead of reaching element outside of html code, please help, know easy topic can't make work... there css code not relevant question here's code: <script type="text/javascript"> function rotate( xy , deegrees){ document.getelementbyid("cube").style.webkittransform = " rotate"+xy+"("+deegrees+"deg)"; } // supposed not working // whats wrong ? document.getelementbyid("upp").addeventlistener("click", rotate('x', 540), true); myfunction(); </script> </head> <body> document.getelementbyid('cube').style.webkittransform = 'rotatex(90deg)'; <div id="bu

struct - Scanf needs more values than it should in C -

i'm trying learn structs , i'm using code #include <stdio.h> struct elements { char name[50]; int semester; char am[15]; }student[100]; void read_struct(struct elements p[]); int i=0; main() { (i=0;i<2;i++) { read_struct(student); } (i=0;i<2;i++) { printf("%d\n",i); printf("%s\n",student[i].name); printf("%s\n",student[i].am); printf("%d\n",student[i].semester); } system("pause"); } void read_struct(struct elements p[]) { gets(student[i].name); gets(student[i].am); scanf("%d\n",&student[i].semester); } and face following problem: during second iteration when enter value variable student[1].semester program doesn't print i've entered waits me enter number,press enter , prints. tried fflush(stdin) after every gets , scanf, , got same problem. try replacing scanf("%d\n", &am

python - PyDev Package Explorer doesn't show files in Eclipse -

i have been working weeks using eclipse's pydev (eclipse 3.8.1) , click on files in package explorer navigate through them. of sudden python project looks empty in package explorer, showing standard python libs. i tried many things such as: refreshing project. importing again project workspace. looking @ custom filters in "customize view". opening project file in editor , using "link editor". closing pydev package explorer , opening again. closing , opening eclipse again (several times). none of showed files. don't know wrong project. think not related, git project. do know else missing me try? thanks. found solution in pydev faq the usual checks are: in pydev package explorer menu, top level elements pointing working sets? in pydev package explorer menu, customize view, content has both, pydev navigator content , resources checked? in pydev package explorer menu, customize view, possible filters selected hiding elements?

php session variable randomly changes -

i have website has membership system. when users log in, validate username/password database , start session, $_session['userid'] contains id (i have not implemented using cookies yet) i have problem, system works fine of times, users have reported find logged in other random users account. means $_session['userid'] changes without reason else , i'm pretty sure i'm not doing change it. any ideas why happening ? edit : summary of doing this method start session function startsession($id){ $_session['logged_in'] = 1; $_session['userid'] = $id; } this method checks login function isloggedin(){ return isset($_session['logged_in']) && isset($_session['userid']) && $_session['userid']!=" " && $_session['logged_in']==1; } this logout method function logout(){ $_session['logged_in'] = 0; $_session['userid'] = 0; unset($_session['lo

ios - FMDatabase: connect DB made in advance -

i made dbfile sample.db terminal in advance, , added file project. app create dbfile scratch, instead of refering db added. how need fix refer db added? nsarray* paths = nssearchpathfordirectoriesindomains( nsdocumentdirectory, nsuserdomainmask, yes ); nsstring* dir = [paths objectatindex:0]; fmdatabase* db = [fmdatabase databasewithpath:[dir stringbyappendingpathcomponent:samble.db]]; [db open]; check existence of database in documents folder before try open it, , if it's not there, copy version bundle documents folder before subsequently opening documents folder. so, first, because have blank database sitting in documents folder, remove (by uninstalling app , re-installing). , can following bool success; nsarray* paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring* dir = [paths objectatindex:0]; nsstring* documentspath = [dir stringbyappendingpathcomponent:@"samble.db"]; nsfilemanager* filemanager = [ns

r - Add text to ggplot with facetted densities -

Image
i'm encountering problem when trying make density plot ggplot. data bit in example here. require(ggplot2) require(plyr) mms <- data.frame(deliciousness = rnorm(100), type=sample(as.factor(c("peanut", "regular")), 100, replace=true), color=sample(as.factor(c("red", "green", "yellow", "brown")), 100, replace=true)) mms.cor <- ddply(.data=mms, .(type, color), summarize, n=paste("n =", length(deliciousness))) plot <- ggplot(data=mms, aes(x=deliciousness)) + geom_density() + facet_grid(type ~ color) + geom_text(data=mms.cor, aes(x=1.8, y=5, label=n), colour="black", inherit.aes=false, parse=false) labelling each facet labels work quite unless scales each facet vary. have idea how achieve putting labels @ same location when scales per facet differ? best, daniel something this? plot <- ggplot(data=mms, aes(x=deliciousness)) + geom_densit

c++ - How to create an point of arbitrary size in Qt's QGraphicsView? -

Image
i wish draw period or dot or point in graphicsview that: has arbitrary size, works radius of circle, is affected scaling transformations in position changed according current scale, but arbitrary size not affected scaling. the problem i'm tackling depicting celestial bodies in solar system visualizer. want make things proper distances each other, space unimaginably empty - trying depict earth-sized object proper radius make hard viewer see if said user zoomed out enough see other planets. therefore, mark locations dots don't scale in diameter, while else (like orbital paths, distances) scales. i have tried use itemignorestranformations, makes object ignore both size changes , location changes when scale altered. want object noticeable regardless of scale, @ same time in proper place. alternative solutions welcome. edit1: the new code looks so: ellipse2 = scene->addellipse(0, 0, body.radius,body.radius,blackpen,greenbrush); ellipse2->setflag(qgraphic

python - Loading greyscale images in wxPython -

i'm writing little desktop app using wxpython bit of image manipulation, i'm finding it's running rather slowly. one of biggest problems @ moment using 3 channels of data (rgb) need 1 - greyscale images fine purposes. at moment i'm manipulating images loading them numpy array. once processing done, they're converted wx image object (via imagefrombuffer() function, loaded staticbitmap user interface. seems lot of steps... so have 2 questions - first how load numpy array directly greyscale wx image? possible? the second more general - fastest way of dealing images in wxpython? don't have choice loop on numpy arrays (i need mathematical functionality), way of speeding things before , after process welcome! you pingpong pil :) def converttograyscale(img): import image, imageops orig = image.new("rgb", img.getsize()) orig.fromstring(img.getdata()) pil = imageops.grayscale(pil) ret = wx.emptyimage(pil.si

image - jquery, cannot add img in td -

the setup of html have alphabet imgs inside td. user should click imgs alphabetically, every correct click img removed. if wrong, xmark appear. (not yet in code: after 3 wrongs, it's game over, , ask user if wants play again or go home) this jquery code: var error = 0; var check = 0; $("table img").bind('click',function(){ var letterarray = new array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); var clickedvalue = $(this).attr('name'); if(clickedvalue ==letterarray[check]){ $(this).parent().empty(); check+=1; } else { error+=1;

java - Getting 0.0's returned from my object -

i have 3 classes, node, hiddenlayer, , inputnode class. my hiddenlayer , inputnode classes subclasses of node class , share output() method node class (polymorphism). my question is: why object returning 0's in hiddenlayer class? attached code: node.java public class node { protected double number; public double output(){ return number; } } hiddenlayer.java public class hiddenlayer extends node { protected node[] input; public hiddenlayer(node[] nodes) { this.input = nodes; } //some activation functions can called upon. class activationfunction { //sigmoid activation function public double sigmoid(double x) { return (1.0 / (1 + math.pow(math.e, -x))); } public double derivesigmoid(double d){ return d * (1.0 - d); } // hyperbolic tan activation function public double hypertanfunction(double x) { return (math.pow(math.e, x) -

c# - Cast Parent class to Child -

we have observablecollection<t> of 6 observablecollection list<parent> have different types of child classes. what use generic method retrieve objects have same type, in other words retrieve list contains <t> children. here source code classes , b child classes of parent. observablecollection<managertemplate> managerliststack = new observablecollection<managertemplate>(managertemplates); class managertemplate { public type _type { get; set; } public observablecollection<parents> parentlist {get;set;} } internal static list<managertemplate> managertemplates = new list<managertemplate>() { new managertemplate{ list= new observablecollection<parent>(),type=typeof(a)}, new managertemplate{ list= new observablecollection<parent>(),type=typeof(b)} }; public static list<t> get<t>() t : parent { /*(managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>()).tolist();

ajax - PHP: json_encode() SyntaxError if use of include_once() -

Image
remark: using xampp on php i'm using json_encode() return data js/jquery ajax request. the ajax call .js: $.ajax({url: "/sys/search_rf/functions.php" , async: false, // wait reponse type: "post", data: { id: $('#id').val(), status: $('#status').val(), token: ctoken } , success: function(jsonresponse,status){ // post success console.log(jsonresponse); jsondata = json.parse(jsonresponse); [...] } it works fine until require_once() .php in functions.php. require_once(dirname(dirname(__file__)).'/searches.php'); // -> ../searches.php output debug: none of included php echoes/print @ all, except function returns json_encode() . so then, edited searches.php , left (debugging purpose): <?php ?> so i'm 100% sure nothing echoing, , kept: require_once(dirname(dirname(__file__)).'/searches.php'); // -> ../searches.php in func

java - Compile error method constructor -

i have array list hand has stay private in class a. in class b, have method public string checkhand(arraylist<card> hand) line has stay way is. checkhand supposed check whether hand contains winning combinations , return string. when try compile class b, unfinished right now, error: gamepoker.java:40: cannot find symbol symbol : class arraylist location: class gamepoker public string checkhand(arraylist<card> hand) what might missing? thanks.

ruby on rails - NoMethodError in Clients#new -

so i'm getting error in 1 of views , seems have way client being initialized in controller, here's code client model , controller: model: class client < activerecord::base has_many :visits has_many :exchanges, through: :visits controller: class clientscontroller < applicationcontroller before_action :set_client, only: [:show, :edit, :update, :destroy] def index @clients = client.all end # /clients/new def new @client = client.new end # post /clients # post /clients.json def create @client = client.new(client_params) respond_to |format| if @client.save format.html { redirect_to @client, notice: 'client created.' } format.json { render action: 'show', status: :created, location: @client } else format.html { render action: 'new' } format.json { render json: @client.errors, status: :unproc

django - Error with GeoDjango serializer and ForeignKey field -

i have problem django 1.5.4 . put question in stackoverflow instead of https://gis.stackexchange.com/ because i'm 100% sure not gis related problem. here set up: my models.py from django.contrib.auth.models import user django.contrib.gis.db import models gismodels # this models region of interest, using polygon class roi(gismodels.model): label = models.charfield(max_length=256, default='roi') area = models.floatfield(default=0.0) geom = gismodels.polygonfield(srid=4326) when = models.datetimefield(default=datetime.now()) user = models.foreignkey(user, null=true) objects = gismodels.geomanager() def __unicode__(self): return unicode(self.label) class meta: ordering = ['when'] class indicator(models.model): name = models.textfield() color = models.textfield() measurement_units = models.charfield(max_length=100) algorithm = models.charfield(max_length=256) data_origin = models.textfie

c++ - How can I go to my previous Fl::window? -

ok, i'm making game using fltk. , have function prints splash screen subclass of fl::window made buttons "play" , "rules". when user clicks "rules", prints fl::window subclass "back" button , rules (obviously). problem first figure out how display original splash screen when user presses back. know can create second identical splash screen pops when button pressed, means user can go "rules" , "back" 1 time. prefer loop, user can press "rules"-->"back"-->"rules"-->"back" many times he/she like. make sense? ideas? normally each gui can represented nested state machine. if go screen ( state ) destroy actual displayed widget or window , create new one. if there button, brings "back" first state, same: destroy actual widget or screen , create first 1 again. simple or not :-) if go deeper hierarchy of sm, create new widget on existing 1 of higher state. le

java - Usability: How do I provide & easily deploy a (preferably node.js + MongoDB based) server backend for my users? -

i'm planing application (brainstorming, more or less), designed used in small organizations. app require syncronization w/ backend-server, e.g. user management , advanced, centralized functionality. server has hosted locally , should able run on linux, mac , windows. haven't decided how i'm going realize this, don't know smartest approach. technically speaking, interessting approach seemed node.js + mongoose, connecting local mongodb. i'm struggeling: how ensure it's easy , convienient organization's set up? installing node.js + mongodb tedious work , far standartized , easy. don't have ressources provide detailled walthrough every major os , configuration or take on setup myself. ideally, local administrator should run sort of setup on machine used server (a "regular" pc running 24/7 should suffice) , have system , running, similar way games provide executables hosting small game-servers couple friends (minecraft, instance). i though

java - How to pass ID to controller? -

i have form <form method="post" action="/user/${id}"> <input type="text" name="id" value="${id}" placeholder="input id"> <button>get user</button> </form> how pass id controller? @requestmapping (value = "/user/{id}", method = requestmethod.post) public string getstudent(@pathvariable ("id") integer id, model model){ user saveduser = userrepository.get(id); model.addattribute("user", saveduser); return "user"; } you way , consider passing ${id} value through query string <a href="user?id=${id}">get user</a> and in controller, @requestmapping ("user") public string getstudent(@requestparam integer id, model model){ user saveduser = userrepository.get(id); model.addattribute("user", saveduser); return "user";

Locally stored background image for django jumbotron -

the background image correctly displayed when enter url of external image (google in example): <div class="jumbotron" style="background-image: url(https://www.google.co.uk/logos/doodles/2014/cricket-t20-world-cup-2014-final-5735702968926208-hp.jpg); background-size: cover;"> but not when use image stored locally ( static/media/leaving.png ), neither <div class="jumbotron" style="background-image: {{media_root}}leaving.png; background-size: cover;"> nor <div class="jumbotron" style="background-image: url({{media_root}}leaving.png); background-size: cover;"> the settings.py contains media_root = os.path.join(os.path.dirname(base_dir), "static", "media") . how can display locally stored image in background? you shouldn't using media_root, contains local file path, media_url, contains url local media files. (actually, sure mean media rather static? former as

datetime - Date and time from hex -

i'm trying read public transport cards , i've figured out data format record dates , times mystery. data: e1 a2 00 00 ce 04 05 b1 7e 00 68 22 0a 10 00 ce - 01.03.2014 23:36 e4 a2 00 00 ce 04 e5 7b 7e 00 e4 2e 0a 10 00 e9 - 04.03.2014 16:31 e4 a2 00 00 4c 04 43 8c d0 07 30 00 01 00 00 72 - 04.03.2014 18:42 e4 a2 00 00 ce 04 65 8d 7e 00 7c 17 0a 10 00 a2 - 04.03.2014 18:51 ea a2 00 00 ce 04 25 63 7e 00 70 09 0a 10 00 f1 - 10.03.2014 13:13 ec a2 00 00 ce 04 25 63 7e 00 70 09 0a 10 00 da - 12.03.2014 13:13 f3 a2 00 00 ce 04 85 69 7e 00 64 3b 0a 10 00 9d - 19.03.2014 14:04 f5 a2 00 00 ce 04 e5 89 7e 00 70 22 0a 10 00 ba - 21.03.2014 18:23 f6 a2 00 00 ce 04 6a 00 82 01 68 22 2a 10 00 df - 22.03.2014 00:03 fb a2 00 00 ce 04 85 75 7e 00 84 17 0a 10 00 2a - 27.03.2014 15:40 fb a2 00 00 ce 04 a5 91 7e 00 78 17 0a 10 00 a6 - 27.03.2014 19:25 c1 a2 28 00 ce 04 0b 6b 00 00 74 17 08 10 04 94 - 28.01.2014 14:16 c7 a2 00 00 ce 04 a5 5d 7e 00 6c 09 0a 10 00 1b - 03.02.2014 12:29 c7 a2 00

actionscript 3 - How to make an On/Off Function -

when click in stage, anywhere, calls function change 1 variables value. how make when click again changes original value? public function example() { (...) modifier = 1; stage.addeventlistener(mouseevent.click, happening); } public function happening(event:event) { modifier = 4; } how keeping seperate boolean variable? var clicked:boolean = false; var modifier:int = 1; stage.addeventlistener(mouseevent.click, happening); public function happening(e:mouseevent):void{ if(clicked){ //return default modifier = 1; clicked = false; }else{ modifier = 4; clicked = true; } } or simpler if(modifier==4){ modifier=1; }else{ modifier=4; } or in 1 line modifier = (modifier==4) ? 1 : 4;

python - convert a list of objects to a list of a data member -

say have list of objects. object has data member 'name'. want sub list of objects have value of 'name'. elegant way beyond: class person(base): name = column(text) p1 = person(name="joe") p2 = person(name="jill") plst = [ p1, p2 ] name_test = "jill" found_people = list() person in plst: if person.name == name_test: found_people.append(person) looking elegant solution not verbose. not sure if python code compiles or not :) you use list comprehension . class person(base): name = column(text) plist = [person(name="joe"), person(name="jill")] found_people = [person person in plist if person.name == "jill"]

java - Moving to different servlet other than form action -

i having form : <form action="sendaddnotification" method="post"> <%string namee=rs.getstring(2);%> <input name="indusername" type="hidden" value="<%=namee%>"/> user name : <%=namee%> <br> first name : <%=rs.getstring(4)%> <br> last name : <%=rs.getstring(5)%> <br> email id : <%=rs.getstring(6)%> <br> contact : <%=rs.getstring(7)%> <br> <% string groupidd = request.getsession().getattribute("groupid").tostring(); s=null; rs=null; int flag=0; string sql="select * tbgroupusers i_id=? , gu_groupid=?"; s = con.preparestatement(sql); s.setstring(1,idperson); s.setstring(2,groupidd); rs=s.executequery(); if(rs.next()) flag=1; request.setattribute("flag", flag); %> <c:choose> <c:when test="${requestscope.flag == 1}">

c - An Error occured while compiling Linux Kernel 2.6 with a new System Call -

i added new system call in linux kernel 2.6.33 including essential user-side , kernel-side parts, while compiling got follwing error: arch/x86/built-in.o: in function `sys_call_table': (.rodata+0x724): undefined reference `sys_my_sys_call' make: *** [.tmp_vmlinux1] error 1 i tried change kernal version (2.6.32.21) error occurs. let's show simple code of "hello! world." syscall: #include <linux/kernel.h> asmlinkage long sys_hello(void) { printk("hello world\n"); return 0; }

php - Verify remote file exists with SplFileInfo -

i'm trying copy remote file server. before doing this, want test of file exists. following code not work, though have manually verified file exists on remote server. have php's allow_url_fopen set on. there missing? old procedural method file_exists() i'm looking replicate. //... $fileinfo = new \splfileinfo($imagelocation); if($fileinfo->isfile()) { echo "doesn't exist"; } else { echo "exists, copy file here"; } there no equivalent of file_exists() splfileinfo class. splfileinfo::isfile() different check, correlates is_file() function (they share underlying code). you call file_exists() function on $imagelocation , provided references stream wrapper supports stat() functionality. wrappers such file:// , phar:// , ftp:// (the latter partially) support this. unfortunately http:// (and https:// ) wrapper does not support stat() calls . means file_exists() , , other functions call stat()

how to provide starting directory for __import__ function in python 2.7.6 -

i have class configured configs. has file structure: -basemodel --model1 ---config --model2 ---config etc and inside model constructor read exact config depending input params __import__ i want add basemodel2(basemodel) inherited basemodel and file structure change that -basemodel -basemodel2 --basemodel2a ---config --basemodel2b ---config but problem when invoke basemodel2 constructor invokes basemodel constructor , __import__ function inside trying resolve config basemodel instead of basemodel2 so how directly specify start point __import__ function allow search in basemodel2 subdirs instead of basemodel's ? code simple basemodel.py: class basemodel(object): def __init__(): ... config = __import__(configname, locals(), globals(), [], -1) basemodel2.py: class basemodel2(basemodel): def __init__(): super(basemodel2, self).__init__(); the problem __import__ method invoked inside super() context resolving files under basemodel directory

Duplicate html with Javascript below the original element -

i able figure out how duplicate html javascript. however, can't figure out how duplicate html directly below original duplicated html. right going bottom of page. here html: <div id="duplicater"> duplicate inside div </div> <button id="button" onlick="duplicate()">click me</button> <div class="blank"> duplicated info should stay above this. </div> here javascript: document.getelementbyid('button').onclick = duplicate; var = 0; var original = document.getelementbyid('duplicater'); function duplicate() { var clone = original.clonenode(true); // "deep" clone clone.id = "duplicetor" + ++i; // there can 1 element id original.parentnode.appendchild(clone); } fiddle http://jsfiddle.net/kxmpy/803/ i'd suggest, in place of appendchild() , using insertbefore() : original.parentnode.insertbefore(clone, original.nextsibling); js

How to get the raw text from Opera's omnibox when the text is not a valid URI -

since opera no longer implements shortcut "/." visit slashdot.org, thought write extension replaces functionality. i have not written opera extension, hit docs. setting omnibox extension doesn't work, because requires user put space after keyword. as "/." isn't valid url, i'm not seeing obvious way intercept it. my issue boils down "how text before opera assumes user trying keyword search?" "/." valid url, not working in opera. bug should fixed soon. still have wait until user put space , start typing text omnibox. event oninputstarted earliest event can catch. tried chrome.omnibox.oninputstarted.addlistener(function () { chrome.tabs.create({url:"http://slashdot.org"}); }) and browser create tab after user type first letter.

python - Pythonic alternative to dict-style setter? -

people tend consider getters , setters un-pythonic, prefering use @property instead. i'm trying extend functionality of class uses @property support dict: class oldmyclass(object): @property def foo(self): return self._foo @foo.setter def foo(self, value): self.side_effect(value) self._foo = value class newmyclass(object): @property def foo(self, key): # invalid python return self._foo[key] @foo.setter def foo(self, key, value): # invalid python self.side_effect(key, value) self._foo[key] = value of course, create helper classes deal this, seems writing setter/getter functions take key , value simpler. there more pythonic way refactor? what describe not case properties. properties allowing obj (or rather, class) customize behavior of obj.prop = value . if want customize obj.prop[key] = value , need handle not in obj in obj.prop , means need make obj.prop custom class. want

ember.js - Emberjs Set CurrentUserController from LoginController -

i have currentuser objectcontroller : app.currentusercontroller = em.objectcontroller.extend({ username: 'test', email : 'test@test.com' }) when user logs in, want set currentuser's username, email etc: app.logincontroller = ember.controller.extend({ needs: 'currentuser', login: function(){ var self = this; var data = this.getproperties('username', 'password'); self.set('errormessage', null); $.ajax({ type: "post", url: url, mimetype: "text/xml", success: function(response){ app.currentuser.set('username', data.username); app.currentuser.set('email', data.email); self.transitiontoroute('home'); }, error: function(){ self.set('errormessage', true); } }); } }); i've tried above no luck. there no app.currentuser instance available. app.currentuser.set(&

vba - Best way of looping through all the protected areas in a document? -

what best way of looping through protected areas in document? (protected using 'protect document' feature in developer tab of ribbon.) i see there editor object, , has range property. 1 way loop through editor objects , @ ranges. isn't there more direct method? isn't there object or collection contains list of protected areas in document? (and each area (range) there name of person has access rights.)

c++ - Going from parsing/reading an entire text file to parsing/reading line by line -

i making basic interpreter (using own language) functions of set theory (union, intersection, etc.). i'm coding c++ , doing reading , parsing .txt file. however, i'm trying make code can executed in "command-by-command" way, without having command window close. i'm hoping able have multiple functions read , performed 1 after using carriage return. is there way can change parser keep accepting commands/function instead of reading entire .txt file @ 1 time? generally, when "parsing" something, idea read token @ time, , not care lines , other such things. if language structured way, read language stream, , when see call function (or whatever want call it), execute function go along [assuming don't compile machine code requires entire thing compiled @ once, of course - if that's case, you're in bit of work...] but if want read line @ time, use istream& getline(istream&, std::string&) method. reads single line. p

Warning in php with csv -

this code <?php ini_set("display_errors", true); $inputfilename = 'hw8.csv'; $outputfilename = 'hw8.xml'; // open csv read $inputfile = fopen($inputfilename, 'rt'); // headers of file $headers = fgetcsv($inputfile); // create new dom document pretty formatting $doc = new domdocument(); $doc->formatoutput = true; // add root node document $root = $doc->createelement('rows'); $root = $doc->appendchild($root); // loop through each row creating <row> node correct data while (($row = fgetcsv($inputfile)) !== false) { $container = $doc->createelement('row'); // $i array index (0,1,2,..) , $header value @ $i foreach ($headers $i => $header) { $child = $doc->createelement($header); $child = $container->appendchild($child); $value = $doc->createtextnode($row[$i]); $value = $child->appendchild($value); } $root->appendchild($container); } echo $doc->save

javascript - How to obtain instagram pictures from a place consuming instagram API? -

i gave instafeed.js . works right away, followed first docs , got 20 images sample displaying @ web page. however need obtain pictures place (city, in case). working twitter api used woeid wanted place. here seems quite similar. i read instagram docs : distance default 1000m (distance=1000), max distance 5000. facebook_places_id returns location mapped off of facebook places id. if used, foursquare id , lat, lng not required. foursquare_id returns location mapped off of foursquare v1 api location id. if used, not required use lat , lng. note method deprecated; should use new foursquare ids v2 of api. lat latitude of center search coordinate. if used, lng required. lng longitude of center search coordinate. if used, lat required. foursquare_v2_id returns location mapped off of foursquare v2 api location id. if used, not required use lat , lng. but hell can obtain such id's city. let's want pictures tagged dinner @ puebla, mexico. should do. i used nice