Posts

Showing posts from April, 2014

android - Can I add listener to Circle drawn on the map? -

i want draw circle on map , when user touches it. also, can't find method of circle that. need do? thanks, sarun edit in order clarify question. want circle have constant distance relative ground, means, if zoom map, circle grow bigger. you can using onmapclicklistener . in callback check if distance between clicked latlng , center of circle smaller radius. location.distancebetween should of help.

c# - Entity Framework Include without Relations -

i working on huge project using entity framework. because made entities time-dependent not possible use relations between entities anymore (i manage relations myself). problem came not longer able query data before. have entity called student . entity contains collection of books (list) belong student. each book contains author property comes database well. load students theirs book , corresponding authors either have write hundreds of custom queries (f.e. linq) or lazy load them results in big performance impact. great if use inlude of entity framework without relations. know how achieve this? thank you. if entity framework not managing relations between tables, has no way of using .include() create joins in sql call. best option add related entities parent normal, use [notmapped] attribute. can use custom sql call perform lookups , populate properties when need them. confused, however, statement because entities "time-dependent" can't use relationshi

Python errors confusing a Python noobie -

Image
literally started learning python today , i'm ready pull hair out on errors i'm not understanding. here errors getting when try run script: and here script in question: primes = [] x = raw_input('enter max value check primes: ') num in range(2, x+1): if len(primes) == 0: primes.append(num) else: prime in primes: if (num % prime == 0): break primes.append(num) number in primes: print number from errors received far, looks cannot declare blank list, , doesn't input method. copied these lines more or less out of tutorial worked, , confused why work there not here. appreciated. the error messages posted start "command not found", implies running python script not in python, in shell. fix it, either run python question7.py , or add #!/usr/bin/env python first line of script (this known shebang line, , tells interpreter let python run script instead).

cordova - iOS 7 Status bar with Phonegap -

in ios 7, phonegap applications appear underneath status bar. can make difficult click on buttons/menus have been placed @ top of screen. is there knows way fix status bar issue on ios 7 in phonegap application? i've tried offset entire web page css doesn't seem work. there way offset entire uiwebview or make status bar behave did in ios6? thanks i found answer on thread, i'll answer question in case else wonders. just replace viewwillappear in mainviewcontroller.m this: - (void)viewwillappear:(bool)animated { // view defaults full size. if want customize view's size, or subviews (e.g. webview), // can here. // lower screen 20px on ios 7 if ([[[uidevice currentdevice] systemversion] floatvalue] >= 7) { cgrect viewbounds = [self.webview bounds]; viewbounds.origin.y = 20; viewbounds.size.height = viewbounds.size.height - 20; self.webview.frame = viewbounds; } [super viewwillappear:animat

python - n-grams with Naive Bayes classifier Error -

i experimenting python nltk text classification. here code example practicing: http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/ here code: from nltk import bigrams nltk.probability import eleprobdist, freqdist nltk import naivebayesclassifier collections import defaultdict train_samples = {} file ('data/positive.txt', 'rt') f: line in f.readlines(): train_samples[line] = 'pos' file ('data/negative.txt', 'rt') d: line in d.readlines(): train_samples[line] = 'neg' f = open("data/test.txt", "r") test_samples = f.readlines() # error in code # def bigramreturner(text): # tweetstring = text.lower() # bigramfeaturevector = {} # item in bigrams(tweetstring.split()): # bigramfeaturevector.append(' '.join(item)) # return bigramfeaturevector # updated code stack overflow comment def bigramreturner (tweetstring): tweetstring = tweet

java - Publish an event using Struts 2 jQuery Plugin -

i want use publish / subscribe framework used internally strust2 jquery plugin. the user can select account number list or type in textbox. i want publish event when text box or select option changes. user can type textbox or select select box: <s:textfield name="account" onblur="$.publish('accountchanged',this,event)"/> <s:select name="accountlist" list="destinationaccounts" onblur="$.publish('accountchanged',this,event)"/> below js: $.subscribe('accountchanged', function(event, data) { alert("new data is: " + data.value); if ( event.target.id=='account') { //do } } here issues: the data.value works textbox, select box data.value undefined. i want know target received event. event.target.id not working! think event object not jquery event object? i reviewed sample showcase application, not find any. am calling $.publish method co

matlab - determine average length of cells in a cell array -

this question has answer here: matlab length of each element in cell array 2 answers hi have cell array in matlab, cells of differing lengths. how determine average length of cells. i have tried: mean(length(mycell{:}); however many inputs mean function. thanks. use cellfun mean( cellfun( @length, mycell ) ) btw, of builtin functions might better write mean( cellfun( 'length', mycell ) )

c# - How to add formula on Crystal report fields -

Image
below crystal report ,i want perform formula below ,as new crystal report how can ? if (`fee_unit`==percent) { feetotal = (`fee` divided 100) * `number of patients`; } else { feetotal = `fee` * `number of patients`; } in field explorer -> formula-> new formula. from drop down above select basic syntax. if {tablename.feeunit} = {tablename.percent} // assuming have feeuni , percent column in tablename table. drag drop 2 , wrap code formula=({tablename.fee}/100)*{tablename.patients} // formula here keyword else formula={tablename.fee}*{tablename.patients} end if

python - Byte Array to Hex String -

i have data stored in byte array. how can convert data hex string? example of byte array: array_alpha = [ 133, 53, 234, 241 ] using str.format : >>> array_alpha = [ 133, 53, 234, 241 ] >>> print ''.join('{:02x}'.format(x) x in array_alpha) 8535eaf1 or using format >>> print ''.join(format(x, '02x') x in array_alpha) 8535eaf1 note: in format statements, 02 means pad 2 leading 0 s if necessary. important since [0x1, 0x1, 0x1] i.e. (0x010101) formatted "111" instead of "010101" or using bytearray binascii.hexlify : >>> import binascii >>> binascii.hexlify(bytearray(array_alpha)) '8535eaf1'

sql - Get the most recent record of with unique fields -

i have table in database, , build query return records date contained in last 7 days, number maximum , records group foo_id. example: +---------------------------------------------------+ | id | number | date | foo_id | +---------------------------------------------------+ | 0| 29 | 2013-10-01 08:52:00.000000 | 7 | | 1| 12 | 2013-10-02 08:52:00.000000 | 7 | | 2| 23 | 2013-10-02 08:52:00.000000 | 2 | | 3| 42 | 2013-10-02 08:52:00.000000 | 2 | +---------------------------------------------------+ the query returns: | 3| 42 | 2013-10-02 08:52:00.000000 | 2 | | 0| 29 | 2013-10-01 08:52:00.000000 | 7 | i have build query, doesn't work @ all: calendar time = calendar.getinstance(); time.add(calendar.date, -7); querybuilder<greattable, integer> qbt = dao.querybuilder(); qbt.where().ge(greattable.date_column_name, time.gettime()); qbt.orderby(greattable.date_column_name, false).orde

java - Populating a Struts 2 select menu and redirecting action -

i have jsp file form. form contains select drop-down menu <s:select label="make selection" headerkey="-1" headervalue="select option" list="stuff" name="books" /> now, populate select menu created java file that. created selectaction populate menu , made form's action pointed selectaction in .xml file adjusted contains action populating select redirect action deal form xml file <?xml version="1.0" encoding="utf-8" ?> <!doctype struts public "-//apache software foundation//dtd struts configuration 2.0//en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="example" namespace="/example" extends="struts-default"> <action name="selectaction" class="example.selectaction"> <result type="redirectaction"> <

Parse error: syntax error, unexpected T_ELSE in /home3/mafiasec/public_html/logincheck.php on line 311 -

here's code, it's irritating can't find problem.. have been looking past 2 days , can't work out myself, relatively new coding please explain going on because won't understand saying. please give me hand here - here's code. <?php session_start(); include_once("includes/db_connect.php"); if (isset($_session['real_name'])){ include "mainmenu.php"; die("-"); exit(); } error_reporting(0); //this of course tells website follows $realip=$_server['remote_addr']; if ($_post['submit'] && mysql_real_escape_string($_post['username'])){ function change($msg){ $post = $msg; $post = str_replace(" ", "", $post); return $post; } $username = $_post['username']; $password = $_post['password']; $password = mysql_real_escape_string(strip_tags($password)); $ip = $_server['remote_addr']; $date = gmdate('y-m-d h:i:s'); $tquery = &

javascript - How to check if there is no specific character left -

i'm creating javascript game of hangman (javascript no jquery whatsoever) code replace unguessed letters '_' function partialwords(random_word, letters) { var returnletter = ""; (i = 0; < random_word.length; i++) { if (letters.indexof(random_word[i]) !== -1) { returnletter = returnletter + random_word[i]; } else { returnletter = returnletter + ' _ '; } } return returnletter; } i wondering if able me figuring out how check if there no more '_' left, in advance! there indexof method string object too if(returnletter.indexof('_') == -1) { } you can hold missed letters in separate array function partialwords(random_word, letters) { var returnletter = ""; var missedletters = []; (i = 0; < random_word.length; i++) { if (letters.indexof(random_word[i]) !== -1) { returnletter = returnletter + random_word[i];

android - What is the name of GoogleTTSService in JellyBean 4.3? -

in android versions prior 4.3, name of google's text-to-speech service, belonging package android.tts.ttsservice , googlettsservice . thus, if inspect list of running services in devices running android 4.2 or lower, find com.google.android.tts.googlettsservice among them. but in android 4.3 seems have changed and, among many services listed in running device, can no longer find corresponding service name. what new name? part of different service? update: appears package name service has been renamed android.tts.ttsservice in 2.x android.speech.tts.texttospeech in 4.3. that's step in right direction actual name of google's engine still missing. any idea? you can discover package tts engine in following way: texttospeech tts = new texttospeech(context, oninitlistener); then in oninit listener: @override public void oninit(final int status) { switch (status) { case texttospeech.success:

Python Quiz Scoring and Conditional Statement Problems -

i've started learning python @ school around month now, , have decided make quiz. have added in scoring system if answer question incorrectly, tell score. however, not working , give score of 0. also, there way of putting 1 else statement if fail question, instead of 1 each question? :) here's example of code(python 3.2.3): #quiz print("welcome quiz") print("please choose difficulty:") difficulty = input("a) hard b)easy") if difficulty == "a": score = 0 print("") def question(score): print("you chose hard difficulty") print("where great victoria lake located?") answer1 = input("a) canada b)west africa c)australia d)north america") if answer1 == "c": print("correct") score = score+1 else: print("you failed quiz") print("score:",score) quit() def question2(scor

python - Regex Capture Multiple Phrases after One -

i trying figure out how make regex capture bunch of items come after 1 particular thing. using python this. 1 example of using text b <4>.<5> <6> <1> m<2> . <3> intent of capturing 1, 2, , 3. thought regular expression a.*?<(.+?)> work, caputures final 3 using python re.findall . can this? the regex module (going replace re in future pythons) supports variable lookbehinds, makes easy: s = "b <4>.<5> <6> a23 <1> m<2> . <3>" import regex print regex.findall(r'(?<=a\d+.*)<.+?>', s) # ['<1>', '<2>', '<3>'] (i'm using a\d+ instead of a make thing interesting). if you're bound stock re , you're forced ugly workarounds this: import re print re.findall(r'(<[^<>]+>)(?=(?:.(?!a\d+))*$)', s) # ['<1>', '<2>', '<3>'] or pre-splitting: print re.find

arrays - Unable to access element from Sort class c++ -

hey doing homework assignment compare different kinds of sorts efficiency.however having trouble accessing data element , feel dumb because feel should easy answer. here main function. int main() { //declarations int const myarraysize = 100; sort mysort(myarraysize); mysort.init_array(); clock_t timea = clock(); for(int = 0; < myarraysize; i++) { //run tests mysort.insertion_sort(/*whatgoeshere*/, myarraysize ); } clock_t timeb = clock(); clock_t diff = timeb - timea; system("pause"); } and here header class sort { private: int size; int *myarray; public: sort(int size); ~sort(); friend ostream& operator << (ostream& out, const sort& s) { //put code in here } void insertion_sort(int [], int); void selection_sort(int [], int); void merge_sort(int [], int); void quick_sort(int [], int); void partition(int [], int, int&);

Floating point system error estimation in terms of machine precision epsilon -

i'm doing question ask me derive upper error bound in terms of machine precision episilon computer estimation of express (x/z)*y given fl(fl(x)*fl(y)) = (x*y)(1-delta) my approach fl(fl(fl(x)/fl(z)) fl(y)) = xy/z (1-delta1)(1-delta2)(1-delta3)(1-delta4)/(1-delta5), don't know (1-delta5) since don't know how cancel term.

unix - trying to start XBMC with a bash from BOXEE -

hi new unix , bash programming. trying make simple startup script have boxee start xbmc stored on memory card. can start commands entering them in telnet, if call test.sh script wont allow me access directory xbmc stored on. #!/tmp/mnt/6337-3533/xbmc basedir=/tmp/mnt/6337-3533/xbmc $0 killall u99boxee; killall boxeelauncher; killall run_boxee.sh; killall boxee; killall boxeehal gconv_path=$pwd/gconv ae_engine=active pythonpath=$pwd/python2.7:$pwd/python2.7/lib-dynload xbmc_home=$pwd ./xbmc.bin -p gives: # sh test.sh : not foundne 2: : not foundne 3: test.sh: line 4: /tmp/mnt/6337-3533/xbmc: permission denied : not foundne 5: : not foundne 6: killall: u99boxee: no process killed killall: boxeelauncher: no process killed killall: run_boxee.sh: no process killed killall: boxee: no process killed : no process killed : not foundne 9: : not foundne 10: test.sh: line 11: ./xbmc.bin: not found # i used command line xbmc. , assume $pwd expects script in /tmp/mnt/6337-3533/xbmc i

MIPS errors and operation -

#if true perform matrix operation mul.s $f7, $f5, $f6 #m * a[d][c] add.s f7, $f7, $f5 #add (m*a[d][c])+col c div.s $f5, $f4, $f2 #divide -a[r][d]/a[d][d] , store m move $f3, $zero #setting [r][d] = 0 i'm receiving errors on add.s , mov register lines. help? you're missing $ -sign on line add.s f7, $f7, $f5 . should add.s $f7, $f7, $f5 . i don't know how assembler handles move instructions floating-point registers (or if does), i'd suggest using mtc1 $zero,$f3 instead. you'd follow cvt.s.w or cvt.d.w convert value floating point, in case of 0 isn't necessary.

php - mysqli bind_param vs '".$var."'; whats the difference? -

this question has answer here: how can prevent sql injection in php? 28 answers how can prepared statements protect sql injection attacks? 8 answers i'm trying figure out difference between using prepared statements , and escaping/converting variable string follows: $sql = "select `user_id`, `user_name` table `user_id` = ? , `user_name`= ?"; $sqlprepare = $conn->prepare($sql); $sqlprepare->bind_param('ss', $user_id, $user_name); $sqlprepare->execute(); $result = $ $sqlprepare->get_result(); if($result->num_rows ===0) { // work } vs mysqli::real_escape_string($whatever_vars_needed); $sql = "select `user_id`, `user_name` table `user_id` = '&qu

Java index out of bounds error -

i writing code in java plugin minecraft server, logical principles general in nature. public void doreviewmember(commandsender playersent) { if (!reviewsmember.isempty()) { review dothis = null; arraylist<review> players = new arraylist<review>(); arraylist<review> playersvip = new arraylist<review>(); arraylist<review> playersvipplus = new arraylist<review>(); (int c1 = 0; c1 < reviewsmember.size(); c1++) { if (bukkit.getplayer(reviewsmember.get(c1).getname()).haspermission("reviewplugin.vipplus")) playersvipplus.add(reviewsmember.get(c1)); else if (bukkit.getplayer(reviewsmember.get(c1).getname()).haspermission("reviewplugin.vip")) playersvip.add(reviewsmember.get(c1)); else players.add(reviewsmember.get(c1)); } if (playersvipplus.size() > 0) dothis = playersvipplus.get(0);

Any Idea how I generate random Char values in Java? I'm creating a random password generator -

this question has answer here: how generate random alpha-numeric string? 39 answers i'm creating random password generator in java , need how can generate random char values in program. ideas? i'm using menu system way show different types of passwords generate lowercase, uppercase, etc. any advice help. thanks! random r = new random(); string alphabet = "123xyz"; // prints 50 random characters alphabet (int = 0; < 50; i++) { system.out.println(alphabet.charat(r.nextint(alphabet.length()))); } instead of printing chars, add them stringbuilder , , have random password. (source)

c - Solving n linear equation -

i trying solve n linear equations n variables. used cramer's rule in cases failed when determinant equal zero. how approach problem ? i using c language. also linear equation of form: for n = 3 : - x + y + z = x - y + z = b x + y - z = c for n = 2 : - x + y = x - y = b i unable proceed further. when solving cramer, if determinant 0 have 2 cases: at least 1 variable has non 0 - determinant : there no solution the determinant variables zero : have infinite number of solutions. in last case, can find answer in terms of 1 of variables.

CSS3 Gradients and Transparency Combined? -

i need use cool gradients in current html5 mobile app, , wondering how can use css3 gradients achieve http://goo.gl/op63lu i made little fiddle try hands ( http://jsfiddle.net/yrxsk/ ) did not come close amazing gradients links above, , need help! background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#323232), color-stop(100%,#c62f35)); i want use these colours deep red: #c62f35 light red: #94b435 light red: #fff1e0 cool green: #fd4246 , other complementing colors it's not answer take @ http://www.colorzilla.com/gradient-editor/ tool generating sorts of gradients. for instance 1 more similar link pick radial drop down in top right.

javascript - Script file not loading -

i beating head against wall on this. know javascript/jquery , can not see reason why not working. i've tried both 2.0.3 , 1.10.2 same results. i'm trying test make sure script file loaded. i've tried number of different methods, nothing working. when click url in source, goes correct file has right code. this i'm trying do. $(document).ready(function() { alert('test'); }); which works if include in page between <script> tags. not when referencing .js file. this how i'm loading it: <script type="text/javscript" src="http://localhost/kdev/views/dashboard/js/default.js"></script> clicking on url takes me correct file alert above. but's not working. crap going on? did forget? have typo? the entire page: <!doctype html> <html> <head> <title>test</title> <link rel="stylesheet" href="http://localhost/kdev/public/css/default.css"

c++ - Given a 2D array, convert to Z-Order -

having trouble wrapping head around conversion. want recursively convert 2d nxn matrix z-order version. for example given array: [ 1 2 ] [ 3 4 ] the z-order [ 1 2 3 4] what steps recursively z-order conversion? the recursive way simple: visit top-left visit top-right visit bottom-left visit bottom-right in code #include <iostream> template<typename m, typename cback> void zorder(const m& m, int y0, int x0, int size, cback cback) { if (size == 1) { // base case, 1 cell cback(m[y0][x0]); } else { // recurse in z-order int h = size/2; zorder(m, y0, x0, h, cback); // top-left zorder(m, y0, x0+h, h, cback); // top-right zorder(m, y0+h, x0, h, cback); // bottom-left zorder(m, y0+h, x0+h, h, cback); // bottom-right } } void print(int x) { std::cout << x << " "; } int main(int argc, const char *argv[]) { int x[][4]

sql - Trigger to Truncate then Insert rows -

everyday, rows inserted sql server table (t_past). these rows records past (ie august 1, 2013) records in future (ie january 1, 2014). want leave past dated records in table (t_past), future date records, to: 1) delete them original table 2) insert them new table has future dated records (t_future) the thing is, future dated records can have changes in columns, instead of running update query well, prefer truncate t_future table, , reinsert records. everything works in sense proper records insert t_past, proper records delete t_past , t_future table truncated. problem when insert multiple future dated records, last record shows in t_future table, not of them. alter trigger [dbo].[trg_getfuture] on [dbo].[t_past] after insert begin truncate table dbo.t_future end begin insert dbo.t_future select * inserted date > getdate() end begin delete dbo.t_past date > getdate() end thanks!! this because truncating t_future table in trigger. every time trigger fired f

Compile Clojure using Maven -

what preferred way compile clojure using maven? in particular situation have set of clojure .clj files aot-compiled .class files during maven compilation phase, , included in resulting .jar . you can check out this maven plugin compile clojure code.

java ee - Tutorials on Core netty and Protobuf -

i working distributed systems(java/ee,netty,protobuf).wondering how send document client server , store in server database. sending string seems simple, how go sending big file. need chunk small messages , send over. any tutorials, on how work documents. i assuming you've done boilerplate code portion of netty, have running server protocol buffers interceptors set , you've generated protocol buffers related classes. if need these steps, please so, edit , add them. first thing first, serialising big chunks of data (anything may temper heap) no protobuf. simple thing(s) do; 1- byte stream (buffered) of content 2- construct protobuf message (ex: contentchunk) , add minimum 2 fields representing chunk order , chunk part (depending on concurrent traffic, chunk parts should not crack heap optimise size wisely) itself. chunk order server side reconstruct chunk in right order. 3- can add additional field inner framing of chunks or pass total length in first messag

c - gdb ptrace operation not permitted -

i'm trying attach programme gdb returns me: attaching process 29139 not attach process. if uid matches uid of target process, check setting of /proc/sys/kernel/yama/ptrace_scope, or try again root user. more details, see /etc/sysctl.d/10-ptrace.conf ptrace: operation not permitted. edb-debugger returns "failed attach process, please check privileges , try again." strace returns "attach: ptrace(ptrace_attach, ...): operation not permitted" i changed "kernel.yama.ptrace_scope" 1 0 , "/proc/sys/kernel/yama/ptrace_scope" 1 0 , tried "set environment ld_preload=./ptrace.so" this: #include <stdio.h> int ptrace(int i, int j, int k, int l) { printf(" ptrace(%i, %i, %i, %i), returning -1\n", i, j, k, l); return 0; } but still returns same error. how can attach debuggers? this due kernel hardening in linux; can disable behavior echo 0 > /proc/sys/kernel/yama/ptr

asp.net web api - Using own domain model/entity on client with wcf data service (uses web api/odata/entity framework) as service reference -

here's situation, i'm trying create wpf application connects own web odata service (uses web api , entity framework). have own set of domain models/entities in server side web api , entity framework works with. when, add web odata service reference in wpf client side, can't recognize own domain models/entities , looks creates own set of it. i'm trying possible or missing something? regards, raymond drive-by answer (unchecked): remember reading wasn't possible @ least few weeks back. might want search uservoice site , official forums current status, or wait better answer here.

c++ - Counter keeps repeating please provide answer -

now, learning c programming, stumbled upon countdown code on 'codeproject.com' , decided run , analyse learn. however, output countdown repeats each number thousands of times before moving next. please need understanding why is. code shown below: #include <stdio.h> #include <time.h> int main() { unsigned int x_hours = 0; unsigned int x_minutes = 0; unsigned int x_seconds = 0; unsigned int x_milliseconds = 0; unsigned int totaltime = 0, count_down_time_in_secs = 0, time_left=0; clock_t x_starttime, x_counttime; count_down_time_in_secs = 10; // 1 min 60 x_starttime = clock(); time_left = count_down_time_in_secs-x_seconds; //update timer while (time_left>0) { x_counttime = clock(); x_milliseconds = x_counttime-x_starttime; x_seconds=(x_milliseconds/(clocks_per_sec))-(x_hours*60); x_minutes=(x_milliseconds/(clocks_per_sec))/60; x_hours=x_minutes/60;

delegates - Notification Center vs. Delegation in iOS SDK -

why did apple choose use delegation communication amongst sdk objects , post notifications notification center others? in particular, i'm thinking set of keyboard appearance notifications come uiwindow. is because notification center system means more 1 object can use keyboard appearance action trigger change state, whereas 1 object have been able act delegate implementation? delegation allows execute methods (and pass parameters) 1 class another. allows method fired when class not imported. delegation allows multiple view controllers (or otherwise classes) fire methods in single view controller. notification center, on other hand, listens , waits until hears message waiting for. allows multiple listeners in multiple view controllers wait , listen given message. you delegation 1/many 1 relationship while notification center 1/many 1/many relationship.

php - Add the correct number of days for each month -

using following function can display years , months between 2 dates, how can add correct days each month array within each month? can't add days manually need account leap years etc. function yearmonth($start_date, $end_date) { $begin = new datetime( $start_date ); $end = new datetime( $end_date); $interval = new dateinterval('p1m'); // 1 month interval $period = new dateperiod($begin, $interval, $end); foreach ( $period $dt ) $years[$dt->format( "y" )][] = $dt->format( "f" ); return $years; } $list = yearmonth("2007-03-24", "2009-06-26"); var_dump($list); since nobody else answered: function yearmonth($start_date, $end_date) { $begin = new datetime( $start_date ); $end = new datetime( $end_date); $interval = new dateinterval('p1d'); // 1 month interval $period = new dateperiod($begin, $interval, $end); $lastmonth = null; $lastyear = null; $aresult = array(); forea

javascript - Select the first enabled option in a select element -

how set value of select element first enabled option? have html this: <select name="myselect" id="myselect"> <option value="val1" disabled>value 1</option> <option value="val2">value 2</option> <option value="val3" disabled>value 3</option> <option value="val4">value 4</option> </select> how select first option isn't disabled (here val2)? try selecting first option enabled. $('#myselect').children('option:enabled').eq(0).prop('selected',true); .children() finding list of option enabled , .eq(0) choosing first entry on list , using .prop() select option

how to make fortran code to remove coordinate of particles from input file to avoid overlapping -

i had configuration 1804 particles particles overlap. try make fortran code remove co-ordinates of particles. got error. please me. program check_overlap implicit double precision (a-h,o-z) parameter (maxatom = 20000000) dimension rx(maxatom), ry(maxatom), rz(maxatom) real drmax character resname*(5),atomname*(5) character box_par drmax = 0.15 open (10, file = 'conf.gro') read (10,*) box_par read (10,*) nn 100 ipart = 1, nn read(10,99) numres,resname,atomname,numatom, & rx(ipart), ry(ipart), rz(ipart) 99 format (i5,2a5,i5,3f8.3) 100 continue close(10) 200 = 1, nn-1 rxi = rx(i) ryi = ry(i) rzi = rz(i) 300 j = i+1 , nn rxij = rxi - rx (j) ryij = ryi - ry (j) rzij = rzi - rz (j) rijsq = rxij*rxij + ryij*ryij + rzij*rzij if ( rijsq.lt.25) rxiold = rxi ryiold = ryi rziold = rzi

html - Position:Relative image that doesn't push nearby text? -

simple question: need image appear in middle of paragraph of text, however, image larger height of each line of font, pushes open horizontal "gap" in text make room itself. fix this, could: 1) shrink image, not larger font. 2) use position:absolute but don't want shrink further, small enough "technically fit" between each line of text, except need use few pixels of white area above , below line of text in. and can't use position:absolute, because image's position in top left corner of window, instead of in paragraph want it. i thought perhaps put dummy "placeholder" image of size 1 pixels paragraph. then, use position:absolute on real image, , continually set real image @ same location dummy image is. haven't researched see if possible, seems bit excessive such simple thing. there easier way? edit: found adding: margin:-20px; image's style works!!! margin:-20px; jsfiddle example: http://jsfiddle.net/j7tlx/3/ i

php - How to Make Checkboxes Into Array In Dreamweaver -

i designing seat reservation system. want check boxes represent seats. want know how make each check boxes array , how group check boxes in single canvas store multiple values in 1 single variable in database column. i using dreamweaver , php. you should below: <input type="checkbok" value="1" name="seat[]" /> <input type="checkbok" value="2" name="seat[]" /> <input type="checkbok" value="3" name="seat[]" /> <input type="checkbok" value="4" name="seat[]" /> ....

java - How to use methods and call them within the Switch statement -

i'm making tax calculator class can't quite figure out how separate code in individual cases println("please enter filing status: "); println("enter 0 single filers,"); println(" 1 married filing jointly,"); println(" 2 married filing separately, or"); println(" 3 head of household"); double tax = 0; decimalformat df = new decimalformat("#.00"); int filingstatus = readint("status: "); switch (filingstatus) { case 0: double taxableincomes = readdouble("please enter taxable income: "); if (taxableincomes <= 8925) { tax = (taxableincomes * ten); println("you owe: $" + df.format(tax)); } if (taxableincomes > 8925 && taxableincomes <= 36250) { tax = 892.5 + fifteen * (taxableincomes - 8925); println("you owe: $" + d

c++ - internal working of placement new? -

in 1 interview asked that suppose have 25 mb of memory , have 3 processes of 10 mb each. how assure process should not run out of memory ? i replied if use placement new survive. asked me how relate placement new realloc ? i want know placement new related realloc ? realloc isn't valid placement new. since memory might end in new location, pointers referring object become invalidated, pointers contained within objects themselves. think of linked list example. the interviewer looking mention of virtual memory.

parsing - Scala equivalent of java.util.Scanner -

i familiar using java.util.scanner next() , hasnext() , nextint() , nextline() , , parse input. is there else should use in scala? this data isn't structured according grammar; it's more ad-hoc that. for example, lets had inventory. each line of input starts name, has quantity of items, has ids items firetruck 2 a450m a451m machine 1 qzlt keyboard 0 i see console has methods such readint() , reads entire line of input; equivalent of nextint() doesn't seem exist. java.util.scanner trick. there else should use (for example, returns scala rather java types)? no there no equivalent scala implementation. don't see reason 1 java.util.scanner work fine , java primitives types converted scala types implicitly. so "for example, returns scala rather java types", scanner return scala types when used in scala.

javascript - how to update the styles to a listview in jquery mobile? -

i getting data server , create ul list trying update styles. it seems listview('refresh',true) doesn't work. using jqm 1.4 beta function parsedata(data) { var html = '<ul data-role="listview" data-autodividers="true" data-filter="true" data-inset="true">'; $.each(data, function( index, value ) { html = '<li>' + '<div data-role="collapsible">' + '<p>' + value.title + '</p>' + '</div>' + '</li>'; }); html += '</ul>'; return html; } var div = $('#div'); div.html(parsedata(data)); div.find('ul').listview('refresh',true); jsfiddle an ideas? as of jquery mobile 1.4 alpha 2 , .trigger('create') , .trigger('pagecreate') deprecated , removed 1.5. the replacement of function .enhance

ajax - JQuery: How to select specific element of a class by data-, then use as target? -

i've modified code tutorial ( http://gazpo.com/2011/09/contenteditable/ demo: http://gazpo.com/downloads/tutorials/html5/contenteditable/ ) show more 1 div of contenteditable div database, , through ajax, save changes of modified . here's php produces: http://jsfiddle.net/fmdx/78rwq/ <div data-id="0" class="wrap"><!-- content wrapper --> <div data-id="0" class="status"></div> <div data-id="0" class="content"> <p data-id="0" style="padding-left:7px;"> <span data-id="0" style="padding-right:10px;">a)</span> <span data-id="0" data-primary="1" data-comcounted="0" data-showcom="1" data-fileno="cttest" data-part="1" class="editable" contenteditable="true">compliance terms , conditions of clearwater ordi

How to execute the code at particular time in java -

this question has answer here: run program or method @ specific time in java 4 answers i have requirement saying want execute mailing code without event based on timer when specified time comes code execute , mail has send . package com.uttara.reg; import java.util.timertask; public class timer extends timertask { @override public void run() { // todo auto-generated method stub } } i can't understand how call timer class could plz me out!!! in advance you can try few things 1 : timer class 2 : timertask class 3 : quartz 4 : cron 5 : scheduler or if have simple requirement then step 1 : create thread time step 2 : in thread keep if(time_by_thread == time_want_to_execute) { //execute timer code here }

python 2.7 - How to remove <?xml version="1.0" encoding="utf-8"?> when using "xml" in Beautiful Soup -

from bs4 import beautifulsoup xmlcontent = "some text <tags>" bs = beautifulsoup(xmlcontent, "xml") print bs outputs: <?xml version="1.0" encoding="utf-8"?> text <tags> is possible not output: <?xml version="1.0" encoding="utf-8"?> i know if using lxml , remove added <body> tags do: bs = beautifulsoup(xmlcontent, "lxml") print bs.body.next is there equivalent use xml xml version , encoding not included? i choosing use xml on lxml contents being parsed in xml format - best choice or can use lxml xml content? this seems work: from bs4 import beautifulsoup xmlcontent = "some text <tags>" bs = beautifulsoup(xmlcontent, "xml") bs = bs.encode_contents() print type(bs) # it's string print bs # text <tags>

c - Why doesn't the printout of this program stop at the 0 digit? -

#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char* key="844607587"; while(*key!=0){ printf("hello world,%c\n",*key); key++;} } why doesn't program stop @ 0 digit? 0 mean? 1 without ' ' you made simple mistake - comparing (most ascii) characters in string numeric value 0. change: while(*key!=0){ to while(*key!='0'){ note numeric value 0 value of c string terminator, written '\0' , code stops when reaches end of string, rather when sees character '0' .

visual c++ - How to specify negative range for slider control? -

i developing mfc based sdi vc++ application. in application need specify negative range value slider control. minimum range slider -40 , maximum range 255. tried using setrange function. not working. how can set range in slider?please help.. my code slider follows: slider declared csliderctrl m_ctrlectslider; oninitialupdate function contains m_ctrlectslider.setrangemin(-40); int ivalmin = m_ctrlectslider.getrangemin(); m_ctrlectslider.setrangemax(255); int ivalmax = m_ctrlectslider.getrangemax(); m_ctrlectslider.setpos(0); setdlgitemint( idc_ect_value, m_ctrlectslider.getpos(), false); setdlgitemint( idc_min_ect, ivalmin, false); setdlgitemint( idc_max_ect, ivalmax, false); onbnclickedset function contains int nmin = getdlgitemint(idc_min_ect, 0, false); int nmax = getdlgitemint(idc_max_ect, 0, false); m_ctrlectslider.setrange(nmin, nmax); m_ctrlectslider.setpos(nmin); int pos = m_ctrlectslider.getpos(); setdlgitemint(idc_ect_value, m_ctrlectslider.getpos(), false);

c# - Why is dictionary lookup slower than recursive search? -

i trying optimize search node in treenodecollection . original method uses recursive approach: public ugtreenode findnode(baseid nodeid, treenodecollection nodes) { foreach (ugtreenode n in nodes) { if (n.node_info.description.base_id.id == nodeid.id && n.node_info.description.base_id.rootid == nodeid.rootid && n.node_info.description.base_id.subid == nodeid.subid) return n; ugtreenode n1 = findnode(nodeid, n.nodes); if (n1 != null) return n1; } return null; } i tried storing nodes in dictionary , use dictionary.trygetvalue search node: public ugtreenode findnode(baseid nodeid, treenodecollection nodes) { ugtreenode res; _nodescache.trygetvalue(nodeid.id, out res); return res; } but turns out second approach way slower first (appoximately 10 times slower). possible reasons this? the recursion may faster when search 1 of first items in tree. depends

jquery - code on jsfiddle vs active server (code on active server isn't working correctly) -

here problem, put piece of code in jsfiddle, , works perfectly. put same code on website, adding in header include jquery , jquery ui (links directly jquery sites, not hosting files locally) , code doesn't work. i attempting "sortable" effect work in project. not code either. been every single piece of code has draggable, movable, etc. uses jquery. i'm missing , can't think of is. i own servers in datacenter, , running cpanel, have full access server if need make changes. when test code on jsfiddle, when click , drag tags, doesn't highlight text , moves <li> tags allowing me reorder list. on website, starts highlighting text , doesn't move file. html same on both places. any ideas? jsfiddle : http://jsfiddle.net/ygrup/ code: (some of code still there interacts php code; however, removed php code example testing) <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/

c# - TCP server with multiple Clients -

i working on tcp server/client application. my question is: my server application starts new thread , blocks until connection accepted listenforclient method but how can manage connections when multiple clients connected server , request different things @ same time how can manage client 1 gets info need , same client 2. it's multithreaded, multiple clients can connect how can process request. don't want put in 1 method would. thanks in advance private void serverstart() { this.tcplistener = new tcplistener(ipaddress.any, 49151); this.listenthread = new thread(new threadstart(listenforclients)); this.listenthread.start(); } private void listenforclients() { this.tcplistener.start(); while (true) { //blocks until client has connected server tcpclient client = this.tcplistener.accepttcpclient(); // here first message send hello client //

javascript - how to remove all style except font-weight using jquery in all elements -

i using nicedit editor in app , users of our website use paste data ms word or other sources, hence ui breaks up, have decided remove formatting html using jquery. what did removed inline style , class, creating problem removing bold , italics too, want retain it. is simple way of removing style except bold using jquery. example : <div style="color:red; font-size:13px; font-weight:bold;">test div </div> in above element want as <div style="font-weight:bold;">test div </div> i think way store styles want, remove them , set them again. $('.selector').each(function() { var keepstyle, $el; $el = $(this); keepstyle = { font-weight: $el.css('font-weight'), font-style : $el.css('font-style') }; $el.removeattr('style') .css(keepstyle); })