Posts

Showing posts from May, 2014

Get Average of two java.util.Date -

i have array of java.util.date objects. trying find average. for example, if have 2 date objects 7:40am , 7:50am. should average date object of 7:45am. the approach thinking of inefficient: for loop through dates find difference between 0000 , time add time diff total divide total count convert time date object is there easier function this? well fundamentally can add "millis since unix epoch" of date objects , find average of those. tricky bit avoiding overflow. options are: divide known quantity (e.g. 1000) avoid overflow; reduces accuracy known amount (in case second) fail if have more 1000 items divide each millis value number of dates you're averaging over; work, has hard-to-understand accuracy reduction use biginteger instead an example of approach 1: long totalseconds = 0l; (date date : dates) { totalseconds += date.gettime() / 1000l; } long averageseconds = totalseconds / dates.size(); date averagedate = new date(avera

scala - Why are constructor parameters made into members for case classes? -

{ class myclass(name: string) {} val x = new myclass("x") println(x.name) // error name not member of myclass } but { abstract class base case class myclass(name: string) extends base {} var x = new myclass("x") println(x.name) // name member of myclass } so, what's deal case classes? why of constructor parameters turned variables. name member in both examples, private in first example while public in second. case classes make constructor parameters public val default.

python - showing specific xtick in matplotlib -

Image
so have graph runs on order of magnitude 10000 time steps, , have lot of data points , xticks spaced pretty far apart, cool, to show on xaxis point @ data being plotted. in case xtick want show 271. there way "insert" 271 tick onto x axis given know tick want display? if it's not important ticks update when panning/zomming (i.e. if plot not meant interactive use), can manually set tick locations axes.set_xticks() method. in order append 1 location (e.g. 271 ), can first current tick locations axes.get_xticks() , , append 271 array. a short example: import matplotlib.pyplot plt import numpy np fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(300)) # current tick locations , append 271 array x_ticks = np.append(ax.get_xticks(), 271) # set xtick locations values of array `x_ticks` ax.set_xticks(x_ticks) plt.show() this produces as can see image, tick has been added x=271 .

Time complexity for 3 nested loops with 2 variables -

how represent time complexity next nested loops when there 2 variables involved , not n? let's n=input of size , a=some discrete value (relevant quantity) so n=50000 , a=30000 for( int i=0;i<n;i++) { for( int j=0;j<a;j++ ) { for( int x=0;x<n;x++) { // dosomething(); } } } could o(n^2*a)? thank in advance chus yes, complexity in case o(n^2*a)

javascript - Google Maps API js3 not loading entire map -

my site utilizing google maps api, latest version, via javascript. site loads pages via ajax. i'm listening internal link click events , loading page, parsing dom, selecting want via jquery , inserting div. when load contact page (which contains map), map loads fine. in fact, if load page, , click contact link (causing contact page load via ajax), map loads fine. once view contact page, if navigate page (via ajax), , return contact page clicking contact link (via ajax), map shows 1 square, , remainder of map not load. of javascript initiate , setup map within contact page code gets loaded via ajax each time. i have tried using google maps event method trigger resize, has done nothing. any ideas? this question of timing. google.maps "one-tile" condition caused trying load initialise map in div that's rendered hidden, or not yet rendered. another issue may not have considered each map load eats goggle quota, potentially costly. "single-page&quo

javascript - Arrow key press statement not functioning correctly -

i'm trying create simple gallery web page consists of user pressing left , right arrow keys taking them previous/next image. far have code shown below. doesn't seem respond key presses though. i've checked console , there no errors, leaving me stuck issue is. the .image div html not change on key press - ideas? $(document).ready(function() { var current = 1; $("body").keydown(function(e) { if(e.keycode == 37) { if (current == 1) { var current = 1; } else { var current = current - 1; } $('.image').html('<img src="images/' + current + '.jpg"/>'); } else if(e.keycode == 39) { var current = current + 1; $('.image').html('<img src="images/' + current + '.jpg"/>'); } }); }); html <body> <div class="image"> <img src="images/1.jpg"/>

Thread Sleep in c# -

ok. i'm calling external script [edit: web service] that's doing asynchronous task. takes 1 2 minutes complete. in meantime want display user "please wait" message, since need make call check if previous task has been completed yet before continue. using timers not solution. need user wait before continue. so question have whether or not thread.sleep put entire web application sleep or 1 current ui? i don't want ui other website visitors hang. i'm not sure how works in production environment. i use iis 7 on windows 2008 r2 thanks thread.sleep affect current thread - it's not want anyway. you should return complete response web application - 1 starts javascript timer fire in few seconds, , make ajax call web app check whether task has completed. (you should include sort of "task id" in response server knows task check.) if sleep before returning response, user won't see any message until sleeping has completed.

c++ - g++ error: invalid preprocessing directive #INCLUDE -

i tried testing mingw under windows 7 simple hello world program , got following errors: c:\code\helloworld.cpp:2:2: error: invalid preprocessing directive #include c:\code\helloworld.cpp:3:7: error: expected neested-name-specifier before 'namespace' c:\code\helloworld.cpp:3:17: error: expected ';' before 'std' c:\code\helloworld.cpp:3:17: error: 'std' not name type c:\code\helloworld.cpp: in function 'int main()': c:\code\helloworld.cpp:7:2: error: 'cout' not declared in scope my original code follows: //hello, world #include <iostream> using namesapce std; int main() { cout << "hello, world!"; return 0; } it should lowercase. use #include . also, it's using namespace std; (typo in namespace ).

python 2.7 - Why minor ticks disappear on pylab subplots -

begin edit after initial post continued playing code. in subplots making 4 plots of same data set, each subplot having different time range. however, if give each subplot same time range minor ticks not disappear. may why deditos not reproduce issue. that being said, if manually create each subplot (with each having different x-axis range), set minor tick locations, set each subplot's xrange not see minor ticks disappear until set ax3's (i.e. last subplot) range. it seems issue in having different x-axis ranges. bizarre, think setting each axis' properties individually not tied together. end edit i creating 1 figure has 4 sub-plots, of time series. have xaxis major ticks spaced every 4 hours, , want minor ticks every hour. when set minor ticks first subplot (called ax1) minor ticks appear, should. however, when set minor ticks in ax2 show in ax2, minor ticks in ax1 disappear. repeats ax3, , ax4. so, in end have minor xaxis ticks in fourth subplot. had sa

Trouble with custom seekBar android -

Image
i have trouble custom seekbar .i used http://android-holo-colors.com/ give images of seekbar .the problem vague beginning of seekbar . how can solve problem?! screenshot: this code (i check , images same default except colors. <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background" android:drawable="@drawable/scrubber_track_red" /> <item android:id="@android:id/secondaryprogress"> <scale android:scalewidth="100%" android:drawable="@drawable/scrubber_secondary_red" /> </item> <item android:id="@android:id/progress"> <scale android:scalewidth="100%" android:drawable="@drawable/scrubber_primary_red" /> </item> </layer-list> and seekbar <seekbar android:id="@+id/seektrack

Using Wildcard/Regex for find & replace in Visual Studio -

i need replace different values of receivetimeout attribute receivetimeout="59:59:59" can wild card search used achieve task, in visual studio? <endpoint receivetimeout="10:10:20" someotherproperty="x1" yetanotherproperty="y1" /> <endpoint receivetimeout="10:50:20" someotherproperty="x2" yetanotherproperty="y2" /> ... <endpoint receivetimeout="30:50:20" someotherproperty="x3" yetanotherproperty="y3" /> i tried: using wildcard option in find & replace dialog, receivetimeout="*" selects complete line, receivetimeout="10:10:20" someotherproperty="x1" yetanotherproperty="y1" /> as might have guessed, editing wcf service web.config , have task manually & repeatedly. using regex option... find: <endpoint receivetimeout="[^"]+" then... replace: <endpoint receivetimeout="59

android - Implementing a custom indicator with ViewPageIndicator - How can I do it to a gallery? -

i'm working on project , managed point can show images in gallery sort of style using pageradapter. want add indicator image on screen , figure vpi me out - problem i'm new code , don't know how implement it, help? here's gif of want achieve - green line indicator: http://imgur.com/ggygy8i i made simpler version of project fit in post, here is: imageadapter.java package com.exp.viewpagersstest1; import android.content.context; import android.support.v4.view.pageradapter; import android.support.v4.view.viewpager; import android.view.view; import android.view.viewgroup; import android.widget.imageview; public class imageadapter extends pageradapter { context sscontext; private int[] ssimages = new int[] { r.drawable.splash1,r.drawable.splash2, r.drawable.splash3 }; imageadapter(context sscontext) { this.sscontext = sscontext; } @override public int getcount() { return ssimages.length; } @override publi

vba - Call a sub when a cell is a certain value -

i call sub causes cell blink between red , white if value of cell n63 = 0. in other words, if cell d70 = 0 startblinking else stopblinking. here bliking sub option explicit public nextblink double 'the cell want blink public const blinkcell string = "sheet1!d70" 'start blinking public sub startblinking() application.goto range("a1"), 1 'if color red, change color , text white if range(blinkcell).interior.colorindex = 3 range(blinkcell).interior.colorindex = 0 range(blinkcell).value = "white" 'if color white, change color , text red else range(blinkcell).interior.colorindex = 3 range(blinkcell).value = "red" end if 'wait 1 second before changing color again nextblink = + timeserial(0, 0, 1) application.ontime nextblink, "startblinking", , true end sub 'stop blkinking public sub stopblinking() 'set color white range(blinkcel

java - Working around access denied in a FileWalking Tree in Java7 -

the following simple code test files.walkfiletree() method. however, folder /etc/ssl/private , has these permissions ( rwx--x--- ), throws exception, when thought guarded if statement ( if (permissions.equals("rwx--x---") ). what doing wrong? in advance. public static void main (string []args) throws ioexception, interruptedexception { files.walkfiletree(paths.get("/"), new walkingthething2()); } @override public filevisitresult previsitdirectory(path dir, basicfileattributes attrs) throws ioexception { posixfileattributeview posixview = files.getfileattributeview(dir, posixfileattributeview.class); posixfileattributes posixattr = posixview.readattributes(); string permissions =posixfilepermissions.tostring(posixattr.permissions()); if (permissions.equals("rwx--x---")) { return filevisitresult.skip_subtree; } return filevisitresult.continue; } @override public filevisitresult visitfile(path file, ba

html - How to do two rows inside of a Hero-Unit without responsive? -

i'm doing web on bootstrap , i'm getting serious troubles can't solve bootstrap documentations. so, code: <div class="container"> <div class="hero-unit"> <h2>two rows</h2> <div class="row"> <div class="span6"> <center> <img src="../img/renders/example.png" style="position: absolute; width: 200px; height= 200px; margin-top: 80px"> <img src="../img/covers/some_image.jpg" title="image title" class="img-rounded propiedades_imagenes"> </center> </div> </div> <div class="span6"> <div class="well" style="margin-top:130px"> <a class="btn btn-large btn-primary" href="#link"> <i class="icon-download"

php - Strange letters showing up? -

well had problem include() blank area. said open notepad++ , save utf-8 without bom. can see strange letters @ blank area. how can remove that? , there way create php without bom in dreamweaver cc? i assume question using windows ? http://www.bryntyounce.com/filebomdetector.htm is best bom remover windows have used. edit: for mac open terminal window , sed -i .bak '1 s/^\xef\xbb\xbf//' *.php to stop happening again utf-8 without bom?

SSH Tunnel to access EC2 Hadoop Cluster -

background : i have installl 3 node cloudera hadoop cluster on ec2 instance workin expected. client program on windows machine load data machine hdfs. details : my client program has developed in java reads data windows local disk , write hdfs. for trying create ssh tunnel through putty , trying login windows username remote ec2 instance not working. able login unix username. wanted understand correct behavior? i don't know have created tunnel correctly or not after when try run client program gives me below error : my client program has developed in java reads data windows local disk , write hdfs. when trying run programs givin me below error. priviledgedactionexception as:ubuntu (auth:simple) cause:java.io.ioexception: file /user/ubuntu/features.json replicated 0 nodes instead of minreplication (=1). there 3 datanode(s) running , 3 node(s) excluded in operation. 6:32:45.711 pm info org.apache.hadoop.ipc.server ipc server handler 13 on 8020, ca

Android billing - where in the app flow is the best way to verify that the user is subscribed or not? -

i have application able user subscribe. but not best way manage subscription inside app. since user can unsubscribe outside app, need check status of subscription every time open app? or slow down app flow? or there better way that? thanks! all of apis asynchronous. shouldn't slow application down if ask verify application loads , response when it's ready. far know, should tell once subscription status changes, there's no need poll it. user can fool disconnecting internet connection while using app, next time connects, should pick on that. if aren't already, i'd suggest use androidbillinglibrary . it's pretty easy use , abstracts away of difficulties. should enough basic cases. make sure apply this patch or version applied.

php - SimpleXML child element attributes -

<form action='' method='post'> <input type='text' name='location'> <input type='submit' name='submit'> </form> <?php if(isset($_post['submit']) && !empty($_post['location'])) { $input = $_post['location']; $url = 'http://api.openweathermap.org/data/2.5/forecast?q='.strtolower($input).'&mode=xml'; $xml = file_get_contents($url, false); $xml = simplexml_load_string($xml); echo '<b>viewing weather for:</b> '. $xml->location->name; echo '<b>temperature:</b> '. $xml->forecast->children('temperature')->attributes('value'); } weather api: http://api.openweathermap.org/data/2.5/forecast?q=london,uk&mode=xml i trying value of temperature echo '<b>temperature:</b> '. $xml->forecast->children('temperature')->attributes('value'); this im s

How to use an accessor in Laravel 4 that only affects a field in a certain query function -

is there way use accessor change field query in laravel 4? so, have model, "fanartist.php". in table, "artists", have field "description". calling join in query function. function: public static function fan_likes_json() { $fan_likes = db::table('fanartists') ->join('artists', 'fanartists.artist_id', '=', 'artists.id') ->where('fanartists.fan_id', '=', auth::user()->id) ->select('artists.id', 'artists.stage_name', 'artists.city', 'artists.state', 'artists.image_path', 'artists.description') ->get(); } i trying change "description" string specific query function, using this: public function getdescriptionattribute($value) { return substr($value, 0, 90); } do add fanartist model, or artist model? , also, how hav

java - Heap dump's total size more than the used heap/perm gem -

i'm analyzing memory usage of tool using visualvm + visualgc. noticed wasn't expecting exposes misunderstanding of mine concerning jvm , heap dumps. to give full context, application profiling lookup of huge blob of serialized printing size of using jamm . after that, app sits there , waits until aborted. using visualvm, see heap usage growing expected. once operation complete , app sitting there sleeping, trigger gc (or rather, multiple gcs, carried away clicking button) using visualvm. the used heap @ point 1,849,825,472 bytes , permgem used space 25,864,448 bytes . at point, perform heap dump takes while but, when heap dump completes, used heap still 1,944,542,296 bytes permgen same @ 25,892,800 bytes . here's punch: heap dump shows total bytes count of 2,299,816,089 . what explain such discrepancy? repeated experiments few times , i'm getting same results.

html - PHP Contact Form Not Being Received In Email -

i know there few of these posts up, , read through them, unable find solution problem. php , html looks not sure why not receiving email submitted contact form. here php: <?php $fname = $_post ['fname']; $lname = $_post ['lname']; $email = $_post ['email']; $message = $_post ['message']; $to = 'myname@mywebsite.com'; $subject = 'contact website'; $msg = " first name: $fname/n" . "last name: $lname/n" . "email: $email/n" . "message: $message"; mail ($to, $subject, $msg,"from: " . $fname . $lname); $confirm = "thank contacting us! please allow 48 hours representative respond. click <a href='contact.php'>here</a> return previous page."; ?> and here html form code: <form id="form1" name="form1" method="post" action="send.php"> <tr> <label><td wid

many to many vs new object with compound foreign keys in django -

i have seen many many relationships expressed explicitly in model like: class pizza(models.model): toppings = models.manytomanyfield(topping, blank=true, null=true) i have seen people use object compound object this class pizzatopping(models.model): pizza = models.foreignkey(pizza) topping = models.foreignkey(topping) is there more preferable method of two? if so, why? example number 2 used when have additional fields in intermediary table (which example not have). example number 1 suffice when don't.

html - Print array elements into their respective column in JavaScript -

i have requirement take array in javascript , print out screen in table-like format. can column headers print without issue i'm struggling getting data print under columns in table manner.... javascript file (the data file): var firstnames = new array(); var lastnames = new array(); firstnames[0] = 'marc'; firstnames[1] = 'john'; firstnames[2] = 'drew'; firstnames[3] = 'ben'; lastnames[0] = 'wilson'; lastnames[1] = 'smith'; lastnames[2] = 'martin'; lastnames[3] = 'wilcox'; var personalinformation = { firstname : firstnames, lastname : lastnames }; html file: <!doctype html /> <html> <title>the data structure</title> <body> <script type="text/javascript" src="thedata.js"></script> <script> function printobj(theobject){ var theoutputtable = ''; var theoutputheader = ''; //print

linux - Are *_r UNIX calls reentrant (async-signal safe), thread safe or both? -

there difference in re-entrant , thread-safe functions , don't know if linux functions ending _r thread-safe, re-entrant (i mean async-signal safe) or both, they thread-safe. stevens/rago apue teaches distinction between thread-safe functions (reentrant respect being called multiple threads), , async-signal-safe functions (reentrant respect signal handlers, can called safely within signal handler). apue ch 12.5 reentrancy lists ~79 functions not thread-safe, ~11 have equivalents are reentrant, *_r functions. means 11 can called multiple threads @ same time. apue ch 10.6 reentrant functions lists ~135 functions async-signal-safe. block signal delivery when needed. so, can use them in signal handler code. note, async-signal-safeness matters when functions called inside signal handler. may motivate 1 not write signal handler code, further details tricky. kerrisk tlpi ch 21 signals: signal handlers has own table of functions async-signal-safe. interestingly n

python - Executing a script within a script but continuing on error(s) and saving them to file -

if have following bit of code: try: execfile("script.py") except ## unsure exception goes here... continue: try: execfile("other.py") except ## unsure exception goes here... continue: how catch errors script.py save file , continue onto next called script anyone have ideas or clues? errors = open('errors.txt', 'w') try: execfile("script.py") except exception e: errors.write(e) try: execfile("other.py") except exception e: errors.write(e) errors.close()

objective c - for loop with two integers -

i'm new here. know, how use for loop 2 integers. let's say: for (int x = 1, int y = 1; x <=200, y <=4; x++, y++) i need it, because have images on web server, following names: 1501.png, 1502.png, 1503.png, 1504.png 1511.png, 1512.png, 1513.png, 1514.png as can see, last digit image name y , first 3 digits x. i want use like: [@"mywebsite/%i%i.png", x , y] any suggestion? much clearer put 1 loop inside other: for (int x = 1; x <=200; x++) { for(int y = 1; y <=4; y++) { // [@"mywebsite/%i%i.png", x , y] } } i'd suggest more descriptive names x , y

.net - How can I remove an access control entry from a printer in C#? -

i've been attempting use wmi remove access control entry (ace) discretionary access control list (dacl) associated local printer in windows 7. code gets security descriptor, , iterates through aces in dacl. unless trustee in ale named "everyone", ace added temporary list. the temporary list turned array, , replaces dacl property of security descriptor. code calls setsecuritydescriptor() modified descriptor. the return value 0x8007051b, 0x051b being win32 error code: 1307, security id may not assigned owner of object. the error message bit confusing, in code (intentionally) changing owner of printer. if change method include every ace in temporary list, call setsecuritydescriptor() completes successfully. running application administrator makes no difference. and, of course, code: private void changesecurity() { var query = string.format("select * win32_printer name \"%{0}%\"", printername); var sear

c++ - How do I connect an SDK to Visual Studio? -

i'm new sdk. don't know how add sdks downloaded visual studio. to more specific, i've downloaded sdk leap motion windows: https://developer.leapmotion.com/dashboard i using visual studio 2012 , writting in c++. i want know how connect sdk vs, can use methods provided sdk. any appreciated! import dll libraries code using reference adding , using or import reference (depending prog language). there dll x86 , x64 arquitectures, select full filled compliment version project , machine. when code has no errors pleas, copy dll release , debug folder manually or have runtime exceptions. regards

.net - Asp.net MVC3 web application server response time issue -

my site taking on 5 seconds load, other sites hosted on same server working fine , opening fast. pointed same dns. i using same connection helper class open connection ms sql express 2008 express r2 (sp1) sites: public class connectionhelper : iconnectionhelper { public objectcontext connection { { if (_connection == null && httpcontext.current.items["dbactivecontext"] != null) { _connection = (cpusortentities)httpcontext.current.items["dbactivecontext"]; } else { _connection = new cpusortentities(connectionstring); //httpcontext.current.items.add("dbactivecontext", _connection); httpcontext.current.items["dbactivecontext"] = _connection; } return _connection; } } private objectcontext _connection; public string connectionstring {

class - Confused about classes in Learn Python the Hard Way ex43? -

i'm confused on how map , engine classes work run adventureland type game (full code here: http://learnpythonthehardway.org/book/ex43.html ). think understand happening in map class, i'm confused happening in engine() , why scene_map variable needed. class map(object): scenes = { 'central_corridor': centralcorridor(), 'laser_weapon_armory': laserweaponarmory(), 'the_bridge': thebridge(), 'escape_pod': escapepod(), 'death': death() } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): return map.scenes.get(scene_name) def opening_scene(self): return self.next_scene(self.start_scene) class engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() while true: print "\n------

Should a PHP app store configuration data in defined constants or a database? -

i'm working on php application , keep going back-and-forth myself on best way store configuration data (the type might change occasionally, not frequently). includes lot of non-sensitive information validity periods tokens , cookies, or parameters various email messages application sends, includes few more sensitive things api keys. store in database table - path started going down, in part because imagining handy administrative utility allow system admins modify these values when necessary. since of application pages need access 1 or more of these values, feels lot of excess trips database, if small, fast lookups. use defined constants - thought of using defined constants , sticking data in .php file (outside web root, of course). avoid database lookups, somehow feels wasteful define few dozen constants on every page load when given page need handful of them @ most. is 1 or other (or else altogether) recommended, whether reasons of security, efficiency, or style?

php - (Yii)Datetime Validation fails -

i'd validate form input datetime article posted. $model = new post('update'); $model->attributes = $_post['post']; if($model->validate()){ //but, validation fails... } this rule got check if input datetime format or not. used page( http://chris-backhouse.com/date-validation-in-yii/528 ) reference. but validation error 'created'input. public function rules() { return array( //datetime validation array('created', 'date', 'message' => '{attribute}: not datetime!', 'format' => 'yyyy-mm-dd hh:mm:ss'), ); } this have in $models-attribute. array(1) { ["created"]=> string(19) "2013-08-01 00:00:01" } could knows how make work? thanks lot in advance!!! i advice use input formats in rule, since want custom formats. array('created', 'date', 'format'=>'yyyy-mm-

html - How to use Jquery to add click function for run time added image? -

i have html table markup generated on browser when user click. here code $('#selectedtable > tbody:first').append( '<tr > ' + '<td>chair</td>' + '<td><img src="/content/images/showinfo.png" title="show info"></td>' + '</tr>' ); so question possible add click event above generated image? yes, can either add onclick handler after added image dom, with $("#my-image").click(function() { alert("i've been clicked"); }); (for image id my-image ) or can set handler applied future added elements: $(document).on("click", ".image-class", function() { alert("i've been clicked"); }); (for images classes .image-class )

Lua math.random not working -

so i'm trying create little , have looked on place looking ways of generating random number. no matter test code, results in non-random number. here example wrote up. local lowdrops = {"wooden sword","wooden bow","ion thruster machine gun blaster"} local meddrops = {} local highdrops = {} function randomloot(lootcategory) if lootcategory == low print(lowdrops[math.random(3)]) end if lootcategory == medium end if lootcategory == high end end randomloot(low) wherever test code same result. example when test code here http://www.lua.org/cgi-bin/demo ends "ion thruster machine gun blaster" , doesen't randomize. matter testing simply random = math.random (10) print(random) gives me 9, there i'm missing? you need run math.randomseed() once before using math.random() , this: math.randomseed(os.time()) one possible problem first number may not "randomized" in platforms

delphi - recovering from "Connection Reset By Peer" Indy TCP Client -

how should recovering in situation? the server crashes, connection has been abnormally closed. calls result in "connection reset peer" exceptions. seem have fixed calling disconnect on tidtcpclient object inside except block, results in 1 final exception same message (which have caught in second try-except block). this indy10 , delphi xe2. try if not ecomsocket.connected ecomsocket.connect(); except on e: exception begin try ecomsocket.disconnect(); except messagedlg('connectivity server has been lost.', mterror, [mbok], 0); end; end; end; try this: try if not ecomsocket.connected ecomsocket.connect(); except try ecomsocket.disconnect(false); except end; if ecomsocket.iohandler <> nil ecomsocket.iohandler.inputbuffer.clear; messagedlg('connectivity server has been lost.', mterror, [mbok], 0); end;

What is the purpose of adding an id to a css link tag -

this question has answer here: why give style tag id 1 answer what purpose of adding id attribute css link tags? example: <style type="text/css" id="some_id_name"> in html 4.01, id attribute cannot used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, , <title> . while in html5, id attribute can used on html element (it validate on html element. however, not useful ). but use can reference i.e var styles = document.getelementbyid('some_id_name'); // want, styles.parentnode.removechild(styles); // remove these styles styles.setattribute('href', 'alternate-styles.css'); check why give style tag id

Dotnetnuke Skin Issue -

hi chris using dotnetnuke 6.2.3 enterprise edition. in localhost images referred in skin file came both login , logout period.i followed following steps.1st need create 1 child portal. went host-->sitemanagement-->add new site--> choosed child portal , site title,description,keywords.i can able create child site. after went admin-->sitewizard-->blank template-->replace content-->i choosed installed skin , container in portal .and added html modules. both skin , html contains image tag. now login superuser -->my content, images ,style properties came fine. once logout skin file not loaded due page alignment collapsed. next in chrome went inspect element not able open images.if login host able see files. can please share 1 of urls images aren't working? perhaps have permissions in dnn file manager setup have logged in view of files in folder. can go file manager, click on folder, , manager permissions there.

java - How to override struts 2.2.3.1 file upload messages? -

the struts.messages.error.file.too.large or struts.messages.error.content.type.not.allowed keys pose interest me. i've tried put them in "global.properties" , "struts-messages.properties" , , "actionname_en_us.properties" file , have not seen either 1 of messages wrote. have three <s:file> fields in form , action submitted has interceptors: <interceptor-ref name="fileupload"> <param name="maximumsize">2097152</param> <param name="allowedtypes"> image/png,image/gif,image/jpeg,image/pjpeg </param> </interceptor-ref> <interceptor-ref name="securestack"></interceptor-ref> the securestack interceptor not throw errors. edit: here's definition of it: <interceptor name="authenticationinterceptor" class="client.interceptors.authentication" /> <interceptor-stack name="secures

Initialization of Instance Variables in Java -

how instance variable id gets initialized 0 when have provided our own default constructor , did not initialize id in it? output comes id:0 status:b how id 0? `class demo{ private int id; private char status; public demo(){ status = 'b'; } public void display(){ system.out.println("id:="+id+" status:"+status); } public static void main(string args[]){ demo ob = new demo(); ob.display(); } }` below default intializations the following chart summarizes default values above data types. data type | default value (for fields) -----------------------+----------------------------- byte | 0 short | 0 int | 0 long | 0l float | 0.0f double | 0.0d char | '\u0000' string (or object) | null boolean | false

How can I know google sync is activated on an android device programmatically? -

i need know 2 things : does google sync active on device. if yes , when last backup datetime. so far didn't find way hand on data , appreciated. don't mind if it's solution work particular api version. thanks you should use accountmanager , filtering results account type ( com.google ), above sync state, using contentresolver . check out code attached: accountmanager = accountmanager.get(this); account[] accounts = am.getaccountsbytype("com.google"); boolean syncenabled = contentresolver.getsyncautomatically(accounts[0], contactscontract.authority);

android - Maven + RoboGuice + ActionBarSherlock + RoboGuice-Sherlock -

i trying create android base project using android-quickstart archetype, , adding roboguice, actionbarsherlock dependencies, plus roboguice-sherlock combine two. this pom.xml: <?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.myapp</groupid> <artifactid>baseapp</artifactid> <version>0.0.1-snapshot</version> <packaging>apk</packaging> <name>baseapp</name> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <platform.version> 4.1.1.4 </platform.version> <android.plugin.version>3.6.0&l

python - django taggit prevent overlapping tags across different models -

i have 2 different models. class messagearchive(models.model): from_user = models.charfield(null=true, blank=true, max_length=300) archived_time = models.datetimefield(auto_now_add=true) label = models.foreignkey(messagelabel, null=true, blank=true) archived_by = models.foreignkey(orgstaff) tags = taggablemanager() now say, have defined spam , todo , urgent tags messages. and have model: class personarchive(models.model): from_user = models.charfield(null=true, blank=true, max_length=300) archived_time = models.datetimefield(auto_now_add=true) label = models.foreignkey(messagelabel, null=true, blank=true) archived_by = models.foreignkey(orgstaff) tags = taggablemanager() i define awesome , legend , rockstar model person. there might few more defined. as quite clear, not want tags person , message overlap. how should achieve that? thanks! you can utilize limit_choices_to feature on foreignkeyfields

abount the singleton beans of spring -

i reading 《spring in action》, , says "singleton beans in spring don't maintain state because they're shared among multiple threads", in opinion, bean in spring pojo, how can not maintain state? i reading 《spring in action》, , says "singleton beans in spring don't maintain state because they're shared among multiple threads", in opinion, bean in spring pojo, how can not maintain state? yes, it's better spring/singleton not have state (of course can uses other spring/singletons [also them without state]) can call methods different threads without worring messed state (it doesn't have 1 :-)). let's think calculator stores intermediate results inside internal stack, can happen if 2 threads try calculate @ same time? a spring/singleton annotated (and if it's not it's be) , lives inside spring context , it's not pojo. if want have spring/bean state have use scope "prototype", kind of scope ever

asp.net mvc 4 - MVC 4 javascript not rendering -

i cant seem these (js files) rendered. layout.cshtml <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@viewbag.title - asp.net mvc application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @if (issectiondefined("scripts")) { @scripts.render("~/bundles/jquery") @rendersection("scripts", required: true) } @styles.render("~/content/css") @scripts.render("~/bundles/modernizr") </head> index.cshtml @section scripts { <script src="@url.content("~/scripts/lib/firebugx.js")" type="text/javascript"></script> <script src="@url.content("~/scripts/lib/jquery-ui-1.8.16.custom.min.js")" ty

ruby on rails - Login failure without clear error specification -

i'm trying authenticate application, , fails login. saw redirect login again if credentials(username , password ok). in user.rb have : class user < activerecord::base validates :nome, :presence => true, :uniqueness => true validates :password, :confirmation => true attr_accessor :password_confirmation attr_reader :password validate :password_must_be_present def user.authenticate(nome, password) if user = find_by_nome(nome) if user.hashed_password == encrypt_password(password, user.salt) user end end end def user.encrypt_password(password, salt) digest::sha2.hexdigest(password + "wibble" + salt) end # 'password' virtual attribute def password=(password) @password = password if password.present? generate_salt self.hashed_password = self.class.encrypt_password(password, salt) end end private def password_must_be_present errors.add(:password, &

c# - Create Microsoft Mouse and Keyboard style selection -

Image
i'm making application relating key bindings - hence wish take image of mouse, , overlay outline of button on said mouse show key (i wish controllers , keyboard, should same doing mouse) effectively, i'm going akin microsoft mouse , keyboard program: the mouse cursor cannot seen in image, on right mouse button - hence selected / highlighted both whole button , binding. i understand c# / visual studio might not best way this. i'm not wanting majorly fancy. in fact, being able overlay 1 image on other , detect mouse on fine. what's way, or way can this, preferably without having code directly? ( i.e being able place , position in designer, coding visibility , rest ) i have tried use visual basic powerpacks graphics, seem offer basic pre-defined shapes (in case used rectangles) , looked out of place when put on top of mouse buttons i have tried using image box 2 images (as per hans passant's suggestion) not image box take account transparency of image

opencv - EMGU crashes when trying to write out greyscale image to VideoWriter -

can tell me why emgu throws exception when trying write out greyscale image? here do: gcam.startacquisition(); debug.writeline("recording..."); //bitmap safeimage = new bitmap(xiimagewidth, xiimageheight, //system.drawing.imaging.pixelformat.format8bppindexed); bitmap safeimage = new bitmap(xiimagewidth, xiimageheight, system.drawing.imaging.pixelformat.format16bppgrayscale ); //emgu.cv.image<gray, byte> currentframe; emgu.cv.image<gray, uint16> currentframe; gcam.getimage(safeimage, xi_capture_timeout); //currentframe = new image<gray, byte>(safeimage); currentframe = new image<gray, uint16>(safeimage); currentframe.save("testimage.bmp"); starttime = datetime.now; if (emguvideowriter.ptr != intptr.zero) { emguvideowriter.writeframe(currentfra

Drupal custom theme visibility to all users -

i'm creating custom drupal 7 theme <?php print theme('links', array('links' => menu_navigation_links('menu-headermenu'), 'attributes' => array('class'=> array('links', 'headermenu')) )); ?> above code i'm using in theme show menu created using admin section. my problem menu getting displayed admin. i want shown anonymous registered users. also, i've tried changing role permission ticking 'administer block' , 'administer menus , menu items' 3 kind of users. nothing helps. please me.. i'm not 100% sure answer question, because side steps code above - but, try enabling menu block module, using create block based on desired menu. can place block region, , control via normal block controls. the trick of might need add region template if doesn't exist in place want, that's easy.

java - What does ceill floor in this code mean? -

can explain me code mean? in if/else. have read documentation several times, can't these functions mean. thanks. private long getbalancewithfactor(long balance, double factor) { double faccountbalance = (double)balance * factor; long res = 0; if ((math.ceil(faccountbalance) - faccountbalance) <= 0.5) res = (long)math.ceil(faccountbalance); else res = (long)math.floor(faccountbalance); return res; } math.ceil() rounds up, math.floor() rounds down nearest integer. so example if give 0.5 ceil(0.5) return 1.0 , , floor(0.5) return 0.0 . there useful function in context: math.round() ceil() , floor() combined. rounds nearest integer using mathematical rounding rules. please note these methods return doubles you'll need cast them integers.

java - Design Scenario: Smartphone class and will have derived classes like IPhone,AndroidPhone,WindowsMobilePhone can be even phone names with brand -

this 1 of java designing question found on internet. tried solve question per object oriented knowledge. you have smartphone class , have derived classes iphone,androidphone,windowsmobilephone can phone names brand, how design system of classes? detail mentioned per requirement wise design must flexible enough support future products , stable enough support changes in existing model. as per understanding if have provide design above question ,then create phone class abstract class. smartphone class subclass of phone class , iphone,androidphone,windowsmobilephone 4 subclasses of smartphone class. there attribute name brand in iphone,androidphone , windowsmobilephone classes support phone names brand. other possible attributes version number, platform, model number,model name etc please let me know if above design correct or not.i need inputs improve or correct solution. your design seems fine. i suggest: 1-> create parent class "smartphone"

Eclipse does not recognize that Glassfish stopped -

i encountering following issue: i using glassfish 3.1 server deploy applications on , restarting him within eclipse have clean glassfish (he keeps old classfiles , want make sure...) should working fine, every ~5 times restarting server wont start again. log output looks this: info: server shutdown initiated info: jmx002: jmxstartupservice: stopped jmxconnectorserver: null info: jmx001: jmxstartupservice , jmxconnectors have been shut down. info: shutdown procedure finished after no more lines printed out. tried wait time wont start again itself. meanwhile eclipse showing "restarting glassfish 3.1 @ localhost" in prograss view. if click stop button turns gray wont vanish. telling server start again not working waits "restarting" finish , well... isnt happening. to still able work have restart eclipse every time glassfish server wont stop... i can work it, interested if has experienced similar behavior , maybe has solution :) edit 1 forgot include

javascript - Search data from the table is not working -

i working on javascript. in code have table , textbox. when enter data in textbox should show particular value typed doesn't search data table. how search data in table?i have provided link below. http://jsfiddle.net/surwn/ <table name="tablecheck" class="data" id="results" > <thead> <tr ><th>&nbsp;</th> <th>&nbsp;</th> <th><center> <b>course code</b></center></th> <th><center>course name</center></th></tr> </thead> <tbody> <tr id="rowupdate" class="tableheaderfooter"> <td> <center> <input type="text" name="input" value="course" ></center> <center> <input type="text" name="input" value="course1&quo