Posts

Showing posts from April, 2013

ruby on rails - Nested Querying in Mongoid in 2013 -

so question 2 years old: querying embedded objects in mongoid/rails 3 ("lower than", min operators , sorting) and way recommends query nested objects less or greater than: current_user.trips.where('start.time' => {'$gte' => time.now}).count simply doesn't work, returns 0 numerous queries have wrong. i've tried current_user.trips.where(:'start.time'.gte => time.now}).count which 0. none of these throw error. what correct syntax querying nested elements nowadays? seems fair bit of confusion on this. it works expect in environment. (mongoid 3.1.3) class user include mongoid::document embeds_many :trips end class trip include mongoid::document embeds_one :start embedded_in :user end class start include mongoid::document field :time, type: datetime embedded_in :trip end user.create({ trips: [ trip.new({ start: start.new({ time: 5.days.ago }) }), trip.new({ start: start.new({ time: 2.days.f

java - Passing/storing info from a class? -

i'm beginner java , i'm making simple text rpg , want store character information in class such name, job, age, etc. example: class mychar { string name = ""; string job = ""; int age = 0; //set, get, etc... } and want user able asked name, job, etc. , pass class can pulled later on. understand how ints quite well, example have stats class hp, attack power, etc. stored: class stats // demonstrates class { int hp = 10; //set, get, etc... public int hit() // player hit { hp --; return hp; } } so see have small grasp on i'm not quite sure how player can enter information , have stored. understand usage: stats mystats = new stats("john", "warrior", 30); when comes identifying info, not how let player choose themselves. i'm sorry if sound vague, i'll update post needed! edit: have main public class contains different "rooms" , such. it's pretty leng

matlab - Using the if statement and for loop to write a program that generates N random numbers (and more) -

the question: write matlab program that i) generates n<=20 random numbers in interval [a,b], n, a, b entered via keyboard my attempt: a = input ('a=') b = input ('b=') n = input ('n=') n = (1:n) r = rand([a,b],[1,n]) end doesn't seem work. following error messages appear "??? subscript indices must either real positive integers or logicals." what doing wrong? ii) write numbers vector/array x no idea how this? matter of putting r = x? iii) write numbers divisible k screen, k entered via keyboard. my attempt: k = input ('k=') t = mod(x,k); x = i:n if mod(x,k) == 0 disp t end end am anywhere near correct? [i've never used stack-overflow before- having trouble formatting things appropriately] sorry get n random numbers in range [a, b]: a = input('a='); b = input('b='); n = input('n='); % floating point: r1 = + (b-a)*rand(1, n); % integers: r2 = round(

mysql - Update Query when username changes -

here query i'm trying. please don't laugh i'm clueless, lol. update toondb set tusername = (select username user userid='1') (select username user userid='1') != (select tusername toondb tuserid= '1') i whipped up, hoping it'd work. let me try explain, please. i have 1 table called 'toondb'. toondb has different columns. in particular case, focusing on 'tusername' , 'tuserid' column in table. 'tusername' column contains user's username, , 'tuserid' column contains user's userid. when submit info via form, 'tusername' , 'tuserid' columns automatically populated username , userid on forum. now, other table, 'user', info comes from. there column 'userid' , 'username' in 'user' table. userid 1 , username whatever so.. have row in 'toondb' table myself. userid set 1 row (as userid never changes). however, username set 'admi

Entity Framework Code First Automatic Migrations to Azure Database -

i'm using ef 5.0 code first , testing automatic migrations. works fine when i'm working locally when upload database azure , change connection string accordingly migration fails work. i'm using migratedatabasetolatestversion initializer. azure doesn't allow? i'm not getting error. no migration. ideas? try doing on website trigger call db. i had problem, until realized migrations weren't run until did on website triggered call db -- e.g. attempt log in. migrations run then.

alloy - Adding an removing relation between state -

i have alloy model module test sig b {} sig { c: b, delta: c lone -> lone c } pred operationa[disj x, x': a, c1, c2: b]{ x'.delta = x.delta + (c1->c2) x'.delta = x'.delta - (c1->c2) x'.c = x.c } run operationa 10 2 this not generate me instance. adding relation c1->c2 in x' state , removing again, reason not allow me that. the alloy language declarative, meaning write specification of what has happen in end , not how make happen (which imperative approach). therefore, body of operationa predicate interpreted conjunction of 3 lines wrote there, , not sequence of operations performed. more concretely, line x'.delta = x'.delta - (c1->c2) says content of x'.delta relation at same time equal x'.delta - c1->c2 . on it's own, line satisfiable if , if x'.delta not contain tuple c1->c2 (because - operator set difference, , if try remove set that's not in there, result same set). however

css - div height overstretching when image is appended -

i'm having problem nested divs , height. what want accomplish image's parent's height stretch fit image. happening parent overstretching , height bigger image. you can check code working here: http://jsfiddle.net/83ke6/ html <div class="select_box"> <div class="selected"> <img src="http://awardwallet.com/images/fbsmalllogo.png" /> </div> </div> css .select_box { display:inline-block; height:50px; border:1px solid blue; } .selected { border:1px solid gray; } img { border:1px solid red; } so on case, .selected should equal img height, 5px heigher; help by default img inline element , therefore reserves space under lines in paragraph. add display: block; image remove spacing. fiddle: http://jsfiddle.net/83ke6/3/

asp.net - How can I assign an href to be embedded within a tag? -

an href's target attribute can set display on separate page assigning "_blank" it; e.g., in site www.duckbilledplatypirus.org , link site way: <a href="http://www.bigsurgarrapata.com" target="_blank">garrapata</a> if leave target attribution out, href'd site replaces existing site on browser's current page. but want have page/site display, not in user's browser per se, embedded within site, in 1 of tags; in case, inside contents of accordion "fold." tried work way: <div id="accordion"> <h3>garrapata</h3> <div id="garrapatafold"><a href="http://www.bigsurgarrapata.com" target="#garrapatafold">big sur garrapata site</a></div> iow, it's targeting itself; doesn't work; acts if had assigned "_blank" href's target attribute. so going wrong, or close don't know value assign target attribute?

Ini file read and write + add new property + matlab -

this question has answer here: property_value + matlab 1 answer how read , write ini files: want add new property existing one. want write ini file temp file , add new property it. new property have head,name,desc, value , layout (like: line 1 & 3) #--------------- # head # -------------- [name]% type # desc value filedata = []; fh = fopen( filename, 'r' ); % read handle tname=tempname(); wfh =fopen(tname,'w'); % write handle line = fgetl(fh); val = ''; prop =''; type = ''; header = ''; desc= ''; while ischar(line) if strcmpi(line(1),'#') && strcmpi(line(3),'=') layout = line(2:end); elseif strcmpi(line(1),'#')&& ~strcmpi(line(3),'=') header = line(2:end); else prop = regexp(line,{'\[*\w+\]\s*%\s*.*\s*

swing - SimpleGUIApplication in scala 2.10.1 -

i'm reading programming in scala , there example gui program, extends class simpleguiapplication . don't see in scala library.i think it's removed 2.10.1. what replacement simpleguiapplication in scala 2.10.1 ? ok, i've found answer in doc : @deprecated since version 2.8.0 use simpleswingapplication instead

Rails - how to use request referrer to limit access to a view based on referrer -

i've been looking around can't seem find solution i'm trying do. i have 'thankyou' view routed custom controller action. want restrict access view case user came view user submitted form since don't want users able navigate directly view. how write controller code accomplish in custom controller action? in controller can do: def thankyou if request.referrer != "http://mysite.com/myformpage" redirect_to root_path, notice: "invalid access" end end or can create before_filter action same logic

osx - Running Applescript from Excel 2011 VBA -

mac os x, excel 2011 vba question: trying run bash shell excel 2011 macro. command executes mac os x lion 10.7.5 terminal. executes correctly using applescript command line: osascript -e 'do shell script "/users/myfolder/desktop/myshell"' i can execute ./test.sh, test.sh executable (chmod +x test.sh) file including lines #!/bin/bash osascript -e 'do shell script "/users/myfolder/desktop/myshell"' from excel, able execute similar test.sh file #!/bin/bash open /applications/calculator.app/ using excel vba function code function testshell() double shell activeworkbook.path & ":test.sh" testshell = 0 end function however, when switch test.sh file have desired content (the applescript command uses osascript above), fails. 1 further aspect of pathology if erase test.sh file, replace it, on first run put window saying 'this file internet. still want run it?'. in case, after clicking ok code appears run, doe

generate file using msxsl.exe using csv file -

previously using excel file genrate .xml file manually using export open excel file , use same file .xml file genearte file using msxsl.exe like msxsl.exe exported.xml file.xsl -o outputfile now want automate genration of exported.xml file instead of doing manually. 1 suggest me replace excel file .csv file , reduce effort. able use csv file , dont know how generate exported.xml file csv file automatically excel file too. can suggest me quick way same? thanks & regards vikas so data in excel file, you've been exporting xml data , transforming using stylesheet created different xml format. , want automate above. probably easiest way write vbscript both of above steps. here how save csv. save xml, use xlxmlspreadsheet=46 instead of xlcsv=6. use exec call msxsl.exe, or use transformnode apply stylesheet directly.

html - Relative Positioning not working on a Table Row. -

i have installed , using ie10 , chrome. , i'd fixed top header <tr> in <table> . below style tag dose not working!! <tr style="position:relative;top:expression(this.offsetparent.scrolltop);"></tr> do have experience? if these bug, want solution solve problem. plz me! create http://fiddle.jshell.net/ so can understand code.

How to update existing merged Excel cells with Apache poi -

i can't update existing excel cells these merged , borderd. created excel file styling , use template. @ code-> firstly read excel file , update cells wish. no merge cells ok . merged cells can't insert datas. it may produce damage excel file or empty data cells. don't want overwrite merged , bordered of existing cells. here code reading , updating.. hashmap<string, bytearrayoutputstream> streams = new hashmap<string, bytearrayoutputstream>(); try { string appdir = system.getproperty("appdir"); string resoucedir = appdir + system.getproperty("resourcedir"); string templatedir = resoucedir + "/template"; if (streams.keyset().size() <= 0) { xssfsheet sheet = null; fileinputstream file = new fileinputstream(new file(templatedir +"/shipping_template.xlsx")); xssfworkbook workbook = new xssfworkbook(file); bytearrayoutputstream baos = null; sheet = workbook.

visual studio 2010 - ASP.NET MVC 3.0 GridView -

i need use gridview in asp.net mvc 3.0. can post video tutorials on how use gridview in asp.net mvc 3.0 / video tutorials suggesting on how implement third party tools using gridview ? it should include features such paging , sorting etc. thanks, mangesh if you're referring gridview in gridview control in webforms , there nothing that. need roll own implementation. typically you'll bind view model (which has data fetched), loop through , generate html, here example tutorial . asp.net mvc more "close metal".

vb.net - TIDYCom Deletes the missing tags during cleanup? -

html tidycom removes unclosed tags during cleanup? eg: tag missing closing wiped off when compared source file .so can 1 let me know how can retained. following code snippet using program. dim tid new tidyobject() tid.options.doctype = "strict" tid.options.outputxml = true tid.options.addxmldecl = true tid.options.clean = false tid.options.dropemptyparas = true tid.options.dropfonttags = false tid.options.charencoding = charencoding.utf8 tid.options.quoteampersand = true tid.options.quotemarks = false tid.options.quotenbsp = true tid.options.tidymark = false tid.options.logicalemphasis = true tid.options.breakbeforebr = false tid.options.fixbackslash = true tid.options.fixbadcomments = true tid.options.wrap = true tid.options.uppercaseattributes = false tid.options.uppercasetags = false tid.options.indent = true tid.options.indentspaces = 4 tid.options.indentattributes = true

selenium webdriver - How to select element from options populated -

i need write script selenium-webdriver. stuck in situation need enter text (e.g : "tt" ) in textbox , list gets populated (hidden values). need select option populated list. (like in "google" search). <div class="select2-search"> <input type="text" autocomplete="off" class="select2-input tabindex="-1" style> </div> <ul class="select2-results"> <li class="select2-results-dept-0 select2-result select2-result-selectable select2-new"> <div class="select2-result-label"> <span class="select2-match">et</span> </div> </li> <li class="select2-results-dept-0 select2-result select2-result-selectable select2-highlighted"> <div class="select2-result-label">"secr" <span class="select2-match">et</span>"ary" </div> </li> <ul>

Why do I get Link of class failed importing a jar into an Android project in Eclipse? -

in eclipse wrote package of classes use android , tested them in android project, keeping test code in second package. used command line create jar file casses in project's bin/classes directory (just library package, not test package).running "jar tf" shows classes correctly prefixed package name. i created android project activity imported first package , used methods, this: import uk.me.stevewaring.nestedsettings.nestedsettingscommon; import uk.me.stevewaring.nestedsettings.nestedsettingsreformat; public class shownestedsettings extends activity implements nestedsettingsreformat {... i right clicked on new project , used build path add jar. jar shows @ top of java build path under libraries, , @ bottom under order , export. once added jar, red squiggly lines lint complaining methods in package vanished. however when try debug project, in logcat get: 04-27 05:45:44.180: i/dalvikvm(14576): failed resolving lcom/example/shownestedsettings/shownestedsettin

jquery - How to delete the dynamically created image in the following code? -

this dynamically create image: function handlefileselect(evt) { var files = evt.target.files; // filelist object // loop through filelist , render image files thumbnails. (var = 0, f; f = files[i]; i++) { // process image files. if (!f.type.match('image.*')) { continue; } filenames.push(f.name); var reader = new filereader(); // closure capture file information. reader.onload = (function(thefile) { return function(e) { // render thumbnail. var span = document.createelement('span'); span.innerhtml = ['<img class="thumb" id="',escape(thefile.name),'" src="',e.target.result, '&q

countdown - Jquery Count down Serversync issue -

hi trying use countdown serversync, there couple of questions related none of them giving clear solution my timer callback server c# code below public jsonresult getcurrentdatetime() { var date = datetime.utcnow; return json(data: date); } output is: thu may 23 2013 10:23:00 gmt+0100(gmt daylight time) and countdown calling script code below: <script type="text/javascript"> function servertime() { var stime; $.ajax({ type: "post", url: "/auction/getcurrentdatetime", contenttype: "application/json; charset=utf-8", datatype: "json", data: "{}", async: false, success: function (msg) { stime = new date(parseint(msg.replace(/(^.*\()|([+-].*$)/g, ''))); }, error: function (msg)

arrays - `KFAS`: how to fit time-varying variance in `regSSM` function -

please, consider following example kfas package: install.packages('kfas') require(kfas) # drivers model <- structssm(y = log(seatbelts[,"drivers"]), trend = "level", seasonal = "time", x = cbind(log(seatbelts[,"kms"]), log(seatbelts[,"petrolprice"]), seatbelts[,c("law")])) fit <- fitssm(inits = rep(-1,3), model = model) out <- kfs(fit$model, smoothing = "state") str(out) you can see out$model$h single value, model not time-varying in variance of disturbance terms. see arguments of regssm typing: ?regssm regssm says can make h argument time-varying: ... h p * p covariance matrix (or p * p * n array in of time-varying case ) of disturbance terms epsilon [ t ] of observation equation. default gives p * p 0 matrix. ... could show me how may fit time-varying covariance state-space model using regssm

How To Make Twitter Typeahead Exact Match Words and Phrases -

twitters typeahead matches word anywhere in phrase search "car" results can come phrase second word matches "car". instance when searching car in list business card. business card appears , worse appears before car. ie: search term: car suggestions: business card car car pool carbon i want more google , twitter (they never suggest isn't matching typed beginning) typed word relevant, car more relevant when typing car business card. i want stop matching second word until types space , starts second word. in above example business card not appear in list unless typed: business c how can stop behavior of matching , suggesting words aren't exact match start of typed search. another way how stop typeahead tokenizing or splitting on space. typeahead matches start of word (^), if space wasn't recognized word boundary work more google , twitters users expect. thanks help, tyler update 1. i updated dataset return datum has value , token

Liferay - Eclipse alloy tag library error -

i developing portlet runs on liferay portal (i have liferay+tomcat7 bundle, later run on jboss). using eclipse helios liferay ide , liferay sdk. in .jsp files, use alloy : <%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %> everything works fine - portlet gets deployed , shown correctly. problem is, eclipse marking error: description resource path location type can not find tag library descriptor "http://liferay.com/tld/aui" edit.jsp /portletvisual-portlet/docroot line 2 jsp problem this cosmetic error. liferay ide in eclipse evidently doesnt understand these dependencies, although project works fine. can live "error marker", doesnt bother me much. curious if there way fix it. thanks tips! edit: web.xml file: <?xml version="1.0" encoding="utf-8"?> <web-app id="webapp_id" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi=&quo

c# how to retrive objects as values from array -

i trying create simple 'inventory' system stores items key being items name, , remaining information being stored value. however, having difficulty figuring out how read information. example, if have list of 10 items, , want select items 'type' information key 'television' outlined below, how this? television {large, 5, 3, false, dynamic, 0.8, 20} hashtable myitems = new hashtable(); protected virtual bool onattempt_additem(object args) { object[] arr = (object[])args; string itemtype = (string)arr[0]; string itemname = (string)arr[1]; int itemamount = (arr.length == 2) ? (int)arr[2] : 1; int itemacanhave = (arr.length == 3) ? (int)arr[3] : 1; bool itemclear = (bool)arr[4]; string itemeffect = (string)arr[5]; float itemmodifier = (float)arr[6]; int itemweight = (int)arr[7]; // enforce ability have atleast 1 item of each type

javascript - Jquery Selector to get value of text area -

i want take values of multiple textarea , display them tool tip of highcharts graph.i used input , eq selector values of multiple text areas values not getting returned tooltip.. html code.. <div id="dialog" title="input data"> <form id="pform" > <!--name: <input type="text" name="name" width='50' height='100' maxlength="10" placeholder="fill in data" /><br><br>--> <label for="txt1">data 1:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <textarea id="txt1"rows="2" cols="10" name="ar2" maxlength="20" style="resize:none" placeholder="data 1"></textarea><br><br> <label for="txt2">data 2:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp

Bootstrap number validation -

i'm having bootstrap , have problem validation. need input positive integer. how implement it? for example: <div> <input type="number" id="replynumber" data-bind="value:replynumber" /> </div> it's not twitter bootstrap specific, normal html5 component , can specify range min , max attributes (in case first attribute). example: <div> <input type="number" id="replynumber" min="0" data-bind="value:replynumber" /> </div> i'm not sure if integers allowed default in control or not, else can specify step attribute: <div> <input type="number" id="replynumber" min="0" step="1" data-bind="value:replynumber" /> </div> now numbers higher (and equal to) 0 can used , there step of 1, means values 0, 1, 2,

Error 400 (Bad Request) when get a file which name contains & character in C# ASP.NET MVC3 -

i have issue regarding filename contains & character. i have image name is: test&testagain.jpg . in asp.net mvc3 application, in view side, put url.content( "~/content/images/"+ filename ); in chrome, see error 400 bad request because of filename contains & . i think & used query string , browser interprets file name query string. because filename doesn't contain ? browser throw error. ( a potentially dangerous request.path value detected client (&). ) it way (workaround) fix without replace character ? you need urlencode path: url.content("~/content/images/" + httpserverutility.urlencode(filename)); edit: seems doesn't work. way can think of right allow resticted characters , enable verificationcompatibility setting in registry: // 32-bit iis hklm\software\microsoft\asp.net verificationcompatibility = 1 // 64-bit iis hklm\software\wow6432node\microsoft\asp.net verificationcompatibility = 1

android - How to find how commonly is an English word used? -

i have following problem. i writing android application uses english dictionary, educational app, submits english language related test user. i have following problem: in order assess difficulty of tests application produces, i need have approximation of how commonly english word used. i need high level approximation, reasonable source acceptable. the problem have every word in dictionary (sqlite database) contains 95000 words . interesting problem, isn't it? please suggestion more welcome! edit edit edit i thinking doing google queries via code , use results have approximation. point doubt google allow code 95000 automatic queries... use frequency list (pdf) of english. words low frequency or not in list not common .

objective c - How to switch to a full screen window when [fullscreenWindow makeKeyAndOrderFront:nil] seems not to work? -

i have 2 windows in applications: window1 , window2. window2 created after window1 per user's action. when window2 in full screen mode, belong separate space default different space of window1. app supports launched url , singleton. the problem when app running , window2 in fullscreen mode: try launch app via url , window2's title specified in url, in app, though [window2 makekeyandorderfront:nil] is called, window2 won't become front, instead, window1 becomes front , activated. if window2 not in full screen mode, there no problem same scenario.(window2 brought front most.) how can make app switch fullscreen space , make window2 become front when in full screen mode , makekeyandorderfront seems not work expected? i tried [window2 setcollectionbehavior: nswindowcollectionbehaviormovetoactivespace] , the result not want. the app did not switch fullscreen space, still in window1's space. , on right side of menubar, there no fullscreen toggle b

java - How to stop ActiveMQ 's 'Queue' to stop receiving messages -

is possible stop specific queue of activemq after has consumed 100 messages 5sec , after 5sec again restart , start receiving messages ? activemq has flow control on memory constraints. try using router software that, such apache camel throttler i'm not sure can ask out of box similar things. or can add want logic. note camel bundled in activemq distributions. then setup 1 "from" queue application writes messages , route though activemq 1 "to" queue consumer reads messages.

cakephp - HTMLHelper link() added unintended path -

i believe simple question. maybe that's why can't find on google. when inside view/product/view.ctp echo $this->html->link('download pdf', 'app/files/product/1/manual.pdf'); the resulting url this: app/products/app/files/product/1/manual.pdf it automatically added app/products since inside product's view. how nullify automatic addition? thanks you're specifying relative url, causing browser append url current url. echo $this->html->link('download pdf', '/app/files/product/1/manual.pdf'); (note leading slash / ) should result in link http://example.com/app/files/product/1/manual.pdf

ios6 - iOS 6 OpenGL ES 2.0 video memory leak in a render buffer object -

below example code behaves 1 leaking video memory on ipad 2 ios 6.1 (basically creates render buffer object, allocates memory , destroys after drawing): if put draw loop see lots of memory warnings , application killed os. instruments give no hints , cannot see memory size growth, memory warnings. i understand creating buffers in draw loop bad idea, buffer needs recreated anyway in case if user rotates device , resolution changes leak remain need more time kill app (also looks springboard restarts when application killed). so example below way reproduce problem hidden, think. glad here ideas on what's wrong here , how leak can fixed. there several things tried (see commented code) nothing helped. thing helps commenting of glclear , gldrawarrays calls. looks gpu doesn't touch render buffer in case , problem disappears, need clear buffer , draw (the reason why need buffer next: i try implement multi-sampled rendering texture, works in fact, leaks memory). check gl

wxwidgets - Running ride.py shows error "wxPython with ansi encoding is not supported" -

when executing file called ride.py , following error message: wxpython ansi encoding not supported need install wxpython 2.8 toolkit unicode support run ride. see http://wxpython.org more information. configuration: my os centos6 python version 2.7 wxwidget version 2.8.12 ride version robotframework-ride-1.1 robotframework version 2.7.7 it looks ride doesn't support ansi mode. xw.platforminfo includes "ansi" below. >>> print wx.platforminfo ('__wxgtk__', 'wxgtk', 'ansi', 'gtk2', 'wx-assertions-off', 'swig-1.3.29') but wxpython, source, compiled on os. don't know how set "ansi" mode. compile steps noted below: $../configure --prefix=/opt/wx/2.8 \ --with-gtk \ --with-gnomeprint \ --with-opengl \ --enable-debug \ --enable-debug_gdb \ --enable-geometry \ --enable-graphics_ctx \

javascript - How do I provide my own insert link dialog in pagedown editor? -

i use pagedown markdown editing , used insertimagedialog overriding default dialog inserting images. want same insert link. found plainlinktext hook, not seem do, want, since post processing url. how can provide own dialog inserting link? var editor = new markdown.editor(converter, '', options); editor.hooks.set("insertimagedialog", function (callback) { //show dialog //example: //showprompt({ // message: 'input url', // onok: function(url){ callback(url); } //}); return true; });

what does the following type casting do in C? -

i have question type casting in c: void *buffer; (int *)((int)buffer); what type casting doing? , ((int)buffer) doing? imagine on linux/x86-64 computer mine. pointers 64 bits , int 32 bits wide. so, buffer variable has been initialized location; perhaps 0x7fff4ec52020 (which address of local variable, perhaps inside main ). the cast (int)buffer gives int, least significant 32 bits, i.e. 0x4ec52020 you casting again (int*)((int)buffer) , gives bogus address 0x000000004ec52020 not point valid memory. if dereference bogus pointer, you'll sigsegv. so on machines (notably mine) (int *)((int)buffer) not same (int*)buffer ; fortunately, statement , (int *)((int)buffer); has no visible side effect , optimized (by "removing" it) compiler (if ask optimize). so such code huge mistake (could become undefined behavior , e.g. if dereference pointer). if original coder intended weird semantics described here, should add comment (and such code unporta

c++ - Set an image as background in Open GL -

Image
i want achieve following result in opengl (and c++): have plot want use background of animation , want fix when points move on surface. example (see image): want calculate level plot of 3 variables function (black , white in photo), want set background , show animation of points moving on surface (red points in photo). best method achieve , have performances? one possibility draw background image texture on quad behind other points (e.g., points @ z=0.1, quad @ z=0.2). since (presumably) don't want quad scaled compared points, want use orthographic projection, not perspective.

java - Using dbpedia spotlight with a local mediawiki (not instance of wikipedia) -

i'm trying use dbpedia spotlight spot special terms (which not included in dbpedia) using local mediawiki dump input instead of default index , spotter.dict. ideas appreciated dbpedia spotlight requires 5(five) files build index follows: format n triples : instance types: list of urls , types (dbpedia, freebase etc) e.g: <your_link> <www.w3.org/1999/02/22-rdf-syntax-ns#type> <dbpedia:type> . labels: list of urls , labels e.g: <your_link> <www.w3.org/2000/01/rdf-schema#label> "label"@en . redirects: list of urls , redirect pages e.g: <your_link> <dbpedia.org/ontology/wikipageredirects> <your_link> . disambiguations list of urls , disambiguations pages . xml dump: wiki dump - (like wikipedia dump). after preparing these files own data, "just" follow internationalization guide available in dbpedia spotlight wiki create index own data. all best,

c# - How make arrays of delegates and use this array? -

i have write class eve make code below: class mainclass { int sum = 5; public void add (int x) { sum += x; } public static void write (int x) { console.writeline("x = " + x); } public static void main (string[] args) { eve p = new eve(); mainclass m = new mainclass(); p.registrate(m.add); p.registrate(write); p.registrate (delegate (int x) { system.console.writeline(" have {0} ", x); }); p.registrate (x => system.console.writeline (" square : {0} ", x * x)); p.run(10); p.run(5); console.writeline(" sum {0} ", m.sum); } } output: x = 10 i have 10 square : 100 x = 5 i have 5 square : 25 sum 20 so think have use delegates. , method registarte should add delegate array of delegates. i wrote code dint sure wright. public class eve { int i;

iphone - got stuck converting MySql output in JSON array with php -

i making iphone app. part of app allows users search company on location. i have mysql database containing companies can searched for, , php file on website receive searched data, , return companyname , companylocation found companies app. looks this: <?php if (isset($_get["companycitysearchfield"])){ $companycity = $_get["companycitysearchfield"]; $result = search($companycity); echo $result; } function makesqlconnection() { $db_hostname = "******"; $db_name = "*******"; $db_user = "*******"; $db_pass = "*******"; $con = mysql_connect($db_hostname,$db_user,$db_pass) or die(mysql_error()); mysql_select_db($db_name,$con) or die(mysql_error()); return $con; } function disconnectsqlconnection($con) { mysql_close($con); } function search($companycity) { $con = makesqlconnection(); $query = mysql_query("select companyname, comp

java - JList is not updating correctly when action listner is a thread -

i have button actionlistener thread. within thread's run method try update jlist setlistdata() method , not update. worked combobox not jlist. tried doing in invokelater thread didn't work. class main{ jbutton btn = new jbutton(); jlist jlist = new jlist(); btn.addactionlistern(new actionlistener(){ actionperformed(actionevent e){ new itthread().start(); } }); class itthread extends thread{ run(){ string [] data = new string[2]; data[0] = "it" data[1] ="itd"; jlist.setlistdata(data); } } }

html - Simple Nav Issue involving jQuery's .show() function -

hi have mini nav how make example if click on #hog , #cat (#green) showing show #red (#hog) if click on #hog , #red showing hide #red, sorry don't know how explain better hope understand mean, sorry :-) <!doctype html> <html lang="en"> <head> <title>toggle</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <h1>hog</h1> <div id="container"> <div id="menu"> <div id="hog"></div> <div id="dog"></div> <div id="cat"></div> <div id="red"></div> <div id="blue"></div> <div id="green"></div> </div> </div> <script src="jquery-1.8.3.js"></script> <scr

javascript - Jquery Validate addMethod "notEqual" causes browser crash -

i using: jquery.validator.addmethod("notequal", function(value, element, param) { return this.optional(element) || value !== param; }, "please specify different (non-default) value" ); then: $(this).validate({ rules: { address: { notequal: "address" }, building: { notequal: "building"} }, submithandler: function() { $(this).submit(); } }); to make fields not equal default values, causes browsers slow, or crash in case of webkit engines. jquery javascript library v1.8.3 jquery validation plug-in pre-1.5.2 can please tell me what's wrong? update: tried replace validation plug-in to: jquery validation plugin - v1.11.1, still same result. working sample: http://jsfiddle.net/avy9e/ you're calling submit event recursively submithandler option. instead, call native submit function on form element: $(this).validate({ rules: { address: { n

javascript - socket.io web client not working -

i met socket world socket.io , node.js found server example online: https://gist.github.com/creationix/707146 created first client on ios , receive , dispatch messages, same telnet client, next create second client socket.io receive messages on browser too. i tried example in howto: http://socket.io/#how-to-use these examples client not recognized! where wrong? start? the server code: // load tcp library net = require('net'); // keep track of chat clients var clients = []; // start tcp server net.createserver(function (socket) { // identify client socket.name = socket.remoteaddress + ":" + socket.remoteport // put new client in list clients.push(socket); // send nice welcome message , announce socket.write("welcome " + socket.name + "\n"); broadcast(socket.name + " joined chat\n", socket); // handle incoming messages clients. socket.on('data', function (data) { broadcast(socket.name + "> " + data,

asp.net mvc - Entity version in odata using accept header in web api -

i using web api create restful services. decided using accept header api versioning mechanism following implementation. http://blog.maartenballiauw.be/post/2013/03/08/custom-media-types-for-aspnet-web-api-versioning.aspx accept: application/json; version=1 for entity standardization , query capabilities, planned use odata. problem see odata supports(or know) entity versioning using url. modelbuilder1.entityset<v1.product>("products"); modelbuilder2.entityset<v2.product>("products"); microsoft.data.edm.iedmmodel model1 = modelbuilder1.getedmmodel(); microsoft.data.edm.iedmmodel model2 = modelbuilder2.getedmmodel(); config.routes.mapodataroute("odataroute1", "api\v1", model1); config.routes.mapodataroute("odataroute2", "api\v2", model2); is there solution available configure odata consider accept header ? thanks in advance. we have sample on versioning using web api odata. can find h

PHP Image Upload Via JQUERY -

i'm trying pass form data (avatar & user id) through jquery post command, won't upload file. can please point me in right direction might doing wrong? here form , script: <form id="avatar"> <script> $(document).ready(function() { var ok = true; $('#avatarbutton').click(function() { var id=$("#id").val(); var avatar = $("#avatar").val(); if(ok == true) { $('.avatarvalidation').html("uploading avatar").removeclass("error").addclass("success"); jquery.post("php/<?php echo $usertype; ?>/avatar.php", { id:id, avatar:avatar }, function(data, textstatus){ if(data == 1){ $('.avatarvalidation').html("profile updated").removeclass("error").addclass("success"); } else if(data == 2){ $('.avatarv

asp.net mvc - How to fix intellisense for VS2010 if VS2012 changed files in bin folder? -

i work projects using vs2010, colleagues use vs2012 , 1 of colleagues updated bin folder svn repo , changed files affected intellisense. i've tried creating new mvc 4 project , overwriting following files: system.web.optimization.dll system.web.razor.dll system.web.webpages.deployment.dll system.web.webpages.dll system.web.webpages.razor.dll webgrease.dll but unfortunately, intellisense still isn't working. there additional files should taking account?

java - How do I make an button display a dialog when I click on it? -

i have 12 buttons , each button has name of in family on it. want make buttons functional. when user clicks on name want message pop , "hello (whatever name)!" code below. can please tell me how make these buttons function way want them to. in advance. import javax.swing.jframe; import javax.swing.jbutton; import javax.swing.jpanel; import java.awt.dimension; import java.awt.gridlayout; public class namebuttons{ public static void main(string[] args) throws exception { jframe frame = new jframe("pick name"); frame.setdefaultcloseoperation(jframe.exit_on_close); jpanel buttonpanel = new jpanel(); jpanel containerpanel = new jpanel(); buttonpanel.setlayout(new gridlayout(4,6)); buttonpanel.add(new jbutton("stephanie")); buttonpanel.add(new jbutton("dwayne")); buttonpanel.add(new jbutton("jennifer")); buttonpanel.add(new jbutton(&quo

qt - Paste entire column into QTableView from Excel -

i having issue pasting qtableview excel when user has copied selecting entire column in excel, putting every single row in selected column, entire excel sheet, on clipboard. following paste code qtableview (please note, in python using pyqt principle same c++). def paste(self): model=self.model() pastestring=qtgui.qapplication.clipboard().text() rows=pastestring.split('\n') numrows=len(rows) numcols=rows[0].count('\t')+1 selectionranges=self.selectionmodel().selection() #make sure have 1 selection range , not non-contiguous selections if len(selectionranges)==1: topleftindex=selectionranges[0].topleft() selcolumn=topleftindex.column() selrow=topleftindex.row() if selcolumn+numcols>model.columncount(): #the number of columns have paste, starting @ selected cell, go beyond how many columns exist. #insert amount of col

Google maps for rails: How to normalize two address fields -

i using google maps rails gem - https://github.com/apneadiving/google-maps-for-rails . according there model customization guide here - https://github.com/apneadiving/google-maps-for-rails/wiki/model-customization normalize address field. aparently have 2 address ( from , to ). how do it? i tried this acts_as_gmappable :normalized_address => "from_address" && "to_address" def gmaps4rails_address from_address && to_address end it doesnt work entirely. to_address gets normalized. from_address stays entered user (although calculates fine. have normalized version). any help? i think problem models rather gmaps4rails. should have each address polymorphic object . attach twice parent model; once from_address , once to_address. each address can normalized on it's own. edited example.... example: class address < activerecord::base belongs_to :mappable, :polymorphic => true acts_as_gmappable :normalize

monkeyrunner - Android.isUserAMonkey throws RuntimeException -

i'm seeing exceptions when activitymanager.isuseramonkey() run on older android devices: java.lang.runtimeexception: unable start activity componentinfo{com.myapp.androidapp}: java.lang.runtimeexception: unknown exception code: 1 msg null @ android.app.activitythread.performlaunchactivity(activitythread.java:2781) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2797) @ android.app.activitythread.access$2300(activitythread.java:135) @ android.app.activitythread$h.handlemessage(activitythread.java:2132) @ android.os.handler.dispatchmessage(handler.java:99) @ android.os.looper.loop(looper.java:143) @ android.app.activitythread.main(activitythread.java:4914) @ java.lang.reflect.method.invokenative(native method) @ java.lang.reflect.method.invoke(method.java:521) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:858) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:616) @ dal

Windows 7 Query Folder Preferences -

i looking @ adding feature explorer program. program not allow folder based viewing preferences (pictures, music, documents, etc.) windows does. wondering how can access/alter preferences of folder known windows explorer applies other explorer program well. way explorer program won't have keep track of preferences , use what's available windows.

javascript - Sencha Touch carousel Image issue -

i have create vbox layout view , added carousel images in follows: var imgslider1 = ext.create('ext.carousel.carousel',{ direction: 'horizontal', singleton: true, height:300, width:250, id: 'imgslider', buffersize: 2, defaults: { stylehtmlcontent: true }, items: [ { xtype: 'image', cls: 'my-carousel-item-img', src: 'resources/images/training.jpg' }, { xtype: 'image', cls: 'my-carousel-item-img', src: 'resources/images/upcoming_programms.jpg' } ] }); ext.define('rasovaiapp.view.homepage',{ extend: 'ext.container', fullscreen: true, requires:[ imgslider1 ], config:{ scrollable: true, layout: { type: 'vbox' }, items: [ { xtype: 'container', layout: { height: 300, type: 'hbox' }, items: [