Posts

Showing posts from February, 2011

java - IText API convert HTML file to PDF - Formatting and Image rendering issues -

we have requirement convert html file pdf file. that, using itext api. if html has image in body, itext api fails put image in pdf , throws following exception. exceptionconverter: java.io.filenotfoundexception: d:\cid:870001313@01022011-2b8b (the system cannot find file specified). if html has image in body possible read image , make attachment pdf file? if html has tables generated pdf loses table format , puts data in pdf. need table in generated pdf in html. do have solutions or suggestions above 2 issues? if have other api apart itext fulfill our requirement, please suggest. a: itext html->pdf converter isn't good, thought looks getting attention in immediate future. b: i'm going guess there's script stuff going on there, souped itext never handle. check out wkhtmltopdf . uses web kit rendering (including javascript handling).

python - How to filter all selected options? -

i have these 5 options pull down menues: <select name="image_style"> <select name="image_background"> <select name="image_activity"> <select name="image_merchandise"> <select name="image_type"> i want selected ones filtered. try this: image_background = self.request.get("image_background") image_activity = self.request.get("image_activity") image_merchandise = self.request.get("image_merchandise") image_type = self.request.get("image_type") items = image.all() if image_style != "none": items.filter("image_tags =", image_style) elif image_background != "none": items.filter("image_tags =", image_background) elif image_activity != "none": items.filter("image_tags =", image_activity) elif image_merchandise != "none": items.filter("image_tags =", image_merchandise) e...

load all class files in a folder in codeigniter? -

how load class files in folder in codeigniter? its when develop, create , delete class files often, don't want add/remove manually in autoload.php. thanks! if want autoload directory of libraries, in application/config/autoload.php file, replace $autoload['libraries'] this: require basepath."helpers/directory_helper".ext; $libraries = directory_map(apppath."libraries/", true); foreach($libraries $library) { if( ! is_array($library)) { $class = str_replace(ext, "", $library); $autoload['libraries'][] = strtolower($class); } } i haven't tested that, i'm guessing work. write own helper file own function , require instead of ci's directory_helper. way load libraries, helpers, configs, models, etc. configure load sub directories, too... if wanted.

How to get link_to in Rails output an SEO friendly url? -

my link_to tag is: <%= link_to("my test title",{:controller=>"search", :action=>"for-sale", :id=> listing.id, :title => listing.title, :search_term => search_term}) %> and produces ugly url: http://mysite.com/search/for-sale/12345?title=premium+ad+%2b+photo+%5btest%5d how can link_to generate: http://mysite.com/search/for-sale/listing-title/search-term/12345 been trying few different ways , cannot find online, appreciate help! tahe @ this add in config/routes.rb map.connect ':controller/:action/:title/search_item/:id', :controller=>'search', :action=>'for_sale' restart server , check. hope helps :)

assembly - What do .xstabs assembler directives mean, and where are they documented? -

i've not been able find documentation on .xstabs assembler directive means, particularly on sparc architecture. i found following in local copy of man as : -s places stabs in .stabs section. default, stabs placed in stabs.excl sections, stripped out static linker, ld(1), during final execution. when -s option used, stabs remain in final executable because .stab sections not stripped static linker. but doesn't discuss x stabs, , doesn't explain stabs are, either. the sparc assembly language reference manual: appendix a: pseudo-operations has them: .xstabs <various parameters> not descriptive. any explanations or pointers useful resources gratefully appreciated. further googling turned stabs interface -- sun studio 9 (pdf, google htmlized-copy) seems explain things, albeit in more detailed manne...

.NET Binary Serialize object with references to other objects . . . what happens? -

Image
if have object instance references other objects (for example instances b , c), , binary serialize a file, happens? have serialized data includes a, b , c? how work exactly? if deserialize data? a, b, , c?? (feel free include internal workings explanations well). all of references other objects serialized well. if deserialize data, end complete, working set of data, including objects a, b, , c. that's primary benefit of binary serialization, opposed xml serialization. if of other classes object holds reference not marked [serializable] attribute , you'll serializationexception @ run-time (the image of shamelessly stolen web; run-time errors don't anymore in current versions of vs):      further that, i'm not sure "internal things" hoping understand. serialization uses reflection walk through public , private fields of objects, converting them stream of bytes, written out data stream. during deserialization, inverse happens: stream of...

asp.net mvc 2 - Linq to SQL and MVC 2 "Class member MyClass.MyProperty is unmapped. _COMPlusExceptionCode = -532462766 -

thanks in advance listening problem. i have linq sql class, specific properties being displayed on grid use viewmodel. firstly i'll paste part extentend class via partial class: public string owner { get; private set; } public int32 documents { get; private set; } partial void onloaded() { owner = "personcompanyrolemedicalexam"; documents = sfdb.storedfiles.count(s => s.owner == this.owner && s.ownerid == this.id); } next ill paste viewmodel used grid: public class medicalexamviewmodel { public int32 id { get; set; } public int32 personcompanyroleid { get; set; } public int32? periodindays { get; set; } public datetime? examcompleted { get; set; } public bool? medicallyfit { get; set; } public int32 documents { get; set; } } and lastly method ajax call grid populate it: [gridaction] public actionresult _medicalexamgridajaxbinding(int32 id) { personcompanyrole pers...

php - Need to add an array into another array at a specified key value -

ok, have array so, it's not guaranteed laid out in order of time... $array = array( 'sadness' => array( 'info' => 'some info', 'info2' => 'more info', 'value' => 'value', ), 'happiness' => array( 'info' => 'some info', 'info2' => 'more info', 'value' => 'the value', ), 'peace' => array( 'info' => 'some info', 'info2' => 'more info', 'value' => 'the value', ) ); ok, , i'd throw in array right after happiness key defined. can't use key of "peace" since must go directly after happiness, , peace might not come after happiness array changes. so here's need add after happiness... $another_array['love'] = array( 'info' => 'some info...

sql server - SSRS: Report label position dynamic -

i have report displays customer address in multiple labels. my customers use windowed envelopes mailing. need address labels position configurable. something like, i'll have database table stores top/left position of each label per customer. based on table, need position address labels on report. i thought, doable expressions, location property doesn't provides ability set expression , make label's top , left dynamic. anybody, ideas, on how achieve this? as mentioned, cannot set expression location property. want before seems there no solution work.

winapi - How to show the progressbar using threading functionality in win32? -

in application have simple module read files process take few seconds..so thought of displaying progress bar(using worker thread) while files in progress.i have created thread (code shown below) , designed dialog window progress control.i used function mythreadfunction below display progressbar shows 1 time , disappears,i not sure how make work.i tried best inspite of fact new threading.please me friends. reading files void readmyfiles() { for(int = 0; < filecount ; filecount++) { cwinthread* mythread = afxbeginthread((afx_threadproc)mythreadfunction,null); tempstate = *(checkstate + index); if(tempcheckstate == nocheckbox) { //my operations } else//checked or unchecked { //myoperation } mythread->postthreadmessage(wm_quit,null,null); } } thread functions uint mythreadfunction(lparam lparam) { hwnd dialogwnd = createwindowex(0,wc_dialog,l"proccessing...",ws_overlappedwindow|ws_visible, ...

How to broadcast using the method of RTP / AVP in VLC -

i need broadcast video stream using rtp/avp method. how vlc? i tried set destination ip 224.0.0.0 , , sap notification. on client can't receive video stream ( rtp://224.0.0.0:5004 ). if looked in wireshark saw server broadcasting , client has connected group 224.0.0.0 . video didn't receive on client. i got same problem if use 192.168.1.0 receve audio stream. i used h.264 + acc (ts) transcoding.

Open a URL in a new tab (and not a new window) using JavaScript -

i'm trying open url in new tab, opposed popup window. i've seen related questions responses like: window.open(url,'_blank'); window.open(url); but none of them worked me, browser still tried open popup window. nothing author can can choose open in new tab instead of new window. user preference . css3 proposed target-new , the specification abandoned . the reverse not true; specifying dimensions window in third argument of window.open , can trigger new window when preference tabs.

php - To make data into table format before exporting to Excel -

i use function below process array data retrieve db, export data excel. # feed final items our formatting function... $contents = get_excel_data($items); function get_excel_data($items){ # set variable $output = null; # check if data items , not empty if (is_array($items) && !empty($items)) { # start row @ 0 $row = 0; # loop items # "foreach(array_values($data) $item)" complicated. "foreach($data $item)" suffice. # foreach(array_values($items) $item) foreach($items $item) { if (is_array($item) && !empty($item)) { if ($row == 0) { # write column headers $output = implode("\t",array_keys($item)); $output .= "\n"; } # create line of values row... $output .= implode("\t"...

jquery - a href nested in DIV element in ASP.NET C# -

my question quite simple, created div, hyperlink control in it. following: <div id="divone" style="width: 500px;"> <asp:hyperlink runat="server" id="hlone" text="hlone" navigateurl="http://www.stackoverflow.com" /> </div> i created onclick event in jquery div well: $('#divone').click(function() { alert('you clicked on div element'); }); my goal trigger event when div area clicked (working fine), but- when hyperlink clicked, need page redirect without triggering div 'onclick' event (can use javascript or jquery needed). thanks all! to this, stop click event bubbling using event.stoppropagation() , this: $('#divone a').click(function(e) { e.stoppropagation(); }); return false; stop bubbling...but stop link being followed, that's why have .stoppropagation() :)

Creating a .bat file -

i trying execute command csrun.exe parameters command prompt. able using command prompt. everytime instead of invoking command prompt, thought of writing batch file, in single click me , forward wants execute. following 1 executing command prompt, want have in batch file c:\program files\windows azure sdk\v1.1\bin> csrun.exe e:\publish\serviceconfiguration.csx e:\publish\serviceconfiguration.cscfg /launchbrowser can suggest me how create batch file invoking command? just put commands in file csrun.exe e:\publish\serviceconfiguration.csx e:\publish\serviceconfiguration.cscfg /launchbrowser and name something.bat

php - Accessing variables from within a function within a class (scopes?) -

i'm new classes, , i've been looking online kind of tutorial on this, unfortunately i've been unsuccessful @ finding solution. guys give me appreciated. i have 2 files. 1) variables.inc.php: $myvar = "hello world"; 2) myclass.php: include("variables.inc.php"); class myclass { function dosomething() { echo "myvar: $myvar"; } } the problem: $myvar returns empty. tried adding line between function dosomething() { , echo...: global $myvar; doesn't seem work way either. suggestions? $myvar defined in global scope. if needs accessed then function dosomething() { global $myvar; echo "myvar: $myvar"; } however usage of global variables in other scopes considered bad practice. see variable scope chapter in official php manual more detailed explanation.

python - Using gobject.timeout_add_seconds - Segmentation Fault -

i writing gui program allows user repeatedly send message phone number configurable delay , number of repetitions. i used qt designer create gui, , trying create code behind it. trying make program start sending messages when start button pressed, not freeze gui. i trying use gobject.timeout_add_seconds check if new messages need send every 1s, when causing segmentation fault. queuemessages called whenever button pressed start sending messages, , sendmessages should run every 1s send needed messages. let me know if there easier way (such threading). open other ideas. here's applicable code. can include gui code if helpful: #!/usr/bin/python2.5 import sys, os import time import gobject pyqt4 import qtgui,qtcore smsbomb import * class myform(qtgui.qmainwindow): def __init__(self, parent=none): #build parent user interface qtgui.qwidget.__init__(self, parent) self.ui = ui_mainwindow() self.ui.setupui(self) # create button...

sql - How to show values from two different queries? -

i have 1 database contains of user information including name. there second database contains notes users , contains #id not name. query doing retrieve user notes doesn't have name doing showing notes, right under doing query retrieve name first database using common #id. won't show. is there way can query in one? please help. thanks. use: select u.name, n.* db2.notes n left join db1.users u on n.id = u.id order u.name assuming connection credentials has access both databases, prefix database name in front of table name , separate period. the left join show both users, , notes without users associated. here's good primer on joins .

MYSQL Query using SUM -

how can make select 7500 or greater on_hand value column? " list part number part descrtiption , onhand value each part on hand value @ least $7,500. assign on_hand_values computed column." this have far, tried subquerys in statements cant figure out. select part_num, description, sum(on_hand * price) on_hand_value part sum(on_hand * price)'7500' group part_num, description; part table part_num description on_hand class warehouse price at94 iron 50 hw 3 24.95 bv06 home gym 45 sg 2 794.95 cd52 microwave oven 32 ap 1 165.00 dl71 cordless drill 21 hw 3 129.95 dr93 gas range 8 ap 2 495.00 dw11 washer 12 ap 3 399.99 fd21 stand mixer 22 hw 3 159.95 kl62 dryer 12 ap ...

templates - Django simple_tag and setting context variables -

im trying use simple_tag , set context variable. using trunk version of django from django import template @register.simple_tag(takes_context=true) def somefunction(context, obj): return set_context_vars(obj) class set_context_vars(template.node): def __init__(self, obj): self.object = obj def render(self, context): context['var'] = 'somevar' return '' this doesnt set variable, if similar @register.tag works object parameter doesn't pass through... thanks! you mixing 2 approaches here. simple_tag merely helper function, cuts down on boilerplate code , supposed return string. set context variables, need (at least plain django) write own tag render method. from django import template register = template.library() class foonode(template.node): def __init__(self, obj): # saves passed obj parameter later use # template.variable, because way can resolved # against cur...

Is there a code for concactenantion in SQL? -

i have record in database: column1 column2 1 1 b 1 c and result be: column1 result 1 abc i want query not use loop :) for ms sql use: declare @result varchar(1000) set @result = '' select @result = (@result + column2) mytable column1 = 1 select @result

c - Make select() crack without writing to a file desc? -

i have thread in application monitors set of client sockets. use select() block until client makes request, can handle efficiently without multiplying threads. now, problem is, when add new client list of clients, have wait timeout of select() (set 10 seconds) add new socket listened sockets. so i'd make select() crack before timeout client can listened immediately. i have solution that: create dummy socketpair include in listened sockets list, , in write make select() crack, i'm hoping there's better solution out there. edit : have no access eventfd() because glibc use old (and have no mean update it). might have use fifo or socket. do know any? thanks! the usual way of waking select loop add read end of pipe() fd pair select's watching set. when need wake select loop, write dummy data write end of file descriptor. note on linux might want consider using eventfd() instead of pipe() - may more efficient (although less portable). you...

sql - many-to-many query -

i have problem , dont know better solution. okay, have 2 tables: posts(id, title), posts_tags(post_id, tag_id). have next task: must select posts tags ids example 4, 10 , 11. not exactly, post have other tags @ same time. so, how more optimized? creating temporary table in each query? or may kind of stored procedure? in future, user ask script select posts count of tags (it 1 tag or 10 @ same time) , must sure method choose best method problem. sorry english, thx attention. this solution assumes (post_id, tag_id) in post_tags enforced unique: select id, title posts inner join post_tag on post_tag.post_id = posts.id tag_id in (4, 6, 10) group id, title having count(*) = 3 although it's not solution possible tag combinations, it's easy create dynamic sql. change other sets of tags, change in () list have tags, , count(*) = check number of tags specified. advantage of solution on cascading bunch of joins don't have add joins, or terms, when ...

java - Help installing PMD Eclipse plugin -

i trying install pmd onto eclipse helios installation. follow usual instructions use 'install new software' feature within eclipse. seems go swimmingly , installation completes. after restarting eclipse, option use pmd not there expected (by right-clicking on project). could advise on steps may have missed? eclipse 20100617-1415 version installed on red hat running kde. any guidance appreciated. thanks either pmd plugin had error on installation, or there problem when trying start plugin up. either way, there should in error log. i'd first check there see if relevant in log (open error log view). if not, can check see if plugin installed. click on -> eclipse -> installation details -> plugins , pmd. if installed, try uninstalling , reinstalling it. if pmd plugin not installed, failed. make sure eclipse/ directory writable current user (while not hard requirement, many plugins need reason).

php - Check similar images -

we have 2 images different (or not) pictures. how check php, images same or not? width , height of images 100x100. option equal. should check draw , colors. which 1 of php libraries can recommend job? gd library. there no easy way "is picture same or not?" can compare pixel pixel, @ individual rgba values... if 1 darker? etc.. have come own algorithms checking stuff that.

F# function calling syntax confusion -

i have piece of code: links |> seq.map (fun x -> x.getattributevalue ("href", "no url")) which wanted rewrite to: links |> seq.map (fun x -> (x.getattributevalue "href" "no url")) but f# compiler doesn't seem that. under impression these 2 function calls interchangeable: f (a, b) (f b) the error is: the member or object constructor 'getattributevalue' taking 2 arguments not accessible code location. accessible versions of method 'getattributevalue' take 2 arguments. which seems amusing, seems indicate needs i'm giving it. missing here? a usual function call in f# written without parentheses , parameters separated spaces. simple way define function of several parameters write this: let add b = + b as pascal noted, way of specifying parameters called currying - idea function takes single parameter , result function takes second parameter , returns actual result (or f...

objective c - Custom UIButton + subviews = no events -

basically have custom uibutton , custom button contains subviews. if add subviews uibutton, button stops responding event changes. i.e if tap on it doesn't respond selector. have set userinteractionenabled . tried adding touchbegan , working. if remove subviews, uibutton works again. how tap events button? the subviews should have userinteractionenabled set no . happening here subviews getting touch events instead of uibutton. if doesn't work option override hittest:withevent: in custom uibutton returns , not ask subviews if should handle event. see uiview docs more details.

PostgreSQL: VACUUM FULL or CLUSTER? -

i'm out of disk space because of query tried update every row in huge table. don't have enough space cluster (though barely fit if dropped indexes first , recreated them afterwards). how can estimate how long vacuum take? how vacuum full ? how 3 (with cluster ) compare in terms of running time , disk usage? it's postgresql 8.3. use cluster, until 8.4 vacuum full broke. if takes long might dump , reload table.

java - J2EE/EJB + service locator: is it safe to cache EJB Home lookup result? -

in j2ee application, using ejb2 in weblogic. to avoid losing time building initial context , looking ejb home interface, i'm considering service locator pattern . but after few search on web found if pattern recommended initialcontext caching, there negative opinion ejb home caching. questions: is safe cache ejb home lookup result ? what happen if 1 cluster node no more working ? what happen if install new version of ejb without refreshing service locator's cache ? is safe cache ejb home lookup result ? yes. what happen if 1 cluster node no more working ? if server configured clustering/wlm, request should silently failover server in cluster. routing information encoded in stub ior. what happen if install new version of ejb without refreshing service locator's cache ? assuming update bean , not component or home interfaces, continues work. ejbhome stateless session bean, request can continue accessed same server if av...

PHP Doctrine 1.2 Using Nested Set , how moving a node in different situation -

i use nested set doctrine 1.2. here example. i got tree category 1 category 1.1 category 1.2 category 1.3 category 1.4 category 2 category 2.1 category 2.1.1 category 2.1.2 category 2.1.3 situation 1 - how can move category 1.3 on top of category 1.1 2 - how can move category 1.4 inside category 1.3 3 - how can move 2.1 , child inside category 1 , next category 1.1 situation 1 give me: category 1 category 1.3 category 1.1 category 1.2 category 1.4 ... situation 2 give me: category 1 category 1.1 category 1.2 category 1.3 category 1.4 ... situation 3 give me: category 1 category 1.1 category 2 category 2.1 category 2.1.1 category 2.1.2 category 2.1.3 category 1.2 category 1.3 category 1.4 see http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_node_interface.html please note original question not entirely correct: in case 3) said...

c# - How to parse string with hours greater than 24 to TimeSpan? -

how parse string 30:15 timespan in c#? 30:15 means 30 hours , 15 minutes. string span = "30:15"; timespan ts = timespan.fromhours( convert.todouble(span.split(':')[0])). add(timespan.fromminutes( convert.todouble((span.split(':')[1])))); this not seem elegant. if you're format "hh:mm" try this: string span = "35:15"; timespan ts = new timespan(int.parse(span.split(':')[0]), // hours int.parse(span.split(':')[1]), // minutes 0); // seconds

iphone - Add UITextField on UIView programmatically -

how programmatically add uitextfield on uiview in iphone programming? uitextfield* text; uiview* view = [[uiview alloc]init]; [view addsubview:???]; objective-c: cgrect somerect = cgrectmake(0.0, 0.0, 100.0, 30.0); uitextfield* text = [[uitextfield alloc] initwithframe:somerect]; uiview* view = [[uiview alloc] initwithframe:somerect]; [view addsubview:text]; swift: let someframe = cgrect(x: 0.0, y: 0.0, width: 100.0, height: 30.0) let text = uitextfield(frame: someframe) let view = uiview(frame: someframe) view.addsubview(text)

f# - how to XML-Serialize array of an array in FSharp -

here's i'm looking for: <reports> <parameters> <parameter name="srid" type="java.lang.integer">16533</parameter> <parameter name="pmid" type="java.lang.integer">17018</parameter> <parameter name="start" type="java.text.simpledateformat">1/1/2011 12:00:00 am</parameter> <parameter name="end" type="java.text.simpledateformat">1/31/2011 12:00:00 am</parameter> </parameters> <parameters> <parameter name="srid" type="java.lang.integer">16099</parameter> <parameter name="pmid" type="java.lang.integer">17018</parameter> <parameter name="start" type="java.text.simpledateformat">1/1/2011 12:00:00 am</parameter> <parameter name="end" type="java.text.simpledateformat">1/31/201...

ruby on rails - Paperclip Resize to fit a rectangular box -

i have rectangular image example 30x800 pixels how can scale paperclip preserve aspect ratio 100x100 pixel image borders filling empty area ? an example : http://www.imagemagick.org/usage/thumbnails/pad_extent.gif has_attached_file :image, :styles => { :thumb => "100x100>" }, :convert_options => {:thumb => "-gravity center -extent 100x100"} or not white background has_attached_file :image, :styles => { :thumb => "100x100>" }, :convert_options => {:thumb => "-background red -gravity center -extent 100x100"}

c# - WPF full screen on maximize -

i want have wpf window go in full screen mode, when f11 pressed or maximize button in right top corner of window pressed. while following works charm pressing f11: private void window_keydown(object sender, keyeventargs e) { if (e.key == key.f11) { windowstyle = windowstyle.none; windowstate = windowstate.maximized; resizemode = resizemode.noresize; } } this still displays windows taskbar (tested windows 7): protected override void onstatechanged(eventargs e) { if (windowstate == windowstate.maximized) { windowstyle = windowstyle.none; windowstate = windowstate.maximized; resizemode = resizemode.noresize; } base.onstatechanged(e); } what missing here? or can more elegant? wpf seems making decision whether go full-screen or respect taskbar based on windowstyle @ time of maximisation. kludgy effective solution switch window non-maximised, set windowstyle, , set window maximised again: pr...

c - dealing with array of linked list -

my approach: an array of fixed-length (lets 20) each element pointer first node of linked list. have 20 different linked list. this structure: struct node{ char data[16]; struct node *next; }; my declaration array struct node *nodesarr[20]; now add new node 1 of linked list, this: struct node *temp; temp = nodesarr[i]; // declared , less 20 addnode(temp,word); // word declared (char *word) , has value ("hello") the addnode function: void addnode(struct node *q, char *d){ if(q == null) q = malloc(sizeof(struct node)); else{ while(q->next != null) q = q->next; q->next = malloc(sizeof(struct node)); q = q->next; } q->data = d; // must done using strncpy q->next = null; } and print data array of linked list, this: void print(){ int i; struct node *temp; for(i=0 ; < 20; i++){ temp = nodesarr[i]; while(temp != null){ ...

c++ - Convert char array to unsigned char* -

is there way convert char[] unsigned char* ? char buf[50] = "this test"; unsigned char* conbuf = // should add here although may not technically 100% legal work reinterpret_cast<unsigned char*>(buf) . the reason not 100% technically legal due section 5.2.10 expr.reinterpret.cast bullet 7. a pointer object can explicitly converted pointer object of different type. original type yields original pointer value, result of such pointer conversion unspecified. which take mean *reinterpret_cast<unsigned char*>(buf) = 'a' unspecified *reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a' ok.

c - Windows 7 dsound.dll load from dll crash -

i'm getting crash when loading dsound.dll dll in windows 7. following code crashes: #include <windows.h> #include <mmreg.h> #include <dsound.h> #include <assert.h> hresult (winapi *pdirectsoundenumeratea)(lpdsenumcallbacka pdsenumcallback, lpvoid pcontext); hmodule hdsound; bool callback dsenum(lpguid a, lpcstr b, lpcstr c, lpvoid d) { return true; } void crashtest() { hresult hr; hdsound = loadlibrarya("dsound.dll"); assert(hdsound); *(void**)&pdirectsoundenumeratea = (void*)getprocaddress(hdsound, "directsoundenumeratea"); assert(pdirectsoundenumeratea); hr = pdirectsoundenumeratea(dsenum, null); assert(!failed(hr)); } bool apientry dllmain(handle hmodule,dword ul_reason_for_call,lpvoid lpreserved) { if (ul_reason_for_call == dll_process_attach) { disablethreadlibrarycalls(hmodule); crashtest(); } } with error code: unhandled exception @ ... in ...: 0xc0000005: a...

c# - html from code behind -

i want insert html few controls +style code behind ( asp.net c#) how can ? you use <asp:placeholder> add controls this. e.g. image img = new image(); img.imageurl = "/someurl.jpg"; img.cssclass = "someclass"; img.id = "someid"; img.alternatetext = "alttext" plageholderid.controls.add(img); this produce html <img src="/someurl.jpg" class="someclass" id="someid" alt="alttext" /> you can control, literal, hyperlink, button, table, etc...

objective c - iPhone - Strike out text for firmware 3.0 -

i strike out text of uitableview on iphone firmware 3.0. i posted one: iphone - strike out nsstring , didn't answer firmware < 3.2. thanks.

Prevent screen rotation on Android -

i have 1 of activities prevent rotating because i'm starting asynctask, , screen rotation makes restart. is there way tell activity "do not rotate screen if user shaking phone mad"? add android:screenorientation="portrait" <activity> element/s in manifest or landscape , you're done.

stored procedures - Delete all but 5 newest entries in MySQL table -

i have php code handles logic because not know how handle in sql. want create stored procedure delete rows except 5 newest given config_id. ie config_id = 5 gets passed sp knows config_id looking clean up. create table `taa`.`runhistory` ( `id` int(11) not null auto_increment, `start_time` datetime default null, `stop_time` datetime default null, `success_lines` int(11) default null, `error_lines` int(11) default null, `config_id` int(11) not null, `file_id` int(11) not null, `notes` text not null, `log_file` longblob, `save` tinyint(1) not null default '0', primary key (`id`) ) engine=innodb auto_increment=128 default charset=utf8; newest determined start_time, if stop_time null not newest should deleted (stop_time can null if run unceremoniously killed). here's procedure tested on mysql 5.1.46, uses no subqueries won't error no support limit in subquery. create procedure deletebut5(in c int) begin declare int; declare s ...

c# - How do you create a generic method in a class? -

i trying follow dry principle. have sub looks this? private sub dosupplymodel outputline("item summaries") dim itemsumms new supplymodel.itemsummaries(_currentsupplymodel, _excelrows) itemsumms.fillrows() outputline("") outputline("numbered inventories") dim numinvs new supplymodel.numberedinventories(_currentsupplymodel, _excelrows) numinvs.fillrows() outputline("") end sub i collapse these single method using generics. record, itemsummaries , numberedinventories both derived same base class databuilderbase. i can't figure out syntax allow me itemsumms.fillrows , numinvs.fillrows in method. fillrows declared public overridable sub fillrows in base class. thanks in advance. edit here end result private sub dosupplymodels() dosupplymodeltype("item summaries",new datablocks(_currentsupplymodel,_excelrows) dosupplymodeltype("data...

c# - Cannot access a disposed object -

i facing huge problem "cannot access disposed object. object name: 'treeview'." error. on windows forms of mine use custom windows explorer object . and here come code parts... on selected node event, load images found within selected directory flowlayoutpanel. private sub exptree1_exptreenodeselected(byval selpath string, byval item explorercontrols.cshitem) handles exptree1.exptreenodeselected 'loop until images loaded. loadimagestoflowpreviewpanel() end sub on button close event private sub wizardcontrol1_cancelclick(byval sender system.object, byval e system.componentmodel.canceleventargs) handles wizardcontrol1.cancelclick me.close() end sub on form closing event private sub wizard_formclosing(byval sender object, byval e system.windows.forms.formclosingeventargs) handles me.formclosing select case xtramessagebox.show("exit application?", me.text, messageboxbuttons.yesno, messageboxicon....

amazon s3 - Ruby on Rails, Paperclip, Heroku, GitHub and AWS - securing keys -

i'm using ror hosted heroku , i'd store files on s3 using paperclip. source code hosted on github , world readable. best practice keep keys secret rest of world? paperclip suggests access keys stored in configuration file (or in code), example have: file: config/s3.yml access_key_id: my_access_key_id secret_access_key: my_very_secret_key bucket: bucket_name heroku works committing code local git , pushing heroku. since i'm using github, push same code github well. means push secret keys there too. i'm using world-readable github account, if payed github make half problem go away still i'm not happy secret keys lying in configuration file in code. don't know if there's better practice though. what best practice keeping keys secret , still using above mentioned list of libraries , services? btw, i've started ror , heroku last week may considered newbe, please considerate ;) thanks! you need use env variable heroku app. if heroku...

How do I do an "OR" for my python regex? -

re.compile("abc") i "abc" or "xyz". use | : re.compile("abc|xyz") it's worth perusing regular-expression.info detailed information regular expression howto , re — regular expression operations python documentation.

Facebook Likes Same for *every page* (with querystrings) -

i'm trying have different pages on same website (all distinguished querystrings load different content) have own number of likes. problem is, have same number of likes no matter do. opengraph meta tags different on each page yet somehow facebook recognises them same page , when 1 gets likes, main 1 (without query strings) gets likes. what going on? when write out button, encoding "?" correctly? make sure urlencode() whole url param (if in php). put url in here see button source http://developers.facebook.com/tools/lint/

sql server - converting string to datetime -

hey guys, want convert datetime string, have string contains 'getdate' want convert same in datetime, string in sql server been defined varchar(max) please reply how can type cast getdate() function string datetieme. regards abbas electricwala i guess mean have string contains text getdate() this. declare @s varchar(50) set @s = 'getdate()' and want turn date variable executing getdate() . you since know what getdate() means. declare @s varchar(50) set @s = 'getdate()' declare @d datetime set @d = (select case @s when 'getdate()' getdate() else null end) does not make sense, there more telling.

performance - Cycles/byte calculations -

in crypto communities common measure algorithm performance in cycles/byte. question is, parameters in cpu architecture affecting number? except clockspeed ofcourse :) two important factors are: the isa of cpu, or more how closely cpu instructions map operations need perform - if can perform given operation in 1 instruction 1 cpu requires 3 instructions on cpu first cpu probably faster. if have specific crypto instructions on cpu, or extensions such simd can leveraged, better. the instruction issue rate of cpu, i.e. how many instructions can issued per clock cycle

Is this an edge case in PowerShell's type resolution mechanism? -

here's situation. have powershell module imports powershell-json library; library converts json strings powershell objects. module provides interface couchdb, json strings obtained http calls. have function, send-couchdbrequest , makes http request couchdb , returns response data string (the response data obtained using streamreader.readtoend() ). in function, get-couchdbdocument , make call send-couchdbrequest, , save output in variable, $json . according $json.gettype() , $json | get-member , of type system.string . if feed string convertfrom-json , expect pscustomobject properties defined according json document supplied it; instead, string representation of powershell hashtable, i.e., @{name1=value; name2=value2; name3=value3} . object returned of type system.string based on same tests above, rather expected pscustomobject . seems me powershell doing kind of automatic (and unwanted/unneeded) type conversion here. the bug isn't in powershell-json - i'...

operating system - What's the difference between "virtual memory" and "swap space"? -

can 1 please make me clear difference between virtual memory , swap space ? and why 32-bit machine maximum virtual memory access 4 gb only? there's excellent explantation of virtual memory on over superuser . simply put, virtual memory combination of ram , disk space running processes can use. swap space portion of virtual memory on hard disk, used when ram full. as why 32bit cpu limited 4gb virtual memory, it's addressed here : by definition, 32-bit processor uses 32 bits refer location of each byte of memory. 2^32 = 4.2 billion, means memory address that's 32 bits long can refer 4.2 billion unique locations (i.e. 4 gb).

objective c - NSScrollView frame and flipped documentView -

i have problems nsscrollview, not displayed way want. yes know there lot of post around web, need override isflipped, in order make return yes, in nsview subclass. ok, it's done, now, scrollview scroll top bottom, , not in reverse way, before overriding isflipped. but, second part, real problem, didn't found answer on web, how hell i'm supposed code, or create view in interface builder, if flipped? if put @ top, displayed bottom… have magic trick handle that? and last problem, nsscrollview frame. before setting documentview of scroll view, fine, scrollview displayed @ place choose, but, when set document view, looks scrollview frame looks bigger, have resize it…. normal behavior? thank much. the answer create nsclipview subclass returns yes override of isflipped: then in ib, set scroll view's content view (clip view) subclass.

c# - How to use linq to find the minimum -

this question has answer here: how use linq select object minimum or maximum property value 10 answers i have class { public float score; ... } , ienumerable<a> items , find a has minimal score. using items.min(x => x.score) gives minimal score , not instance minimal score. how can instance iterating once through data? edit : long there 3 main solutions: writing extension method (proposed svish). pros : easy use , evaluates score once per item. cons : needs extension method. (i choosed solution application.) using aggregate (proposed daniel renshaw). pros : uses built-in linq method. cons : obfuscated untrained eye , calls evaluator more once. implementing icomparable (proposed cyberzed). pros : can use linq.min directly. cons : fixed 1 comparer - can not freely choose comparer when performing minimum computation. have @ minby exte...

oop - Abstract attributes in Python -

what shortest / elegant way implement following scala code abstract attribute in python? abstract class controller { val path: string } a subclass of controller enforced define "path" scala compiler. subclass this: class mycontroller extends controller { override val path = "/home" } python has built-in exception this, though won't encounter exception until runtime. class base(object): @property def path(self): raise notimplementederror class subclass(base): path = 'blah'

amazon ec2 - During hardware failure, do EBS-based EC2 instances terminate or stop? -

amazon's new ebs-based ec2 instances have 2 options shutdown: terminate or stop. stopped instances can later started again, automatically continuing same ebs root disk state had when stopped. but happens when amazon datacenter has hardware failure, , ec2 instance forced shutdown. terminate or stop? if instance has been configured stop default on shutdown, can rely on being stopped in situation, , being able start again later? an ec2 instance can terminated @ time , 1 must account indeed, mentioned in david's answer (+1). can arrange failed instance's elastic block store (ebs) remain available regardless though, see e.g. respective faq what happens data when system terminates? : the data stored on local instance store persist long instance alive. however, data stored on amazon ebs volume persist independently of life of instance. if using amazon ebs volume root partition, you have set delete on terminate flag "n" amazon ebs volume pe...

javascript - IPad Disable keyevent on input -

i working on solution implements adding text textboxes disable normal key events , use custom one. disable key event this: <input onkeypress="return false;" onkeydown="return false;" onkeyup="return false;" type="text"> now works fine on browsers(safari, firefox, ie) fails on ipad's safari , when user press key, entered twice. there way disable key events on input field ipad? maybe can make textbox transparent (alpha:0), place inside div, , add text div behind textbox.

jQuery, get datas in AJAX (done) then, display them as star (error) -

i'm using star rating, 100% working except when insert values javascript : example : http://www.gamer-certified.fr/test.html <script type="text/javascript"> jquery(document).ready(function() { jquery.ajax({ type: "get", datatype: "jsonp", url: "http://www.gamer-certified.fr/export/widget.php", data: {demandeur: "esl" }, cache: true, success: function(data, textstatus, xmlhttprequest){ var obj = null, length = data.length; (var = 0; < length; i++) { widget = "<span class='stars'>"+(data[i].qualite / 2)+"</span>" // automatic not working widget = "<span class='stars'>4</span>" // manually not working jquery('#gamer-certified'+i).html(widget); } } }); }); </script> the thing working putting directly data in span value ...

substring - PHP substr Query - Cropping URL -

i have string: "/en/sports/football/" how substr string achieve: "/sports/football/" many pointers. well, lets take look: http://php.net/manual/en/function.substr.php the method signature looks this: string substr ( string $string , int $start [, int $length ] ) if length omitted, substring starting start until end of string returned. so guess characters 3 , onward. substr("/en/sports/football/", 3);

error handling - CakePHP - How to use onError in Model -

i've created custom datasource fetches data web api, , i'm looking @ implementing error handling. in datasource, i'm calling $model->onerror(). in model, i've created onerror method, , can access error details $this->getdatasource()->error; however can't redirect or set flash message because can take place in controller, should doing here communicate error user? are errors relevant fields in model? if so, use $this->invalidate($field, $message) in model::onerror()

python - Subprocess Popen invalid argument/broken pipe while communicating to C program -

i have code all needed libraries imported class vertex(structure): _fields_ = [("index", c_int), ("x", c_float), ("y", c_float)] other stuff this create , array list of vertex def writelist_buf(size, nomeid): nvert_vertex_array_type = vertex * len(bpy.data.objects[nomeid].data.vertices) passarr = nvert_vertex_array_type() in range(len(passarr)): vert = bpy.data.objects[nomeid].data.vertices[i] passarr[i] = vertex(vert.index, vert.co[0], vert.co[1]) return passarr bpy.data.objects[nomeid].data.vertices list of vertices. other stuff this inside def, , communicate c program previous array input = writelist_buf(size, nomeid) c_program_and_args = "here program arguments(it works)" cproc = popen(c_program_and_args, stdin=pipe, stdout=pipe) out, err = cproc.communicate(input) #the program returns 2 integers separed space return [int(i) in out.decode.split()] size , nomeid declared before writelis...