Posts

Showing posts from September, 2015

sql server - Is there a ternary operator in T-Sql? -

or alternatives implement next query: select * table isexternal = @type = 2 ? 1 : 0` use case : select * table isexternal = case @type when 2 1 else 0 end

python - django logging set context globally per request? -

lets want log formatting string : %(levelname)s %(asctime)s %(module)s %(funcname)s %(message)s %(user_id) it can done using type of logging command : logging.error('error fetching information', = { 'user_id': 22 } ) this add current userid logging messages current request. but dict needs added every logging call. is there way add context in common function in django (eg middleware, or index function of view ), dictionary user id set, , further logging calls in current request log current user. there exists threadlocal middleware on https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/threadlocal.py helps issue in making current request available everywhere. so need add middleware middleware_classes setting, , create function somewhere this: django_tools.middlewares import threadlocal def log_something(levelname, module, funcname, message): user = threadlocal.get_current_user() # logging here. "user&qu

python - In pygtk, how can I combine font selection and color selection dialogs in one dialog? -

i'm using pygtk , searches best way combine font , color dialogs in one, pythonic way ? you must change 'base' , 'text' parts of widget's style. can edit 'foreground' property. useful shorthand methods change style properties inherited gtk.widget are: widget.modify_fg(state, color) widget.modify_bg(state, color) widget.modify_base(state, color) widget.modify_text(state, color) windowless widgets such gtk.label, gtk.button, gtk.paned, gtk.frame, etc, (see faq 3.5) despite inheriting gtk.widget don't allow changing background , base color properties don't exist them. if want them need insert widget inside gtk.eventbox adds properties. example: import gtk window = gtk.window(gtk.window_toplevel) window.connect("destroy", gtk.mainquit) label = gtk.label("one, two, testing...") eb = gtk.eventbox() eb.add(label) eb.modify_bg(gtk.state_normal, gtk.gdk.color_parse("blue")) window.add(eb) window.show_al

.net - Are the method names and parameter names case sensitive in a SOAP message -

if change case of method name , parameters, adversely affect clients making use of asmx or wcf web service? public string getstring(int input) { return input.tostring(); } to.... public string getstring(int input) { return input.tostring(); } would clients needed regenerate proxy objects make use of changed methods? yes, parameters names on server side should match (including case) parameter names, defined in operation contracts. method names. if need control on - can use messageparameterattribute from msdn : the value of parameter names in operation signature are part of contract , case sensitive . use attribute when need distinguish between local parameter name , metadata describes operation client applications.

bash - how to stop shell script from getting confused by ack PATTERN escapes -

i trying use ack search (in haskell files) +|+ i looked @ ack-grep: chars escaping doesn't help on mac os x 10.6 following responses: $ ack -q +|+ -bash: +: command not found missing option after + ack: see ack --help, ack --help-types or ack --man options $ ack \+\|\+ unknown option: | ack: see ack --help, ack --help-types or ack --man options $ ack [+][|][+] -bash: ][+]: command not found ack: invalid regex '[+][': unmatched [ in regex; marked <-- here in m/[+][ <-- here / $ ack \q+|+\e -bash: +e: command not found that's suggestions in q&a listed above this should work intended: $ ack "\+\|\+" (edited correct per comments. unquoted pipe 'or'.)

html - Opening a popup window based on selected dropdown option -

what i'm trying create simple form dropdown list , submit button. upon selecting option dropdown list, user clicks submit button , popup window opens allows them view more info option selected. right have: <form action="example.php" method="post" target="_blank"> <select size="7" name="identifier" style="width: 100%;"> <option> options.... </option> </select> </form> now 'work' in when user selects option , presses submit, opens new window selected option post data passed along. open smaller popup window size can define rather whole new window. i'm aware target=_blank deprecated i'm wondering preferred way achieve now? here link may solve problem (stackoverflow link) : how show popup if select "option" in "select" dropdown using javascript?

sql - Multiple row insert into two tables avoiding loops -

i have set of value have inserted 2 tables.input has 5 row , have insert these 5 rows table first.table has identity column.next have insert these 5 rows table b column identity table a. how can done out using loops? highly helpful. insert table_a(col2,col3) select col2,col3 #temp_tab set @identityval=@@identity insert table_b(cola,colb,colc) select @identityval,col2,col3,col4 #temp_tab you cannot insert multiple tables using single statment. what create insert trigger on table after insert occurs performs new insert identity of value inserted table , insert table b.

c# - Check if SELECT statement conditions are true -

string test = "select count(*) table email=@email , active=@active"; hello, possible using c# check if both of conditions true or if 1 of them true? int count = testcmd.executenonquery(); i have tried using code above not sure understand how works.. count 1 if both conditions true ? try: string test = " select count(*) from( select case when (select count(*) table email=@email , active=@active)>0 1 else null end num union select case when (select count(*) table email=@email or active=@active)>0 1 else null end num )x num not null" which returns 2 if both conditions true, 1 if 1 of them true , 0 if both false. and use executescalar() instead of executenonquery() (which returns number of rows effected). i.e. int count = (int32)testcmd.executescalar();

javascript - Why I get error 'Cannot set property '0' of undefined' -

i not understand why can not create new object the error: uncaught typeerror: cannot set property '0' of undefined i got error on line code. this.gameanimals[i] = {}; this = game; gameanimals[0] = 'frog'; so why have error ? many thanks. var game = { init: function(){ this.property1 = 1; this.property2 = 2; this.property3 = 3; this.property1000 = 1000; }, cons: function(gameanimals){ for(var = 0; < gameanimals.length; i++){ this.gameanimals[i] = {}; } }, }; var gameanimals = ['frog', 'lion', 'cat']; game.cons(gameanimals); you trying set zero-th element of this.gameanimals . however, this.gameanimals doesn't exist, since game object doesn't have private member gameanimals . hence it's undefined , try set property on. i think may mean gameanimals , without prefixing this . (alternatively, you'll need create this.

magento - Product page tabs for short_description and description attribute -

i using magento 1.7.0.2 i add tabs short_description , description attribute in product page. attributes text. i tried extensions east tabs has 1 conflict javascript files , cant add tab short_description attribute. how can ? create custom theme app/design/your_theme/template/catalog/product/view/tabs.phtml , add following code this: http://www.woolleydesign.net/2012/07/magento-adding-tabs-to-your-product-pages/ this link create tab..

ios - UIButton setSelected: NO doesnt show default background image -

i have custom uibutton 2 background images: in default state: default.png in selected state: selected.png set in xib file. this gets invoked on button touch down: -(ibaction)numberselected:(id)sender{ nslog(@"button pressed %@",[sender currenttitle]); uibutton* button = (uibutton*)sender; button.selected = !button.selected; [button release]; } the wrong behavior this: i press button, background image switches selected.png (correct), press again, , no backgorund image shown. press time, app crashes. knows help? lot in advance. no need release button there. remove [button release];

Exclude all except 1 subdirectory from teamcity checkout rule -

i have vcs root following checkout rules: +:. -:externals +:externals/jquery however teamcity doesn't seems checkout externals/jquery directory. there anyway achive this, except creating separate vcs root directory? i'm using teamcity 8.0 latest eap. update (2017) since teamcity 10 it's seems it's possible question asking +:**/* => target_directory -:**/folder1 => target_directory if want checkout externals/jquery directory , nothing else, add in checkout conditions . +:externals/jquery -> jquerydir(custom name) or +:externals/jquery -> .

tsql - Vim - custom syntax - how to match second word -

i'm trying make custom syntax highlighting sybase t-sql , i'm stuck when try match table name in following line: update mytablename i've tried: syn match tsqlupdatetablename "\w\+" contained syn match tsqlupdateline "update.*" nextgroup=tsqlupdatetablename hi tsqlupdatetablename guifg=white guibg=red but not match mytablename appreciate help. cheers! the problem nextgroup matches after current group's match. you can fix excluding table name in line match, either dropping .* or, i've done here, asserting following table name ending match \ze : syn match tsqlupdatetablename "\w\+" contained syn match tsqlupdateline "update \ze\w\+" nextgroup=tsqlupdatetablename alternatively, can include table name in line match , use contains= instead: syn match tsqlupdatetablename "update \zs\w\+" contained syn match tsqlupdateline "update \w\+" contains=tsqlupdatetablename ps: should t

Reading messages from a serial port with Boost Asio -

i use boost asio read variable length messages serial port. read , wait long enough sure line idle, not want block completely. the following code have far, , in process of testing it: long readdata(void *_pdata, unsigned long _usize, size_t millis) { size_t n = 0; // n return message size. if (millis > 0) // millis acceptable idle time, 0 invalid in case. { size_t ubytestransferred = 0; boost::asio::deadline_timer timeout(m_ioservice); readcallback readcallback(ubytestransferred, timeout); waitcallback waitcallback(m_port); while (_usize - (unsigned long)n > 0) { // setup asynchronous read timeout m_ioservice.reset(); m_port.async_read_some(boost::asio::buffer((char*)_pdata + n, _usize - (unsigned long)n), readcallback); timeout.expires_from_now(boost::posix_time::milliseconds(millis)); timeout.async_wait(waitcallback); // block until

asp.net mvc - How to return Json as part of my view in C# MVC -

my question is: how can combine 2 of these action results one? there seems no point in having first 1 1 line. cant see way out. ideas appreciated. remaining provide background. i trying , successful in returning partial view json results require using 2 actionresults of same name (one parameter 1 without) achieve this. if continue in manner, have repeat actionresults twice. problem have first action result nothing more literally this: [httpget] public actionresult myresults() { return partialview(); } that used return view. within view have jquery/ajax in turn calls action result of same name parameters. action result populates json object parsed , rendered view above table. actionresult work. looks like: [httppost] public actionresult myresults(datatableprameters param) { //get full list of data meets our needs var fulllist = _myresultsrepository.getlistbyid(id); //count records in set int count = fulllist.count();

visual studio - C++ with OpenGL - Drawing a square -

i have make program should draw square change colors. program draw window white background, dimensions of 256x256 pixels, red square upper left vertex coordinate (x, y) = (30, 226) , lower right corner coordinates (x, y) = (226 , 30). when key 'a' (keycode = 97) pressed, square should stick color blue. when 'v' key (keycode = 118) pressed, square should go red. when esc key (keycode = 27) pressed program should terminated. -- there log... build log build started: project: square, configuration: debug|win32 command lines creating temporary file "c:\users\temp\documents\visual studio 2008\projects\square\square\debug\rsp00000544445896.rsp" contents [ /out:"c:\users\temp\documents\visual studio 2008\projects\square\debug\square.exe" /manifest /manifestfile:"debug\square.exe.intermediate.manifest" /manifestuac:"level='asinvoker' uiaccess='false'" /debug /pdb:"c:\users\temp\documents\visual stu

c++ - Install Windows Service and Console Application using a single setup and deployment -

i have created console application works background app in c++ . trying run application through windows service start automatically if app crashed. what can't create windows service can trigger xxx.exe . how can make windows service , background application single setup file installation ?

fuseesb - In a blueprint.xml route, call a propertyplaceholder using an xpath returned value -

i have blueprint.xml in write routes esb. want values xml file passed route. want use these values make dynamic property key name , call properties file , matching property (all within route). want avoid having create java processor due overhead of instantiating each time. want this: <from uri="file:c:/myfilelocation?"/> <to uri= {{<xpath>//company</xpath>+<xpath>//branch</xpath>}}/> so in blueprint call property using {{}} trying place xpath values property key inside of property {{}} tags. in properties file have mapping each company/branch combination so: company1branch1= http://thiscompany.com company2branch2= http://someothercompany.com any way this, e.g. sort of escape characters? the < > static uris, if want use dynamic runtime computed uris, should use recipient list eip: http://camel.apache.org/recipient-list.html allows send message recipient calculcated @ runtime. this describer in faq: htt

jboss7.x - Multiple logger in same class using jboss7 default logging mechanism -

basically need log 2 messages in same class same logger threshold using jboss7 logging mechanism. please let me know how can done in detail? followed approach suggested, , created 2 periodic-rotating-file-handler below <periodic-rotating-file-handler name="file_debug"> <level name="debug"/> <formatter> <pattern-formatter pattern="%d{hh:mm:ss,sss} %-5p [%c] (%t) %s%e%n"/> </formatter> <file relative-to="jboss.server.log.dir" path="file111_debug.log"/> <suffix value=".yyyy-mm-dd"/> <append value="true"/> </periodic-rotating-file-handler> <periodic-rotating-file-handler name="file_info"> <level name="info"/> <formatter> &l

php - How to export image from MSSQL and display it on a website? -

Image
i'm having difficulties getting work. here code i'm using: require_once('db_connection.php'); $query = mssql_query("select photo persons idperson = '3'"); $person = mssql_fetch_array($query); $photo = $person["photo"]; header('content-type: image/jpeg'); echo $photo; this result i'm getting: (there showing on bottom of image, that's part of image) this how image value looks in database: 0x424d3684030000000000360000002800000040010000f000000001001800000000000084030000000000000000000000000000000000fdfef5fcfdf4fffffae3f2da ....... any ideas? you should have use use base64 encoding display image database like <img src="data:image/jpeg;base64,/9j/4aaqskzjrgabaqeawgbaaad/4gxysundx1bst0zjteuaaqeaaaxitglubwiqaab..." /> use, base64 encoding <?php $query = mssql_query("select photo persons idperson = '3'"); $person = mssql_fetch_array($query); $photo =

php - extracted pdf page and pdf files are not uploaded for some of the pdf files -

i use imagemagic/ghostscript script below extract first page of pdf file , convert jpg format , use html form upload the jpg picture along pdf file , other information wamp server. suprise, upload pdf files , goes confirmation page activated when upload successful. some, returns $err message. can please hep me out? <?php include ('head.php'); include ('connect.php'); if(isset($_post['submit'])) { $pdfdirectory = "pdf/"; $thumbdirectory = "pdfimage/"; //get name of file $filename = basename( $_files['pdf']['name'], ".pdf"); //remove characters file name other letters, numbers, hyphens , underscores $filename = preg_replace("/[^a-za-z0-9_-]/", "", $filename).".pdf"; //name thumbnail image same pdf file $thumb = basename($filename, ".pdf"); $title=$_post['title'] ;

winapi - Hooking NtQueryDirectoryFile can't hide files -

i want hide files (in program). decided use ntquerydirectoryfile. files not hidden, code not work. don't use driver, use user mode. can me please? the code snippet: typedef ntstatus (winapi * ntquerydirectoryfile) (in handle filehandle,in handle event optional,in pio_apc_routine apcroutine optional,in pvoid apccontext optional,out pio_status_block iostatusblock,out pvoid fileinformation,in ulong fileinformationlength,in myfile_information_class fileinformationclass,in boolean returnsingleentry,in punicode_string filename optional,in boolean restartscan); ntquerydirectoryfile originalntquerydirectoryfile; #define status_no_such_file 0xc000000f ntstatus hookedntquerydirectoryfile( in handle filehandle, in handle event optional, in pio_apc_routine apcroutine optional, in pvoid apccontext optional, out pio_status_block iostatusblock, out pvoid fileinformation, in ulong fileinformationlength, in myfile_informat

How can shared memory be locked in php (shmop) -

please how can shared memory created in php using shmop (not shm if matters) locked , unlocked? require libraries? it seems shmop_read() runs while shmop_write() still writing because value read has part of old , new values. you cannot explicity lock shared memory segment, can open in exclusive mode, e.g. shmop_open($shm_key, "n", 0644, 100); quoting http://www.php.net/manual/en/function.shmop-open.php "n" create new memory segment (sets ipc_create|ipc_excl) use flag when want create new shared memory segment if 1 exists same flag, fail. useful security purposes, using can prevent race condition exploits.

vba - Interactive Quiz using ppt -

i posted rubbish question before , have gone away , done work on re-ask. i've made ppt quiz counts how many correct , incorrect answers person has given. feeds information user @ end. want happen want results stored can go in , see how each user has performed in quiz. ideally work on 6 networked computers storing quiz results in 1 place. if need can take file each of 6 computers. my code far looks this: dim username string dim numbercorrect integer dim numberwrong integer sub yourname() username = inputbox(prompt:="type name") msgbox " ready begin " + username, vbapplicationmodal, " orange 1c book 7" end sub sub correct() numbercorrect = numbercorrect + 1 activepresentation.slideshowwindow.view.next end sub sub incorrect() numberwrong = numberwrong + 1 activepresentation.slideshowwindow.view.next end sub sub start() numbercorrect = 0 numberwrong = 0 yourname activepresentation.slideshowwindow.view.next end sub sub results() msgbox "we

How to loop through properties of objects in c#? -

i have method gets values of properties of object , appends commas it. want make generinc can use other objects. foreach (var row in rows.tolist()) { sbresult.append( delimiter + row.medianame + delimiter + separator + delimiter + row.countryname + delimiter + separator + delimiter + row.itemoverridedate + delimiter + separator + delimiter + row.rating + delimiter + separator + delimiter + row.batchno + delimiter + separator + delimiter + row.noinbatch + delimiter + separator + delimiter + row.batchdate + delimiter + separator + delimiter + row.datatype + delimiter + separator + delimiter + row.byline + delimiter + separator + delimiter + row.issueno + delimiter + separator + delimiter + row.issue + delimiter + separator +

jquery - Need to fix div when scrolling stay 20px from top -

i not sure wether can done pure css or if need use jquery this. i have div (product_image) in current state sits @ 400px top , positioned relative clears top menu , header, need when user scrolls down , gets 20px top of div, need div become fixed. here's have tried, have main div relative positioning have div wrapping inside fixed positioning. problem div staying put @ 400px top. here's code: <div class="product_image"> <div class="product_image_fixed"> <a href="products/1.jpg" class="zoom" title="a bed!" rel="gal1"> <img src="products/1.jpg" width="450" alt="" title="a bed!"> </a> <ul id="thumblist" class="clearfix" > <li><a class="zoomthumbactive" href='javascript:void(0);' rel="{gallery: 'gal1', smallimage: 'products/1.jpg',la

ios - Like Facebook page on button action -

Image
i'm trying implement page functionality application, i've added latest facebook sdk , implemented delegates , handlers check session , status user login app. working fine here (this done in sample code). anyways, i've found following code facebook developer site, page, doesn't seem work. - (void) likefacebookindia { nsmutabledictionary<fbgraphobject> *action = [fbgraphobject graphobject]; action[@"object"] = @"http://www.facebook.com/facebookindia"; //action[@"object"] = @"facebookindia"; [fbrequestconnection startforpostwithgraphpath:@"me/og.likes" graphobject:action completionhandler:^ (fbrequestconnection *connection, id result, nserror *error) { // handle result if(error) {

android - Where do I put images in the eclipse resource folder? -

under 'res' there several folders, drawable-ldpi drawable-xxhdpi, should put images if want same image on devices? you may put under either of folder regardless of dpi: res/drawable-nodpi res/drawable

Error with sem function at R : differences in factors -

i wanted use function sem (with package lavaan) on data in r : model1<- 'transfer~amotivation+gender+age amotivation~gender+age transfer 4 questions 5 point likert scale amotivation: 4 questions 5 pint likert scale gender: 0 (=male) , 1 (=female) age: different ages and got next error: in getdatafull (data= data, group = group, grow.label = group.label,: lavaan warning: observed variances (at least) factor 100 times larger others; please rescale is familiar error? influence results? have change anything? don't know error means. your scales not equivalent. gender variables constrained either 0 or 1. amotivation constrained between 1 , 5, age less constrained. created sample data gender, age, , amotivation. can see variance age variable on 4,000 times higher variance gender, , 500 times higher sample amotivation data. gender <- c(0,1,1,1,0,0,1,1,0,1,1,0,0,1,1,1) age <- c(18,42,87,12,24,26,98,84,23,12,95,44,54,23,10,16) set.seed(42) amotivatio

gridview - Issue with grids within tabs in extjs -

i have reviewed other posts using grids within tabs , choosing extend/xtype approach... however, getting error when adding reference grid in tab: ext.define('mygrid', { extend: 'ext.grid.panel', alias: 'widget.mygrid', width:425, height:250, collapsible:true, title:'simple listview <i>(0 items selected)</i>', renderto: ext.getbody(), store: store, multiselect: true, viewconfig: { emptytext: 'no images display' }, columns: [{ text: 'file', flex: 50, dataindex: 'name' },{ text: 'last modified', xtype: 'datecolumn', format: 'm-d h:i a', flex: 35, dataindex: 'lastmod' },{ text: 'size', dataindex: 'size', tpl: '{size:filesize}', align: 'right', flex: 15, cls: 'listview-filesi