Posts

Showing posts from May, 2011

performance - Does an unused import declaration eat memory, in Java? -

does unused import - import android.widget.relativelayout; eat memory? want know how or valuable? maybe stupid question, haven't found answer. no don't take memory. imports used compiler resolve class names @ compile time. compiler changes each class name qualified name. , removes import statement. so, import statement doesn't make byte code. the issue can come wildcard import namespace conflict, i.e., when 2 types same name defined in 2 different packages, importing packages wildcards cause name conflict type used. to see how compiler replaces import statement, can generate byte code of class using javap command. consider below code: import java.util.*; import java.util.regex.*; public class test { public static void main(string[] args) { } } just compile above code, , check byte code using following command: javap test it gives out following output: public class test { public test(); public static void main(java.lang.string[]

jquery long-poll not displaying anything -

for reason following not displaying @ - idea did wrong? update 1: index.php $(document).ready(function(){ (function poll(){ $.ajax({ url: \"getdbdata.php\", success: function(data){ document.write(data.timestamp); }, datatype: \"json\", complete: poll, timeout: 30000 }); })(); }); getdbdata.php $response = array(); $response['timestamp'] = time()+microtime(); echo json_encode($response); sleep(1); original code: index.php <?php echo " <html> <head> <script src=\"jquery.min.js\" type=\"text/javascript\" charset=\"utf-8\"></script> <script type=\"text/javascript\"> $(document).ready(function(){ (function poll(){ $.ajax({ url: \"getdbdata.php\", success: function(data){ var json = eval('('+data+')'); if json['timestamp'] != \"\" { document.write(json['timestamp'])

how to disable "bytes_recv = ##; bytes_send = ##" message spam in Visual Studio Output window from C# and NetworkComms.Net app over USB to iPad -

only spams in usb , not wifi . how can stop continuous display (spam) of these messages in out visual studio output window ? have c# app built visual studio 2010 communicates ipad app built xamarin studio monotouch c# . both use networkcomms.net communicate. when connected usb, these debug messages spam output window. when connected wifi, comm ok; there none of these messages. sample of spam messages: bytes_recv = 256; bytes_send = 256 bytes_recv = 256; bytes_send = 256 bytes_recv = 256; bytes_send = 256 bytes_recv = 256; bytes_send = 256 bytes_recv = 72; bytes_send = 72 bytes_recv = 256; bytes_send = 256 bytes_recv = 256; bytes_send = 256 bytes_recv = 256; bytes_send = 256 cannot find messages in our code. cannot find on google. have posted request on networkcomms.net web. i've looked through source networkcomms.net , output reporting not generated within networkcomms.net. recommend investigating other tools using such usb->tcp connection.

forms - how to convert altcodes to html code in php -

i'm working on website have form, if enter text works should if enter special characters ☺ ☻ ♥ ♦ becomes lot of ?? in database. there way convert them html code? example: ♥ convention served &#9829; the function looking htmlentities http://php.net/manual/en/function.htmlentities.php you'll need know encoding input data uses (obviously). default utf8. $encoded = htmlentities( $input, ent_compat | ent_html401, 'utf-8', false ); note i've set final parameter false (default true ). users can type, example, &amp; , convert & . maybe want default behaviour ( &amp; -> &amp; ) the encoding used when sending post data can set in form tag: <form method="post" action="myscript.php" accept-charset="utf-8"> but see here discussion: is there benefit adding accept-charset="utf-8" html forms, if page in utf-8?

string - passing address of variable to a C function -

i'm relatively new c. i'm trying pass address of variable function, , have function assign char pointer variable address passed. compiler doesn't complain, code doesn't work either. typedef enum { val_1, val_2 } member_type; char *a1="test 123"; int func (member_type x, char *temp) { switch(x) { case val_1: temp = a1; return 1; case val_2: return 2; } return 0; } int main(){ member_type b; static char *d1; b = val_1; printf("%p\n",&d1); func(b, &d1); printf("val_1:%s\n",d1); return 0; } i following error when execute it: -bash-3.00$ ./a.out 0x500950 name:(null) can me how fix it? i find strange compiler doesn't complain. suspect compiling without warnings. should compile using -wall option enabled (assuming using gcc or clang). what doing wrong although passing address of char * pointer functi

shared memory - CUDA volatile and threadfence -

what difference between following 2 functions? __device__ inline void comparator_volatile(volatile float &a, volatile float &b, uint dir) { float t; if ((a > b) == dir) { t = a; = b; b = t; } } __device__ inline void comparator(float &a, float &b, uint dir) { float t; if ((a > b) == dir) { t = a; = b; b = t; } __threadfence(); } could me? i implement bitonicsort in different versions based on cuda sdk version. atomic version (bitonicsortatomic), tried use __threadfence() in __syncblocks_atomic maintain memory consistency. doesn't work (the output incorrect). have call comparator_volatile instead of comparator, correct result. idea? bitonicsort benchmark: // (c) copyright 2013, university of illinois. rights reserved #include <stdlib.h> #include <stdio.h> #include "parboil.h" #define threads 256 #define blocks 32 #define num_vals 2*threads*blocks __device__ volatile int mutex = 0; __device__ inl

Explain the following javascript statement? -

this question has answer here: how javascript closures work? 89 answers why need invoke anonymous function on same line? 18 answers var ninja = (function(){ function ninja(){} return new ninja(); })(); i've been learning javascript while now. why function declaration above encapsulated in '('s , why there '();' in end? i can imagine constructor function, because of '();' in end. why object wrapped in simple brackets? this code equivalent to: function ninja() { // nothing here } var ninja = new ninja(); though in code listed, function/object ninja not global scope. the code (function() {...})(); says "take whatever function contained inside here , execute immediately". it's creating anonymous function , c

javascript - walk throught each li child input find value and increase by one other -

gurus! have list of li's <ul> <li><input type="hidden" value="7" name="order"></li> <li><input type="hidden" value="3" name="order"></li> <li><input type="hidden" value="6" name="order"></li> <li><input type="hidden" value="5" name="order"></li> <li><input type="hidden" value="1" name="order"></li> <li><input type="hidden" value="2" name="order"></li> </ul> i want add new li hidden input list , set value of input val+1 - increase 1 finding maximum values of inputs. can me? please favour , use jquery this: var total; $('li').find('input').each(function(){ total = total == undefined || parseint($(this).val()) > total ? parseint($(this).va

ruby on rails - Writing a method that simply multiplies the object by something -

i'm trying convert bunch of numbers imperial metric on front end of site depending on if user has set measurement_units 'metric' or 'imperial' i can @myweight*.45 convert number, want write helper method this def is_imperial? if user.measurement_units == 'metric' *0.453592 elsif user.measurement_units == 'imperial' *1 end end then able this: @myweight*.is_imperial? i'm not sure how assign *value method is_imperial? thanks help! edit: @myweight float calculated adding several numbers. i'm trying find elegant way of converting number shows on site metric if user has metric value in measurement_units field on user model. i assumed need create helper method in application_helper.rb. not correct? if want measurement_units method dynamic based on user, think need make instance method. modify is_imperial? method return right number: def is_imperial? if measurement_units == 'metric'

java - intellij Debugger is not able to connect with Remote VM -

i working on jnlp based application hosted on jboss server. ide intellij . when tried remote debug on port defined on debug console of intellij message written connected target vm, address: 'camelot-dev.kwcorp.com:8787', transport: 'socket' from message, thought connected remote vm , jumped workspace debugging nothing seems working me. when clicked on f6 , respective buttons debugging nothing seems working (no debug happened). checked debug port , correct. not sure whether doing correct thing or not.

c# - Is Marshal.AllocHGlobal() result deterministic? -

let's have code: intptr native_color = marshal.allochglobal (marshal.sizeof (typeof (gdk.rgba))); is memory of native_color initialized zeros? think yes, there of cases in i've detected not case... so, marshal.allochglobal() not deterministic? from documentation marshal.allochglobal method (int32) when allochglobal calls localalloc, passes lmem_fixed flag, causes allocated memory locked in place. also, allocated memory is not zero-filled . if have seen memory returned marshal.allochglobal filled zeros, because there.

java - Why aren't arguments working in eclipse? -

i trying learn how code java , learning arguments using eclipse. reading book sam's teach java in 24 hours , following book completely; however, not working in eclipse. code following: public class blankfiller { public static void main(string[] args) { system.out.println("the " + arguments[0] + " " + arguments[1] + " fox " + "jumped on " + arguments[2] + " dog."); } } then put arguments in going run → run configurations → arguments , type in "retromingent purple lactose-intolerant" program arguments tab, hit apply run gives me error: exception in thread "main" java.lang.error: unresolved compilation problem arguments cannot resolved variable arguments cannot resolved variable arguments cannot resolved variable @ blankfiller.main(blankfiller.java:4) what doing wrong? you named formal parameter

Log-in to Google Account in Android WebView -

i'm integrating google drive in application. using below link i'm able connect google drive , able download files , able upload files google drive. https://developers.google.com/drive/quickstart-android below code i'm using upload file drive. inline image 2 using above code i'm able upload file drive , line numbers 20 - 23 in above pic, i'm getting file meta data such downloadurl, alternateurl , webcontentlink. now i'm trying load webview alternateurl , page loading asking google credentials again. how avoid webview asking google credential. programmatically, how login google account in webview without explicitly entering google username , password. want webview pick account using either accountmanager or google play service api. i referred below links, not able done needed. http://nelenkov.blogspot.in/2012/11/sso-using-account-manager.html any in regard highly appreciated.

facebook - FB.login() after FB.getLoginStatus() being blocked on Safari -

i have images want users able post facebook page when click 1 of several buttons on webpage. <script> fb.getloginstatus(function(response) { if ( response && response.status == 'connected' ) { postphotostofacebook(); } else { fb.login(function(response) { if ( response && response.status == 'connected' ) { postphotostofacebook(); } }, { scope: 'publish_actions' }); } }, true); </script> it's simple code. checks see if user logged in. if yes, posts pictures facebook. if not logged in, runs fb.login() , makes popup, asking user login facebook , give appropriate permissions app. after login complete, if user logged in , approved permissions, app same above, posts photos facebook. the fb.login() popup appears blocked on browsers though. why this? some methods i've seen suggest check see if user logged in when load page. isn't going work in cases b

sql server 2012 - SQL Error - varchar to numeric -

i imported flat file sql database , created of fields varchar(50). able change data type of fields, hit error in weight field. of data in weight field less 6 characters in total length , either whole integer or decimal. have tried both: update mawb set weight = cast(weight decimal(12,2)) and: alter table mawb alter column [weight] decimal(10,2) i error: error converting data type varchar numeric. i've checked of fields considered numeric using: select count(*) mawb isnumeric(weight) = 0 i've tried ltrim , rtrim safe, still error when try change field. know else might causing error? you can find offending rows query: select * mawb try_convert(decimal(12,2),weight) null , weight not null

How do I reference Django 1.5 URLs that are "named" in an included URL file? -

i have project's main urls.py file following: url(r'^accounts/$', include('accounts.urls'), in accounts.urls.py, have following: urlpatterns = patterns('accounts.views', url(r'^profile/$', 'accounts_profile', name='accounts_profile'), in base.html template, have: <li><a href="{% url 'accounts_profile' %}">profile</a></li> this results in reversenotfound error: noreversematch @ / reverse 'accounts_profile' arguments '()' , keyword arguments '{}' not found. if move accounts_profile url definition main urls.py, url works. remember style of url organization working in prior django version; has changed, or doing wrong? get rid of $ in url(r'^accounts/$', include('accounts.urls'), call. note regular expressions in example don’t have $ (end-of-string match character) include trailing slash. https://docs.djangoproject.c

xaml - Metro Attach FadeInAnimation to an Image -

i've got following should work: xaml <window.resources> <storyboard x:name="fadeinstoryboard1"> <fadeinthemeanimation storyboard.targetname="image1" /> </storyboard> <storyboard x:name="fadeinstoryboard2"> <fadeinthemeanimation storyboard.targetname="image2" /> </storyboard> <storyboard x:name="fadeinstoryboard3"> <fadeinthemeanimation storyboard.targetname="image3" /> </storyboard> <storyboard x:name="fadeinstoryboard4"> <fadeinthemeanimation storyboard.targetname="image4" /> </storyboard> <storyboard x:name="fadeinstoryboard5"> <fadeinthemeanimation storyboard.targetname="image5" /> </storyboard> </window.resources> <image source="../assets/image.png" x:name="image1" />

java - Constants and inner classes -

static variables in inner classes: inner class cannot contain static fields. cannot contain static members, because there problem assign static member. inner class connected outer class. understand why not contain static member, inner class can contain static constant. why? specially treated? on special heap? still static member, constant, specially treated? it can contain: "final static int x", not "static int x". i wonder why variables of method used in local class should final . mean: public void function1() { final int x; // value of x, used in class have final class { void function2() { //body of function } } } the answer is: variable x id copied class a. cannot changed, because there appeared inconsistency. why architects of java did not create language variable x not copied? address of variable passed , variable x changed without inconsistency. can give me example , explain this? or issue connected synchronization. bot

c - Runtime of Initializing an Array Zero-Filled -

if define following array using zero-fill initialization syntax on stack: int arr[ 10 ] = { 0 }; ... run time constant or linear? my assumption it's linear run time -- assumption targeting fact calloc must go on every byte zero-fill it. if provide why , not it's order xxx tremendous! the runtime linear in array size. to see why, here's sample implementation of memset, initializes array arbitrary value. @ assembly-language level, no different goes on in code. void *memset(void *dst, int val, size_t count) { unsigned char *start = dst; (size_t = 0; < count; i++) *start++ = value; return dst; } of course, compilers use intrinsics set multiple array elements @ time. depending on size of array , things alignment , padding, might make runtime on array length more staircase, step size based on vector length. on small differences in array size, make runtime constant, general pattern still linear.

implementation - Best way of implementing this in java -

so have requirments: a class called destination a hashmap called destinations the destination class has array of objects of type door. read "door" file, , every door has attribute "destination" tells me destination belongs to. my question is, what's better?: a) method in object holds destinations checks whether destination new door exists or not in hashmap destinations, , therefore insert door existing destination or create new destination , insert door. b) override (?) add method destinations hashmap , implement previous described functionality there. c) way. thank you. in java , similar languages more create classes meaningful names our application have simple lists , maps , sets (as in more dynamic languages). never see subclassing hashmap or arraylist or hashset , overriding add or put methods. the "java-esque" approach define class called destinations can contain (as field) hash map of destination objects, indexe

python - Defining common options for sub-commands with plac -

my question follow-up this question . shows how can use plac automatically generate command-line interface sub-commands representing each function. is possible tell plac options common sub-commands, , viewed 'global' options? in fact, these options should have meaning without sub-command. as example, might have svn checkout , svn update sub-commands, svn -v or svn --version command. a couple of years ago set multiprocessing script using plac . had multiple commands overlapping sets of arguments. i'll try abstract did class interface(object): commands = ['fn1','fn2',...] dict1 = dict(quiet=(...), dryrun=(...), ...) dict2 = dict() dict3 = dict() dict1.update(dict2) @plac.annotations(**dict1) def fn1(self, dryrun, quiet, ...) ... @plac.annotations(foo=(...), **dict2) def fn2(self, foo, ...) ... @plac.annotations(**dict2) def fn3(self, ...) ... so while arguments ea

javascript - Stopping a function, Arrays, and Integer Check -

so made code creating 5 ships in battleship game. succesfully made code layed out players ships. had no bugs. had player write out cords wanted position ship. write in ship position corresponding part in 2 dimensional array game map.. of course cords had integers or crash , burn. so made check if coordinate integer before doing else. if wasn't restart function making rest of function wouldn't run. if write in numbers correctly there no problems. problem if don't write in number function restart function or part of must still running because ship gets written array no reason. cords haven't been specified have no clue how can possible. here code made checking if integer , restarting function. userytest = parseint(prompt("horizontal coordinate position first unit of ship")); userxtest = parseint(prompt("vertical coordinate position first unit of ship")); if(userxtest % 1 === 0 && userytest % 1 === 0) { us

Cassandra CQL DataType Advantages and Disadvantages -

i looking using cassandra cql 3.0 , reading on various datatypes provided tables (or column families). see here list of datatypes: cql datatypes . questions advantages , disadvantages of different datatypes. example, if storing xml column, driver use blob vs. text? don't use blob unless none of other types makes sense. xml make sense me use text.

c# - What ReadOnlyCollection type should methods return? -

i've seen returning 'ilist' vs 'icollection' vs 'collection' , other questions links to, i'm still confused issue. let's assume demonstration purposes have class, expose public method, follows: public readonlycollection<type> getreadonlycollection(ienumerable<type> enumerable) { list<type> list = enumerable.tolist(); return new readonlycollection<type>(list); } to follow ca1002 , should method return actual collection classes ( readonlycollection , collection , etc.) or their interfaces ( ilist , icollection , etc.) if wish return readonlycollection specifically? you gain flexibility later change implementation if return type general possible. of course have return type useful consumer. hence, returning interface type better, , more general type well, long not cause problems in usage on consumer side.

php - pdo get number of rows -

i trying number of rows using pdo , if number less 1 echo not found else other stuff. below code isn't displaying "not found" if there no results matching clause. $options = array( 'results_per_page' => 200, 'url' => 'index.php?page=*var*', 'db_handle' => $dbh ); $page = $_get['page']; $paginate = new pagination($page, 'select * pants size ="medium" or size ="m" order id desc', $options); $result = $paginate->resultset->fetchall(); if($result > 0) { foreach($result $row) { echo $row['title'];} else { echo "not found";} you cannot compare array number, mind (yeah, in php). to test if have in array, simple if($result) is enough. note problem has nothing getting number of rows. need know if have any rows, not count them.

symfony - Doctrine2 eager loading runs multiple queries instead of 1 -

i'm using symfony2 doctrine2 (latest versions) , have relation defined: /** * @orm\onetomany(targetentity="field", mappedby="event", fetch="eager") * @orm\orderby({"name" = "asc"}) */ protected $fields; the other side of relation defined as: /** * @orm\manytoone(targetentity="event", inversedby="fields", fetch="eager") * @orm\joincolumn(nullable=false, ondelete="cascade") */ protected $event; when doing "fetchonybyid", doctrine runs 2 queries. 1 fetch object , 1 related fields. expect join, isn't. when done in controller, pass object twig. there retrieve fields again property of object. causes another query run retrieve fields again. clearly i'm doing wrong, expect 1 query run , 3 run. i believe reason occurring because you're fetching entities, not specific query. idea of doctrine you're fetching objects, not interacting database objec

java - how to set value of Input Box in Jsp -

<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <html> <form action="index.jsp"> <body> first input: <input name="firstinput" type="text" value=<%=request.getparameter("firstinput") %>> <br> <input type="submit" value="submit"> <% string first = request.getparameter("firstinput"); out.println(first); %> </body> </form> </html> ths code when put input tax after button click set tax , print tax when tax input "tax" value set tax in input box while print correct "tax" want set input box value "tax" when take input "tax" after click please you have both: name="firstinput" and name="fname" for same i

Inserting/updating data into MySql database using php -

i trying insert/update mysql database depending on whether post exists on database (i checking unique user_id). following works: $select_query = "select * "; $select_query .= "from test "; $select_query .= "where user_id = '$user_id'"; $check_user_id = mysqli_query($connection, $select_query); $query = "insert test ("; $query .= " user_id, name, message"; $query .= ") values ("; $query .= " '{$user_id}', '{$name}', '{$message}'"; $query .= ")"; $result = mysqli_query($connection, $query); if ($result) { echo "success!"; } else { die("database query failed. " . mysqli_error($connection)); } however, when use following code if/else statement, not work anymore, although console reports "success!" (meaning $result has value). appreciated. thanks. $select_query = "select * "; $select_query .= "from test ";

android - MultiChoiseModeListener methods are never called -

i have listview custom adapter. in activity oncreate() method set listview choice mode multiple_choise_modal , provide multichoisemodelistener implementation wrote. problem listener methods never called, except constructor. long-clicking triggers listview item onclick() method, instead of triggering oncreateactionmode or anything. i tried using simplecursoradapter instead of custom adapter , using simple_list_item_1 instead if item layout, has not helped much, methods still silent. so, can provide ideas can causing issue? ok, figured out. have no idea why happens, if view of item in listview clickable selection not work. fix problem had use onlistitemclick(listview l, view v, int position, long id) in listactivity instead of separate listeners each item. hope helps somebody

javascript - Reload page after click on <a> to get new data from PHP -

i'm writing multilingual web , logic next: by default there "lang.tmp" file default data "eng". when index.php loads takes data "lang.tmp" , sets default language loading data lang.php: include("lang/".file_get_contents("lang.tmp").".php"); if user wants change language, clicks on link created php, rewrites data in "lang.tmp": include("lang/languages.php"); $i=0; while (list($key, $value) = each($languages)) { echo '<li class="lang"><a href="index.php?'.$key.'"><div id="langbox">'.$value.'</div></a></li>'; if ($_server['query_string'] == $key) { $fp=fopen("lang.tmp","w"); fwrite($fp,basename($key)); fclose($fp); } so! problem is: after rewriting "lang.tmp" file need reload page same "index.php" address new type o

triggers - Automatically create and update one to one relationships in MySQL -

i have web shop (zen-cart)that has inefficient attribute schema. 1 option can used attributes many products. (instead of other way around). have tried use views make things easier, creating new attributes still tedious. have looked changing php-code, difficult. solution multi-lingual, don't need. the tables following: tb_products: prod_id tb_description: prod_id lang_id product_name (t-shirt) tb_attributes: attr_id prod_id option_id values_id tb_options: option_id language_id option_name (size & color) tb_values: value_id option_id language_id value_name (xs red) as quick-fix, following: make additional fields: tb_products: product_name option_name [optional - if attributes created] value_concatinator [optional] tb_attributes: value_name_1 value_concatinator_1 [optional] value_name_2 [optional] value_concatinator_2 [optional] value_name_3 [optional] create trigger, when create new row in tb_products, automatically create new row in both tb_description , tb

ruby on rails 4 - where.not() not working on arrays -

i have array called user_ids , want select records user_ids not in array. here used: mymodel.where.not(user_id: user_ids) but got error wrong number of arguments (0 1) . same thing happens when used mymodel.where.not('user_id=?', user_ids). thought maybe becuase array empty, same thing happens arrays not empty. does know why happens? i using rails 4. you should try this: mymodel.where('user_id not in (?)', user_ids)

localization - Django blocktrans - inside HTML tag -

is possible put html tag inside django block: {% blocktrans %}{% endblocktrans %}? for example: {% blocktrans %}django<br>framework needed{% endblocktrans %} certainly, have use blocktrans template tag actually. check: translating text blocks django .. html? django templates: best practice translating text block html in it https://groups.google.com/forum/#!topic/django-users/j_r6y1veaag

delphi - FindComponent doens't work in a procedure -

i developing program calculates averages of datas in different tstringgrid , thought use procedure. called calcola . procedure calcola(numero:shortint; stringgrid:tstringgrid; pbarprog:shortint); var i,j,cont,num:shortint; avg,temp,numfl:double; a:string; edit1:tedit; begin if stringgrid.colcount>1 //other code avg:=temp/cont; tlabel(findcomponent('label'+inttostr(num))).caption:=floattostrf(avg, ffgeneral, 1, 1); edit1.text:=floattostr(strtofloat(tlabel(findcomponent('label'+inttostr(num))).caption)*10); tprogressbar(findcomponent('progressbar'+inttostr(i+pbarprog))).position:=strtoint(edit1.text); //other code end; end; end; in procedure lazarus tells me " identifier not found findcomponent ". cut/pasted same code in procedure tform1.button1click(sender: tobject); , had no errors. i need use findcomponent() inside calcola , how it? then cut/pasted same code

templates - Initialization of member array with noncopyable non pod -

i think simple way ask due example. assume have following type: class node { // make noncopyable node(const node& ref) = delete; node& operator=(const node& ref) = delete; // moveable node(node&& ref) = default; node& operator=(node&& ref) = default; // not have default construction node() = delete; node(unsigned i): _i(i) {} unsigned _i; }; now want store of these nodes in std::array: template<unsigned count> class parentnode { std::array<node,count> _children; parentnode() // cannt this, since not know how many nodes need // : _children{{node(1),node(2),node(3)}} : _children() // how do this? {} }; as stated in comment, question is: how do this? unsigned passed child should index of array child stored. more general solutions appreciated! the following solution found myself might end in undefined behavior more complex types. proper defined solution see accepted answer. tem

multithreading - Python Twisted TCP application - How to prevent incoming message loss by blocking process -

i have 10 messages/second(total activity) coming in on tcp 40 clients. need take each message , 5 second process (look webservice, db queries , write results db). how separate messages coming in slow 5 second process? might receive message client while processing message client. never want lose message. with twisted, answer want do: from twisted.python.log import err twisted.internet.protocol import protocol class yourprotocol(protocol): ... def messagereceived(self, message): d = lookupwebservice(message) d.addcallback(querydatabase) d.addcallback(saveresults) d.adderrback(err, "servicing %r failed" % (message,)) you can find apis interacting web services in twisted.web.client (presuming "web services" things talk using http client). can find apis interacting sql database servers in twisted.enterprise.adbapi . can find apis interacting other kinds of databases little googling.

php - Why does a method call slows down everything? -

i have small loop new object. for ($i = 0; $i < $ilen; $i++) { $time = microtime(true); $row = db_row($res, $i); echo "(" . ($i + 1) . " / " . $ilen . ") "; $element = new datastructureelement($row['code']); $elementt = $element->gettypeclass(); unset($element); $elementt->setname($row['name']); // bad line! unset($elementt); echo number_format((microtime(true) - $time) * 1000, 1) . 'ms '; echo "\n"; } if leave out "bad line" got results: (1 / 3000) 1.7ms (2 / 3000) 0.7ms (3 / 3000) 2.4ms (4 / 3000) 1.9ms (5 / 3000) 0.7ms (6 / 3000) 0.7ms (7 / 3000) 3.2ms (8 / 3000) 2.1ms (9 / 3000) 0.7ms (10 / 3000) 0.7ms (11 / 3000) 0.7ms (12 / 3000) 0.7ms (13 / 3000) 0.7ms ... (2995 / 3000) 0.6ms (2996 / 3000) 0.5ms (2997 / 3000) 0.6ms (2998 / 3000) 0.7ms (2999 / 3000) 0.5ms (3000 / 3000) 0.5ms but if don't this: (1 / 3000) 1.5ms (2 / 3000) 0.

javascript - SVG Marker does not work -

i created marker in javascript, looks below: var marker = document.createelementns(svg.ns, "marker"); marker.setattribute("markerwidth", "3"); marker.setattribute("markerheight", "3"); marker.setattribute("id", "mkrcircle"); marker.setattribute("viewbox", "0 0 12 12"); marker.setattribute("orient", "auto"); marker.setattribute("stroke", "#000000"); marker.setattribute("stroke-width", "2"); marker.setattribute("fill", "#ffffff"); marker.setattribute("refx", "12"); marker.setattribute("refy", "6"); var mkrcontent = document.createelementns(svg.ns, "circle"); mkrcontent.setattribute("r", "5"); mkrcontent.setattribute("cx", "6"); mkrcontent.setattribute("cy", "6"); marker.appendchild(mkrcontent); defs.appen

javascript - Adding a listener that fires whenever the user changes tab -

i'm creating chrome extension , trying function fire everytime user changes tab. i've been looking @ listeners in webrequest api, , chrome.tabs couldn't figure use, , not use. the information need tab url. take @ chrome.tabs.onactivated : fires when active tab in window changes. note tab's url may not set @ time event fired, can listen onupdated events notified when url set. — google documentation chrome.tabs.onactivated.addlistener(function(activeinfo) { chrome.tabs.get(activeinfo.tabid, function (tab) { mysupercallback(tab.url); }); }); chrome.tabs.onupdated.addlistener(function(tabid, changeinfo, updatedtab) { chrome.tabs.query({'active': true}, function (activetabs) { var activetab = activetabs[0]; if (activetab == updatedtab) { mysupercallback(activetab.url); } }); }); function mysupercallback(newurl) { // ... } it works in background pages (as locercus conf

php - How could I send the information in AJAX at POST? -

sorry english... how send information that's in ajax post? ( info , info_1 , info_2 ) now, i'm sending get edit: try people here said me do, when call post variable in page send him info, show me eror... why? the new code: var xhr = new xmlhttprequest(); xhr.open("post",url,true); xhr.onreadystatechange = function() { if( this.readystate == 4 && this.status == 200) { document.getelementbyid(name).innerhtml = this.responsetext; } }; xhr.send("info="+str+"&info_1="+info_1+"&info_2="+info_2); return false; the first code: var xhr = new xmlhttprequest(); xhr.open("get",url+"?info="+str+"&info_1="+info_1+"&info_2="+info_2,true); xhr.onreadystatechange = function() { if( this.readystate == 4 && this.status == 200) { document.getelementbyid(name).innerhtml = this.responsetext; } }; xhr.send(); return false; chang

c# - Check if a ComboBox Contains Item -

i have this: <combobox selectedvaluepath="content" x:name="cb"> <comboboxitem>combo</comboboxitem> <comboboxitem>box</comboboxitem> <comboboxitem>item</comboboxitem> </combobox> if use cb.items.contains("combo") or cb.items.contains(new comboboxitem {content = "combo"}) it returns false . can tell me how check if comboboxitem named combo exists in combobox cb ? items itemcollection , not list of strings . in case collection of comboboxitem , need check content property. cb.items.cast<comboboxitem>().any(cbi => cbi.content.equals("combo")); or cb.items.oftype<comboboxitem>().any(cbi => cbi.content.equals("combo")); you can loop on each item , break in case found desired item - bool itemexists = false; foreach (comboboxitem cbi in cb.items) { itemexists = cbi.content.equals("combo"); if (itemexists

asp.net mvc - EF code-first how to use POCO objects in client layers -

i'm new asp.net mvc , ef , excuse me if question not clear or easy. i have read tutorials ef code-first approach , i'm trying tutorial getting started ef using mvc . using code-first approach i'm using poco classes define db model, db logic, db validation, ui validation , ui logic. can use these classes(or objects) in presentation layer or use them json objects when dealing web-services(or in javascript code). my question: isn't mixing logic together? mean shouldn't use special view-model classes presentation , these classes should have ui logic , validation ?! is practice send poco object view(or client in general) ? finally need guidance on how organize project layers or folders ? see many ways , i'm confused choose or format should base own on?!! you should not use data entities in higher layers of application. transform/compose/copy data dal view model or business classes using library automapper. keeps layers of application ind

processing css stylesheet with xml document -

i new xml (a couple of days now...)and going good, however, can't seem xml processed css style here perl... #!/usr/bin/perl -w use strict; use warnings; use diagnostics; use text::csv_xs; $csv = text::csv_xs->new ({ binary => 1, auto_diag => 1 }); $ifile="elementarray.csv"; $ofile="elementarray.xml"; open $fh, "<", $ifile or die $ifile.": $!"; open $out, "> ".$ofile or die "cannot write ".$ofile.": $!"; print $out <<eot; <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="elementarray.xsl"?> <?xml-stylesheet href="elementarray.css" title="default style"?> <emailcomments> eot # first record contains list of fieldnames #my $fields = $csv->getline($fh); #print @$fields; while (my $row = $csv->getline($fh)) { last unless $row && @$row; # encode "<" characters "&

python - Colored Selenium Output in Termin on Mac -

i'm playing web2py , work through http://killer-web-development.com/ tutorial. i'm using selenium tdd , think colorized terminal output fine. suggestions? thanks! i'm not sure how it's should work on python, ruby can examples here: colorized ruby output

jquery - How to add captions to slideshow -

i tried many ways add captions slideshow, couldn't. want add div on bottom of each image, should change script? or should add else? html: <div class="minislider"> <img src="http://www.no-margin-for-errors.com/wp-content/themes/nmfe/images/fullscreen/1.jpg" /> <img src="http://www.no-margin-for-errors.com/wp-content/themes/nmfe/images/fullscreen/2.jpg" /> <img src="http://www.no-margin-for-errors.com/wp-content/themes/nmfe/images/fullscreen/3.jpg" /> <img src="http://www.no-margin-for-errors.com/wp-content/themes/nmfe/images/fullscreen/4.jpg" /> </div> css: .minislider { width: 321px; height: 242px; background-color: #649696; position: relative; float: left; left: 76px; top: 11px; border-radius: 10px 10px 10px 10px; } .minislider img { width: 311px; height: 232px; position: absolute; left: 5px; top: 5px; } jquery

css - Why are some properties of my style object being ignored in ng-style? -

i have style object in controller: p: { 'font-family': 'lucida grande\', \'lucida sans unicode\', helvetica, arial, verdana, sans-serif', 'margin': '0' } only 'margin' honored (in chrome dev tools, 'margin' found in 'styles' list in 'elements' section). see issue font-family i've specified? try this: 'font-family': '\'lucida grande\', \'lucida sans unicode\', helvetica, arial, verdana, sans-serif', it may because need opening apostrophe ' before lucida grande, 1 there not serve purpose.

javascript - Get a sequence of images into an array -

i wondering if it's possible sequence of pictures array. i'd use plain javascript, because have 0 experience in php or other language achieve this. so created map called "images", contains 50 images. first 1 called: "1", second 1 called: "2" , on. same type (.jpg). i can manually like: var pictures = new array(); pictures[0] = "images/1.jpg"; pictures[1] = "images/2.jpg"; //and on but mad man this. when upload new picture "images" folder, have manually add new image array, thinking while loop checks if each image in folder stored array. you try: var pictures = new array(); for(var x=1; x<51; x++ ) { pictures[x-1] = "images/"+x+".jpg"; }

twig - Symfony, error: An exception has been thrown during the rendering -

the full error getting one. an exception has been thrown during rendering of template ("some mandatory parameters missing ("id") generate url route "fooblogbundle_articles".") in "fooblogbundle:article:articles.html.twig". this controller, handles action: public function articlesaction($id) { $em = $this->getdoctrine()->getmanager(); $blog = $em->getrepository('fooblogbundle:blog')->find($id); if(!$em){ throw $this->createnotfoundexception('unable find blog posti'); } return $this->render('fooblogbundle:article:articles.html.twig', ['blog'=>$blog]); } } and routing flickblogbundle_articles: pattern: /foo/{id} defaults: { _controller: fooblogbundle:article:articles } requirements: _method: id: \d+ twig , database, normal, no type or problems. error kind of hard spot, have gone wrong. ed

javascript - How do I geocode multiple fields? -

i trying create form geocode google map. have basic code map api, works 1 field: 'address'. instead of using 'getelementbyid', using 'getelementbyclassname' might use data of fields have set up. that said, isn't working. going in right direction using class instead of id? below code i;m working with. api-key omitted. <!doctype html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map-canvas { height: 100% } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=mykey=false"> </script> <script type="text/javascript&qu

ios - Sharper Corners on Grouped UITableView Cells without Subclassing -

Image
how can create less rounded corners uitableviewcells in grouped uitableview? i'm looking lessen corner radius of each grouping in app: (i'm not trying round entire tableview ) i've tried in cellforrowatindexpath no luck: [cell.layer setcornerradius:1.0]; in order have more sharper cornered cell, easiest edit custom view of cell. can using line: cell.backgroundview = [[[uiview alloc] initwithframe:cell.bounds] put inside cellforrowatindexpath method

java ee - DAO classes Singleton or Prototype Which is the best approach -

i working on dao layer , writing classes. these classes injected in service layer using spring ioc. best approach singleton/prototype (dao classes not have state ) if don't have state, doesn't matter much. leave them singletons, won't have multiple unnecessary instances of same dao. note that, if services singletons, making dao prototypes create 1 instance per service it's injected anyway.

c# - XNA Content Build Output not refreshed until all content is built -

is there way see realtime logs content being built using xna content pipeline ? some content take long time process many steps , great feedback going on asset being processed. tried contentprocessorcontext.logger, console.writeline, debug.writeline , tried increase msbuild verbosity (all levels) without success; logs displayed visual studio output window when content has been built. thanks in advance help. this works me - context.logger.logimportantmessage(...); but complex need debug build... 1 way.... system.diagnostics.debugger.launch(); http://blogs.msdn.com/b/shawnhar/archive/2006/11/08/debugging-the-content-pipeline.aspx the way prefer (actually prefer not have debug content pipeline), when must: i open new instance of visual studio open file in whichi wish place breakpoint place break point attach instance of vs other (proper) instance of vs when compile/build breakpoint hit hope helps.

sql server 2008 - Refreshing the database using C# code -

i have windows form application few text boxes, button , data grid view connected sql server database. when button clicked data entered database, not show in grid view. tried refreshing grid view, still no result. to see entered data have manually refresh database. entered data shown in grid view, when run application. please tell me way update database in button click event. or way show data in gridview have been entered database.

java - How can I get request parameter value if value is hash symbol (#) -

i have following request url: localhost:8080/myapp/browse/alphabetical/result?startswith=#&page=1&size=10&sort=title&order=asc notice request parameter "startswith=#" . i unable "#" value of 'startswith' request parameter. instead, empty string ("") value of 'startswith' request parameter. there possible way "#" value of request parameter? this not work: ${param.startswith eq '#'} this works: ${param.startswith eq ''} if there no way handle this, have resort using startswith=0 ... startswith=9 instead of startswith=# , don't want you cannot send # query string that. won't part of query string. quoting rfc - section 3.4 : the query component indicated first question mark ("?") character , terminated number sign ("#") character or end of uri. you need encode parameters in query string, before sending request. e.g., in jsp