Posts

Showing posts from March, 2011

Match values in two columns and return value using vlookup from third column in Excel -

i have worksheet (called final) similar data below: b c year month births 1880 1 530 1880 2 456 1880 3 234 1890 1 163 1890 2 123 1890 3 125 second spreadsheet: b c d year month births 1880 1 1890 2 1890 3 i wish mach value column in sheet 2 e.g. 1880 sheet 2, in sheet 1 column return value in d when meets specific month criteria e.g. 1880(a) , 1(b) return 530 in column d this formula wrote not give me (gives na) =if(if(a2=final!b12,true,false),true,vlookup(final!a2,final!b12:c3532,2,false)) to me logic is, if a2=b2 true outer if gets true , if true vlookup , return value in second column else false) doesn't work you need put logic in lookup. =index(final!$c$1:$c$500(match(1,if(a2=final!$a$1:$a$500,if(b2=final!$b$1:$b$500,1,0),0),0)) this array formula. needs confirmed ctrl-shift-en...

android - Losing ACTION_DOWN parameters when InterceptTouchEvent -

i have parent view should follow finger on touch , child view inside clickable. used onintercepttouchevent decide if have consume touch event on parent or child comparing touch distance before action_up. obviously used "retrun false" on action_down in onintercepttouchevent (because propagate event before calculations) unfortunately ontouch loses action_down. the question how can initialize parameters (as initial position of parent view) ontouch (not onintercepttouchevent)? footnote: reason have write ontouch inline other codes have implemented onintercepttouchevent inside object definition. a part of object definition: boolean mmisbeingdragged; float mlastx; float mstartx; int mtouchslop=viewconfiguration.get(getcontext()).getscaledtouchslop(); @override public boolean onintercepttouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: mlastx = event.getx(); mstartx = mlastx; ...

c++ - Calling NtQuerydirectoryFile from a Kernel Hook Crashes the Kernel -

i'm using latest version of easyhook hook kernel functions. did setup debugging important on windows 8.1 64-bit based virtual machine, , tested hooking both of ntquerydirectoryfile , ntquerysysteminformation in user mode , ntquerysysteminformation in kernel mode without problem. my current problem hooking ntquerydirectoryfile using same code used user mode hook, fails when call original function giving me access violation error. i'm using following code kernel mode hook: ntstatus ntquerydirectoryfile_hook( __in handle filehandle, __in_opt handle event, __in_opt pio_apc_routine apcroutine, __in_opt pvoid apccontext, __out pio_status_block iostatusblock, __out_bcount(length) pvoid fileinformation, __in ulong length, __in file_information_class fileinformationclass, __in boolean returnsingleentry, __in punicode_string filename optional, __in boolean restartscan ) { ntstatus status; status = ntquerydirectoryfile(fileha...

ALSA buffer underrun network audio -

i'm using arch linux arm on olimex lime2. network speed tests between device , nas indicate > 450mbps. i'm using i2s driver audio output. when playing 2 channel, 192khz / 24bit material, following: playing usb stick: good. playing nfs share: buffer underruns between 7 & 300 ms. playing cifs share: buffer underruns between 199 & 215 ms. where begin track down issue? edit: a. i'm testing with: aplay -d default:card=sunxisndi2s "/mnt/nfs/06 - rosie 192.wav" b. 96khz / 24bit material plays without issue on network. edit: ping results: 64 bytes 10.10.10.9: icmp_seq=1 ttl=128 time=0.750 ms 64 bytes 10.10.10.9: icmp_seq=2 ttl=128 time=0.371 ms 64 bytes 10.10.10.9: icmp_seq=3 ttl=128 time=0.439 ms 64 bytes 10.10.10.9: icmp_seq=4 ttl=128 time=0.440 ms 64 bytes 10.10.10.9: icmp_seq=5 ttl=128 time=0.362 ms 64 bytes 10.10.10.9: icmp_seq=6 ttl=128 time=0.438 ms 64 bytes 10.10.10.9: icmp_seq=7 ttl=128 time=0.441 ms 64 bytes 10.10.10.9: icmp_se...

c - Fixed width, minimum width and fastest minimum width unsigned 8 bit integer -

three days read article on choosing correct integer size . before reading article, unaware of these 3 keywords viz: 1) fixed width unsigned 8-bit integer: uint8_t . (typedef's c99 complaints) 2) minimum width unsigned 8-bit integer: uint_least8_t . 3) fastest minimum width unsigned 8-bit integer: uint_fast8_t . so question are: 1) mean saying "at least 8 bits wide" uint_least8_t & uint_fast8_t . example, let's take @ snippet of code for(u16 i=0;i<counter;i++) { increment_counter++; } here :- u16 means unsigned short. counter , increment_counter 2 variables when counter =0xff ; increment_counter work fine type of keyword declaration. when counter =0x01ff ; kind of declaration should choose? uint_least8_t (who guaranteed @ least 8 bits wide) or unit16 type? 2) how choosing uint_fast8_t affects code speed. 3) how choosing uint_least8_t consumes lesser data memory unsigned char. i webbed doubts got nothing. appreciated. thanks in a...

java - Defining a class name Money -

i stuck add/subtract methods defining class named money objects represent amounts of money. class should have 2 instance variables of type int dollars , cents in amount of money. include constructor 2 parameters of type int dollars , cents, 1 one constructor of type int amount of dollars 0 cents , no-argument constructor. include methods add , minus addition , subtraction of amounts of money, , return value of type money. include reasonable set of accessor , mutator methods methods equals , tostring. again, stuck on add/minus part, cannot nail down. plus equals part bit confusing. yes homework. trying best need bit of push. please take look.... public class money { private static int dollars; private static int cents; public money() { } public money(int dollars, int cents) { this.dollars = dollars; this.cents = cents; } public money(int dollars) { this.dollars = dollars; } public int getd...

Microsoft Oxfordproject Speech-to-text Rest API -

Image
i need recognize speech text microsoft engines via rest api (i know other speech text engines , have them working, need ms speech-to-text). i read lot of info , manuals cannot working. i tried follow manuals ms site (sorry cannot add more links) no luck, found many "working" examples, , find way how recognize via ms api, stack problem: 1) can token authorize recognition request: 2) after have token, can try make request recognize recording: but in case error. despite "version" set in request. if knows how recognize audio recordings via microsoft rest api service please give me example. it's hard sure screenshot makes version , other parameters in form (payload), spec requires these query parameters instead.

java - Give a CFG for this language -

the language is: {0 n 1 m | n =2 m } i need give cfg based on language, , can't figure out. it's been hour , extremely frustrated, got hints/lead-way? good question. here start. step 1: write down start variable. step 2: find var written down , rule has var left hand side. replace var right hand side of rule. step 3: repeat 2 until no more var remain.

iphone - Image dragging on a UIScrollView -

a uiviewcontroller called when user touches image on uitableviewcell . called using modalviewcontroller . on modalviewcontroller uiscrollview , uiimageview in middle, fetches image using nsdictionary (passed uitableviewcell ). now, wanted achieve ability user drag image vertically only, such dragging , releasing little cause image return center animation. if user drags extremes, entire uiscrollview dismissed , user returns uitableview . used following code. issue here is, , name suggests, code crude. there elegant way of doing this, without need of calculation? bool imagemoved=no; - (void) touchesmoved:(nsset *)touches withevent:(uievent *)event { uitouch * touch = [touches anyobject]; cgpoint pos = [touch locationinview: [uiapplication sharedapplication].keywindow]; cgrect imagerect = _photoimageview.frame;//_photoimageview object of uiimageview cgfloat imageheight = imagerect.size.height;//getting height of image cgfloat imagetop=240-imageheight/2; cgfloat imag...

jquery - Superscrollorama, TweenMax Make an Animation play and after that resume scrolling -

is there way let user scroll point, element fades in, after animation (x2) played (without user input) , after scrolling triggers further animations, can triggered if animation(x2) has played through. var controller = $.superscrollorama({ triggeratcenter: false }); // set duration, in pixels scrolled, pinned element var pindur = 2800; // create animation timeline pinned element var pinanimations = new timelinelite(); pinanimations .append([ tweenmax.to($('#mouse_walk'), 5, {css:{opacity: 1}, oncomplete: function(){ $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '977px', width: '1080px', left: '49.5%', top:'370px'}, 200, function(){ $( "#mouse_walk, #mouse_walk img" ).stop...

javascript - get datepicker to display todays date by default -

using date picker field, works fine btw. need display todays date default , not 1/1/0001 @html.textboxfor(model => model.selecteddate, new { @class = "jquery_datepicker", @value = model.selecteddate.hasvalue ? model.selecteddate.value.tostring("dd/mm/yyyy") : string.empty }) @using (script.foot()) { <script type="text/javascript" language="javascript"> $(function () { var dates = $("#selecteddate").datepicker({ dateformat: 'dd/mm/yy' }); }); </script> } also need in format 24/09/2013, if possible dd/mm/yyy this should work $("#selecteddate").datepicker("setdate", new date());

C# Enabling/Disabling fields in PropertyGrid -

Image
i developing user control library, in need provide programmer, property grid customize properties of control. if programmer uses system.windows.forms.propertygrid (or visual studio's designer) of property fields in system.windows.forms.propertygrid should enabled/disabled depending on other property of same user control. how it? example scenario this not actual example, illustration only. ex: usercontrol1 has 2 custom properties: myprop_caption : string , myprop_caption_visible : bool now, myprop_caption should enabled in propertygrid when myprop_caption_visible true. sample code usercontrol1 public class usercontrol1: usercontrol <br/> { public usercontrol1() { // skipping details // label1 system.windows.forms.label initializecomponent(); } [category("my prop"), browsable(true), description("get/set caption."), defaultvalue(typeof(string), "[set caption here]"), ...

android, add Marker from Bitmap on googlemap -

i'm using googlemap-android-api v2, , want create marker bitmap @ runtime. do: bitmapfactory.options options = new bitmapfactory.options(); options.inpreferredconfig = bitmap.config.argb_8888; bitmap bitmap = bitmapfactory.decodefile(filepath, options); //create thumbnail use marker bitmap thumbnail = thumbnailutils.extractthumbnail(bitmap,10,10); markeroptions markeroptions = new markeroptions().position(currentlatlng).icon(bitmapdescriptorfactory.frombitmap(thumbnail)); mmap.addmarker(markeroptions) it never seems work, i'm sure both bitmap , thumbnail not null. if instead of .frombitmap , use .fromresource(r.drawable.some_image) shows. however, said, want change @ run-time user's input. any tip? thanks updated: marker show if add (i.e, use above code) @ onresume() of activity/fragment host map. before use code @ onactivityresult() , after user browse file filepath . me, it's still strange since ...

Git push hangs on TOTAL -

git started hang on push command. searched on other questions solutions didn't work. i on ubuntu 12.04. counting objects: 18, done. delta compression using 2 threads. compressing objects: 100% (13/13), done. writing objects: 100% (13/13), 2.57 kib, done. total 13 (delta 9), reused 0 (delta 0) it working 5 minutes ago on larger files. internet connection perfect. it works on repository on same server , on same development machine. repo corrupted, had clone again , copy changes manually in new cloned directory

c - Free() crashes program -

when calling function b_destroy , program crashes before reaches end of function. function looks this: void b_destroy(buffer * const pbd){ #ifdef debug printf("in destroy\n"); printf("buffer address %d\n",pbd); printf("head address %d\n",pbd->ca_head); #endif if(pbd != null || pbd->ca_head != null){ if (pbd->ca_head != null) free(pbd->ca_head); if (pbd != null) free(pbd); } #ifdef debug printf("exiting destroy\n"); #endif } i know pointers aren't null because i'm able print out memory location. ideas why crashes? it doesn't matter address not null, rather data there has not been freed. need search elsewhere see if same memory has been freed, free doesn't set given pointer null afterwords.

regex - Redirect desktop users away from mobile site with .htaccess -

hello folks @ stackoverflow, i'm looking redirect desktop users away mobile site .htaccess: i have code works when mobile user tries access mobile version of website example: m.website.com. rewriteengine on rewritecond %{query_string} !^desktop rewritecond %{http_user_agent} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|#opera mobile|palmos|webos" [nc] rewriterule ^$ http://m.website.com [l,r=302] however if user types m.website.com on desktop browser, goes directly mobile version content. is there way add additional code .htaccess file make work in way when desktop user attempts go m.website.com remains in desktop version. place additional rule in .htaccess of document_root of m.website.com : rewriteengine on rewritecond %{http_host} ^m\. [nc] rewritecond %{http_user_agent} !(android|blackberry|googlebot-mobile|iemobile|iphone|ipod|opera\smobile|palmos|webos) [nc] rewriterule ^ http://website.com%{request_uri} [l,r=302]

tortoiseSVN 1.8 upgrade did not upgrade svn.exe -

we have windows server 2008 running iis & coldfusion upgraded tourtoisesvn client 1.7.4 1.8.2. upgrade went ok no errors. rebooted server complete windows explorer integration. c:\program files\tortoisesvn\bin\svn.exe did not upgraded. if svn.exe --version says @ version 1.7.4 while gui integration @ 1.8. error when use command line svn.exe says client old work working copy @ .... how can svn.exe upgraded 1.8? ton. you installed optional (not installed default) commandline tools tortoise? i'm guessing have commandline client installed (collabnet, cygwin, etc...) on %path% . can show output of these commands: echo %path% svn svn --version c:\program files\tortoisesvn\bin\svn.exe --version

powershell - Laravel 4 + Iron: How to register a queue? -

i have setup free account , create first project: queue_test have followed tutorial: http://vimeo.com/64703617 taylor otwell , create simple app uses queues. put app on server. point is: how can push queue? how can run command: php artisan queue:subscribe queue_test http://mydomain.com/queue/push if use powershell on localhost.. how can run command on server? someone can clarify me point? you can manually in https://hud.iron.io/dashboard : open ironmq (mq button) project. click queues tab click on queue name in subscribers widget, add url: http://mydomain.com/queue/push .

MongoDB c# driver SetWrapped issue -

** updated more code: i have class/entity similar public class price { public decimal mrp { get; set; } } this part of complex doc following: { "name" : "name", "_id" : objectid("522a83c2a833e20db4b028ea"), "price" : { "mrp" : 599, } } i using c# driver update doc ... following: // function check if field exists in doc private bool check_field(bsondocument doc, string field_name) { if (doc.contains(field_name)) { return true; } else { return false; } } // whole doc foreach (var c in cursor) { product prd = new product(); prd.id = check_field(c.tobsondocument(), "id") ? converttostring(c.tobsondocument()["id"]) : null; prd.price = check_field(c.tobsondocument(), "price") ? jso...

sql server - Querying a running-percentage over a date range from MSSQL? -

i want graph % of users on time have twitter account connected. number of users changes constantly, , % of them connect twitter account. the table has user account specific createdatetime column tw_connectdatetime column. let's i'm interested in trend of % connected on last 7 days. there way can have mssql calculate percentage every day in specified range, or need myself using multiple queries? doing in app logic (pseudocode): for day in days: query: select count(userid) totalusers ,c.connected ,cast(c.connected float)/count(userid) percentage users outer apply ( select count(userid) connected users tw_connectdatetime <= $day ) c createdatetime <= $day group c.connected what i'm unsure of how, if it's pos...

How to getElementById() from HTML tag, that is rendered by embed javascript? -

i having file - index.html, has embed script.js. script.js - rendering html <a href="url.html" id="url"> tag. i want insert in index.html code, shows href value, rendered script.js: var d = document.getelementbyid( 'url' ); alert(d.href); but script working on tags, written index.html. how script work? index.html <script type="text/javascript" src="script.js"></script> <script type="text/javascript"> var d = document.getelementbyid( 'url' ); alert(d.href); </script> script.js: document.write("<iframe src=iframe.html></iframe>"); iframe.html: <a href=url.html id=url>test url</a> --- edited --- my friend came code: <script type="text/javascript"> $(document).ready(function() { var href = $("iframe").contents().find("a").attr('href'); alert(href); }); </script> but alert() show...

Saving LZW encoded data into a mySQL database -

i send zipped data, done lzw compression @ client side js, server. problem data becomes corrupted after saving database sql. so question is, collation should use, accomplish that? (my current 1 latin1-default collasion) i checked if problem arrieses during data transferring client server , vice versa sending encoded data http-server , sending(php-echo) immeadiatly without processing it. decode lzw properly. should problem database. more information schema: have single table 3 cols. "data" type of "blob". (i tried text). user_id int , type varchar. this how save data: insert svg.saved_data (user_id, data, type) values ('".$user_id."', '".$data."', '".$type."'); i don't know platform is, link below gives general recipe in php. has example should need. https://stackoverflow.com/questions/17/binary-data-in-mysql

c# - RegularExpressionValidator returns false for valid input -

i trying validate time zone offset has format of optional minus sign, followed 2 digits, followed colon followed 2 more digits; -05:00 or 04:30. used \b[-]?\d{2}:\d{2}\b validation expression, tested on online re testing sites , "successful match" validator keeps returning falase. can't see doing wrong. enter -05:00 or -13:99 , both return false. tried escape colon same thing. drop word boundaries you'll matches. -?\d{2}:\d{2} if want first occurrence make this: -?\d{2}:\d{2}$ if want match valid times use one: -?([0-2][0-3]|[0-1][0-9]):([0-5][0-9]) the above 1 matches hour in range of 0-23:0-59 btw.

python - Django's send_mail messages get grouped into a gmail converation -

for users of our django app receive emails through gmail finding emails getting grouped conversations shouldn't be. i'm not sure gmail expects in email consider unique enough not group conversation when send plain text emails different subjects using send_mail or try multipart/alternative emailmultialternatives html body gmail still assumes part of same conversation. obviously creates confusion when our application sends emails different subjects , bodies same user , grouped , gmail shows subject of first message in conversation. i have 100% confirmed looking @ raw original email messages make sure emails different subjects , bodies. i want know if can change in how django creates email message can play nice gmail conversations. i using python 2.7.4, , can replicate "issue" django 1.4 , 1.5. make sure messages on different subjects have different 'from' address

selenium - Record confirmation email -

using selenium ide(html), i'm recording registering under 1 website, , confirmation email sent when sign successful. this confirmation message sent gmail. recording check in gmail using selenium-ide can't record.so want know how record in gmail using selenium? well email going? gmail? yahoo? some other web page? the above 4 questions important! because, let's want check confirmation email gmail if need go gmail url , need record login , assert things. i show example gmail. i want check in gmail if command open target https://mail.google.com/ this 1 need add test. because of need go new page need use open command.

hadoop - Unknown protocol to job tracker -

i'm attempting run haddoop mapreduce job within datastax 3.1 , getting error. ideas on what's cause? caused by: org.apache.hadoop.ipc.remoteexception: java.io.ioexception: unknown protocol job tracker: org.apache.hadoop.hdfs.protocol.clientprotocol @ org.apache.hadoop.mapred.jobtracker.getprotocolversion(jobtracker.java:347) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodacc quoting hadoop source documentation: org.apache.hadoop.hdfs.protocol.clientprotocol used user code via org.apache.hadoop.hdfs.distributedfilesystem class communicate namenode. dse not come namenodes nor datanodes - part of apache hadoop hdfs , in dse have been replaced cassandra file system. the stacktrace states using hdfs protocol connect jobtracker node, suggests incorrectly sumbitting jobs. with dse should submit m/r jobs invoking: dse hadoop jar <your m/r jar file> <your m/r main...

game physics - Please help me write scripts with AutoHotkey -

i've been inspired art of writing scripts on autohotkey. beginner desperately needs insight. appreciate time , input on matter. primary objective: looping script interaction i'd have single script running @ time trigger 1 upon given events. have 2 scripts, let's name them , b. a's mission perform given tasks until finds specific image trigger b. b's mission perform given tasks image until disappears trigger a. as far looping script interaction, here's i've got. here's a.ahk:- loop imagesearch, px, py, 1, 1, 10, 10, %a_workingdir%image.png if errorlevel = 1 wheeldown else run, %a_workingdir%b.ahk return here's b.ahk:- loop imagesearch, px, py, 1, 1, 10, 10, %a_workingdir%image.png if errorlevel = 0 click %px%, %py% else run, %a_workingdir%a.ahk return please let me know if doing correctly.. imagesearch, can write x, y, instead of px, py? wondering on differences. secondary objective: programming mo...

c# - How do I handle nested NPoco objects that may be null? -

i using npoco object mapping database. have following entities: public abstract class namedentity { public int id { get; set; } public string name { get; set; } } public class person : namedentity { public office office { get; set; } } public class office : namedentity { public address address { get; set; } public organisation parentorganisation { get; set; } } public class address { public string addressline1 { get; set; } } public class organisation : namedentity { } and retrieving objects using npoco in repository: var people = context.fetch<person, office, address, organisation>(sql); this working fine, except case person not have office , in case result of left join in sql query returns null office, address , organisation columns. in situation, unhandled exception thrown in npoco: system.reflection.targetinvocationexception: exception has been thrown target of invocation. ---> system.nullreferenceexception: object referenc...

jquery ajax how to know the return data is xml or html? -

how can know/ test return data jquery ajax xml, html or plain text? for instance, have these 2 types of data want handle. xml, <?xml version="1.0"?> <xml><response><error elementid="accept_terms_conditions" message="field 'agree terms &amp; conditions' needs filled."/></response></xml> html, <form action="http://xxx/booking.php" method="post" enctype="multipart/form-data" class="item-form border-top-bottom"> ... </form> jquery, $(".button-submit").click(function(){ var form = $(this).closest("form"); var url = form.attr("action"); // load article object. $.ajax({ type: "post", //datatype: "html", url: url, data:form.serialize(), context:$(".holder-form-book-online"), async: false, beforesend: function() { ...

css - how to center text inside hyperlink with border -

i need text in center of border. seems bit more down should fiddle here i have tried removing paragraph , added <span>register test</span> <br><span>my text 2</span> but didn't work either did try change padding on a.register element? try : a.register { padding: 18px 0 6px; } http://jsfiddle.net/3fyf9/21/

c# - Resizing High Quality images for web -

hi guys resizing images in c# , saving them .png. public static bitmap resize(int x, int y, image p) { bitmap img = new bitmap(x,y); using (graphics gr = graphics.fromimage(img)) { gr.smoothingmode = smoothingmode.highquality; gr.interpolationmode = interpolationmode.highqualitybicubic; gr.pixeloffsetmode = pixeloffsetmode.highquality; gr.drawimage(p, new rectangle(0, 0, x, y)); } return img; } the problem when user uploads high quality image such images high end smartphones such galaxys, iphones etc filesize of resulting resized image quite high. have constructed table of resized images file size , pixel size. 1) img1 1280 * 666px => 458 kb 2) img1 300 * 399px => 221kb 3) img2 1280 * 1444px => 2.08mb 4) img2 300 * 451px => 327kb i know have interpolation , smoothing set high quality example purposes , saving images .png preserve transparency. setting should change obtain image of reasonable quality , files...

jdbc - Inside mybatis-config.xml, is possible to read properties from pom.xml in a Maven project? -

i'm developing sample multi-module maven project uses mybatis. dependencies have own modules , mybatis self. on persistence layer, have created following on pom.xml : <properties> <!-- jdbc --> <jdbc.url>jdbc:postgresql://localhost:5432/kpi?autoreconnect=true</jdbc.url> <jdbc.driverclassname>org.postgresql.driver</jdbc.driverclassname> <jdbc.username>postgres</jdbc.username> <jdbc.password>postgres</jdbc.password> <jdbc.initconnections>15</jdbc.initconnections> <jdbc.maxactive>40</jdbc.maxactive> <jdbc.maxidle>5</jdbc.maxidle> </properties> then, in mybatis-config.xml inside src/main/resources , did following: <environments default='development'> <environment id='development'> <transactionmanager type='jdbc'/> <datasource type='pooled'...

sorting - NullPointerException using java.util.Arrays.sort() -

this program reads lines of input file , stores them array words. each element in words[] put character array , sorted alphabetically. each sorted character array assigned string , strings populate array sortedwords. need sort elements in sortedwords array. nullpointerexception when use arrays.sort(sortedwords). public static void main(string[] args) throws filenotfoundexception { scanner scanner = new scanner(system.in); system.out.print("enter file name: "); system.out.flush(); string filename = scanner.nextline(); file file = new file(filename); string[] words = new string[10]; string[] sortedwords = new string[10]; try { filereader fr = new filereader(file); bufferedreader br = new bufferedreader(fr); string line = br.readline(); int = 0; while(line != null) { words[i] = line.tostring(); // assigns lines array line = br.readline(); // set line null, terminat...

Copying from struct pointer to struct pointer for database in C -

i have following structures created: typedef struct { char name[15]; int id; } employee; typedef employee item; typedef struct { item items[5]; int size; } list; i using function call peek see being stored in list: void peek (int position, list *l, item *x); the function should take item in list [l] @ [position] , copy address [x]. have peek function this: void peek (int position, list *l, item *x) { item *b; b = malloc(sizeof(l->items[position])); x = b; } this assigns x same location b think result in memory leak , more importantly if try call id of item x in main, function: int employeeid (employee x) { return(x.id); } i returned 32665 or along lines. way data l x? x , b both pointers x = b pointer assignment, not structure assignment x pass value parameter, assigning value x inside function has 0 impact on value of x outside function. try (not solution, step in right direction): void peek (int position, list *l, item **x)...

count hasMany relation in mongodb/mongoid -

enter code herei"m working on rails app running mongodb via mongoid. let's have 2 collections , posts , comments, , they're linked habtm relation, i'd select posts have comments, , think way count comments each post , order comments.count desc. don't know how count number of comments each posts, add column posts results count(comments) comments_count in sql, , order "pseudo-field". any thoughts on ? thanks edit, looking @ others answers related this, i've tried: db.posts.aggregate([ { $group: { _id: { post_id: '$post_id', comment_id: '$comment_id' } }}, { $group: { _id: '$_id.post_id', comments_count: { $sum: 1 } }}] , function(err, result){ console.log(result); } ); i'm getting { "result" : [{ "_id" : null, "datasets_count" : 1 }], "ok" : 1 } the aggregation framework in mongodb has oper...

objective c - iOS7 : how to set navigationItem property of UISearchDisplayController? -

i have uisearchdisplaycontroller works in 1 of ios6 app. now, want migrate app ios7. i had read apple docs, , says following : starting in ios 7.0, can use search display controller navigation bar (an instance of uinavigationbar class) configuring search display controller’s displayssearchbarinnavigationbar , navigationitem properties. displayssearchbarinnavigationbar pretty easy set up. clue have navigationitem following : important: system raises exception if attempt set titleview property search display controller’s navigation item. i can't seem find example of how set navigationitem. how navigationbar embed searchbar? can show me example? thank in advance! uisearchdisplaycontroller creates , manages navigation item needed display search bar in navigation bar. don't need create own, although can access via searchdisplaycontroller.navigationitem after displayssearchbarinnavigationbar has been set yes (the navigationitem created lazily) when...

NServiceBus SetHeader In Catch of Handler -

we using try catch in our message handler, realize against recommended best practices of not handling exceptions. said, have been asked identify last retry , send message queue in suppressed transaction. sending of message working however, calling message.setheader (also tried bus.currentmessagecontext.headers[esbservice.firstlevelretriesheader] = currentfirstlevelretryattempt.tostring();) implement own tracking of retry attempts. looking write incrementing number in header , see when reaches specific value trigger send of message queue. seems write it, when the message processed again, never present. using transactions, possible changes getting rolled when throw exception. tried writing header in suppressed transaction , did not work. is there way update header while still letting exception bubble nsb.

c# - SQLite. Fix sqlite-net-wp8 project dependencies -

why sqlite not available on nuget? why part of visual studio have go updates @ tools->extensions , updates? started coding windows 8 , windows phone 8 in past few months , insight this. to me, using sqlite on windows 8 project creates vs-level dependency. let's develop client library using version of sqlite referenced visual studio ide (example: 3.7.x) , distribute library developer uses sqlite 3.8.x referenced his/her visual studio ide, client library still work? what happened me last week this: i developed client library windows phone 8 using sqlite , had use 3rd party wrapper written peter huene called sqlite-net-wp8. it available at: https://github.com/peterhuene/sqlite-net-wp8/ when @ sqlite.vcxproj file ( https://github.com/peterhuene/sqlite-net-wp8/blob/master/sqlite.vcxproj ) of project, has references given version of sqlite. looks every time update sqlite on visual studio, have update .vcxproj file too. something like: <importgroup label="...

Getting Vimeo thumbnail images using php is unbelievably slow -

i'm using php code thumbnail images of vimeo videos. while($row = $database->fetch_array($result)) { $url = $row["link"]; sscanf(parse_url($url, php_url_path), '/%d', $video_id); $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$video_id.php")); $image = $hash[0]['thumbnail_small']; echo "<img class='vimeo_video' video='$video_id' src=$image>"; } it fetches images, takes @ least 30 seconds load page. vimeo's servers or code?

c# - Reorder an IList<T> using the minimum number of Inserts and Removes -

i need extension method takes 2 arguments: target ilist<t> , custom comparer. public static void customsort<t>( ilist<t> target, icomparer<t> comparer ) { ... } the extension method's job arrange target's elements in order indicated custom comparer. here solutions won't work: the list<t>.sort in-place sorting, i'm after. can't assume target's concrete type list<t> . linq offers solutions unfortunately output results new enumerable instead of modifying target list. instead, need target's remove , insert methods called put elements right order. target list may observable important solution not more removes , inserts necessary obtain desired order. i think you. we sort array of offsets, determine set of deltas need applied , apply them produce newly ordered ilist. public static void customsort<t>( ilist<t> list , icomparer<t> comparer ) { int[] unsorted = enumerabl...

javascript - Using lodash array functions on Restangular collections -

i'm using restangular angularjs, , iterate on collection in function of controller, need modify collection returned restangular: var ordercontroller = [ '$scope', '$http', 'restangular', function($scope, $http, restangular) { $scope.orders = restangular.all('orders').getlist(); $scope.toggleorder = function(order) { _.foreach($scope.orders, function(order) { console.log(order); // not order! order.someproperty = false; // goal }); }); }]; i think problem $scope.orders promise, not actual array, _.foreach tries iterate on properties of promise instead of objects. same result angular.foreach . how can iterate on restangular resource collections? i'd have access collection functions of lodash, such _.filter , well. restangular.all('orders').getlist() - promise, not array. assign list using $object : $scope.orders = restangular.all('orders').getlist().$object; lis...

java - How to solve the problm of a class overshadowed by a jar file? -

i'm using netbeans develop projects, found class in jar file overshadows file same name, how solve problem ? i have project called db_tools_panel, has following structure : src/ : db_tools_panel.java utility/ : tools_lib.java so inside src dir there file : db_tools_panel.java, , in src dir there dir called utility, inside utility there file called tools_lib.java. i packaged project jar file : db_tools_panel.jar then created 2nd project fit, has following structure : src/ : fit.java utility/ : tools_lib.java lib/ : db_tools_panel.jar it uses db_tools_panel.jar, db_tools_panel.jar in fit's lib dir, when change tools_lib.java in fit/src/utility, , run it, nothing happen, if it's never changed, know why, because jvm runs tools_lib.java package db_tools_panel.jar, won't see tools_lib.java in fit/src/utility, in other words, after included db_tools_panel.jar fit project, tools_lib.java in db_tools_panel.jar overshadow tools_lib.java in fit/src/...

jquery - Temporary ID For new object rails -

i trying upload photos through ajax on multistep form (which using ajax), problem facing in order upload photo , keep tied new object (lets call post) photo needs store posts id. can't post new object , id nil! have seen lot of websites when click create url looks "www.example.com/post?step=create&id=134813489134" whats weird id created, step rather simple user closes browser? object stay persist or deleted. in advance

html - Span not growing with child size -

i trying put 2 components on same line , have wrapped this. trying keep reusable possible , trying general of solution possible. html: <div class="form-group"> <span class="component-parent"> <label for="driverslicense.num">driver's license #</label> <input type="text" class="form-control" id="driverslicense.num"></input> </span> <span class="component-parent"> <label for="driverslicense.state">state</label> <select id="driverslicense.state" class="form-control"></select> </span> </div> css: label { display: block; } .component-parent { display: inline-block; } .form-control { width: 100%; padding: 6px 12px; } the width: 100% inherited bootstrap , if remove it cause kinds of problems rest of layout. the problem input und...

struct - getting field name as a string in matlab -

i have matlab reference manual value = getfield(struct, 'field') where struct 1-by-1 structure, returns contents of specified field, equivalent value = struct.field how can opposite getstringname(struct.field) return 'field' also if possible point @ field in numerical way similar array like struct{1} field 1 field edit if follow structname(1) list of field names, , dimentions speed: [2244x1 double] time: [2244x1 double] ... , on i want grab title speed string, , if possible structname(1).filed(1) speed without doing structname(1).speed i want print each field file field name! so if do for i=1:sizeofstruct printtofile(structname(i)); %<=== accessing field index, problem 2 end function printtofile(structfield) structfieldstr = getstrfiledname(structfield); %<=== obtain field string, main problem filename = strcat(fileloc, '/profile/', structfieldstr, '.dat'); %... ...

c# - base class implementing base interface while derived/concrete class implementing extended interface, why? -

i following book namely ".net domain driven design c#". question based on scenario shown in class diagram below: figure: http://screencast.com/t/a9uuljvw0 in diagram, a) irepository interface implemented (abstract base class) repositorybase whereas, b) irepository interface extended interface icompanyrepository (icompanyrepository : irepository). c) icompanyrepository implemented companyrepository derived sqlrepositorybase derived repositorybase (; which, stated in point a), implements irepository parent if icompanyrepository). d) create variable of interface icompanyrepository having reference object of clas companyrepository, below: icompanyrepository comrep = new company repository(); now, if call add() function icompanyrepository variable comrep... comrep.add(); then add() function in repositorybase class (which parent of companyrepository) called. my question: exact underlying object oriented rule/mechanism takes place due function add() ...

rubygems - "bundle install" for Ruby 1.8.7 on Ubuntu Raring Ringtail 13.04 -

i'm not rubyist , there might obvious i'm missing. i've wrote application in ruby 1.8.7, i'm trying package in vagrant (running raring 13.04), i've run "bundle install" install requirements , though gem1.8 exist, running bundle install still install gems ruby 1.9.3. , program fails @ runtime... any idea how solve this? update 1 the related gemfile (thanks first answerers): ruby '1.8.7' # ... gem 'trollop' but ruby1.8 myfile.rb error raised no such file load -- trollop (loaderror) after investigation, problem looks in bundle install : your ruby version 1.9.3, gemfile specified 1.8.7 i don't how solve problem. update 2 after following advices @klaffenboeck things have changed. i'm using rvm , have ruby 1.8.7 when entering in project folder. bundler seems install things correctly, require seems fail... path problem? see here detail vagrant / rvm setup: https://rvm.io/integration/vagrant update 3 pro...

javascript - How to reuse render function for multiple views in Backbone? -

i'm working on app in backbone, , have multiple views have same render function: render: function(){ this.$el.html(this.template(this.model.tojson())); return this; } how reuse function in multiple views can follow old dry way? you can use mixin pattern specified here: proper way of doing view mixins in backbone var renderable = { render: function(){ this.$el.html(this.template(this.model.tojson())); return this; } }; var view = backbone.view.extend({ //other methods }); _.extend(view.prototype, renderable); var myview = new view(); myview.render();

Zedgraph creating too small image -

the output of graph small, can't see values @ x , y axis. there way change this, graph bigger? code output graph is: zedgraphcontrol zc = new zedgraphcontrol(); graphpane pane = zc.graphpane; pointpairlist list1 = new pointpairlist(); lineitem curve1; pane.title.text = title; pane.xaxis.title.text = xaxistitle; pane.xaxis.scale.min = 0; pane.xaxis.scale.max = 11; pane.yaxis.scale.min = 1; pane.yaxis.scale.max = 12; pane.yaxis.title.text = yaxistitle; int32 totalcount = ds.tables[objectname].rows.count; double[] xvals = new double[totalcount], yvals = new double[totalcount]; (int = 0; < totalcount; i++) { xvals[i] = convert.todouble(ds.tables[objectname].rows[i]["ntotal"]); yvals[i] = convert.todouble(ds.tables[objectname].rows[i]["isomonth"]); } list1.ad...

asp.net mvc - Does letter casing of directories and urls matter in .NET MVC? -

say have titlecase directory name, call item within directory using lowercase url. does have effect or impact? for example, server need redirect incorrect lettercase correct lettercase? example a file here: /plugins/cmspages/images/my-image.jpg called with: /plugins/cmspages/images/my-image.jpg the routing engine isn't case sensitive. one thing wary of, if referring page urls - google treats lowercase , uppercase urls different pages, want make use of rel="canonical" ensure google , other search engines know 1 page, no matter whether url upper or lowercase.

c# - Binding DataGridView to database with EF5 classes not sending changes to database -

i using entity framework 5.0 + .net 4.5 i have created database using ef model first approach , want bind datagridview database using ef classes changes database or in datagridview synchronized automatically. this code: //form level fields private bindinglist<product> _products; private bindingsource _productsource = new bindingsource(); ... in form load event //load data database using ef classes var tmp = _context.basecategoryset.oftype<product>().tolist(); //converting ibindinglist _products = new bindinglist<product>(tmp); _products.allowedit = true; _products.allownew = true; _productsource.datasource = _products; //setting gridcontrol's data source productgrid.datasource = _productsource; i can add new rows or change data, changes not sent database - missing? additional things did in hope find solution... 1) added save button call updating grid control's data database explicitly, code: _productsource.endedit(); _context.savechan...

javascript - Jquery Border Color Toggle Issue -

what attempting change borders on document blue different, preferably clear if anything. ideas? current code: http://jsfiddle.net/nqtuv/ why not working? jquery: $(document).ready(function(){ $("#btn1").click(function(){ $("#header").addclass("hover"); $("#header").removeclass("no_hover"); }; $("#btn2").click(function(){ $("#header").removeclass("hover"); $("#header").addclass("no_hover"); }; $(".guess_box").hover(function(){ //this mouseenter event handler $(this).addclass("my_hover"); }; function(){ //this mouseleav event handel $(this).removeclass("my_hover"); }; }; your code complete mess! updated fiddle . should this: $(document).ready(function(){ $("#btn1").click(function(){ $("#header").addclass("hover"); ...