Posts

Showing posts from June, 2010

c# - Using WebImage() with .gif images -

i trying use webimage uploaded .gif image. webimage file = new webimage(fullfilepath + ".gif"); file.save(newimage); i error stating: system.exception: graphics object cannot created image has indexed pixel format. how can use .gif webimage class?

xml - Counting only specific element -

edit: sorry question bit unclear, i'm trying return text in p nodes , children while counting individual p nodes. <1> refers first p node, <2> second , on. i'm trying count occurrence of individual element regardless of appears in structure of xml document. i've tried variations of position() , count() both , without for-each loops , can't seem find work. have idea on how this? an example document be: <text> <body> <div1> <p>abc</p> <div2> <p>def</p> </div2> </div1> <div1> <p>ghi</p> <div2> <p>jkl <name>adam</name></p> <div3> <p>mno</p> </div3> </div2> <p>qrs</p> </div1> </body> </text> with return: <1>abc <2>def <3>ghi <4&g

ruby - Rake dependency not executing but invoke works -

i've been trying run rake db:test:clone_structure , keeps failing rebuild database. looked @ task itself: task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ] when run trace, i've noticed db:test:load_structure isn't getting executed: $ rake db:test:clone_structure --trace ** invoke db:test:clone_structure (first_time) ** invoke db:structure:dump (first_time) ** invoke environment (first_time) ** execute environment ** execute db:structure:dump ** invoke db:test:purge (first_time) ** invoke environment ** execute db:test:purge ** execute db:test:clone_structure now, when change clone_structure task invoke load_structure ... task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ] db_namespace["test:load_structure"].invoke end ...everything works! $ rake db:test:prepare --trace ** invoke db:test:clone_structure (first_time) ** invoke db:structure:dump (

ios - Can I get by by without ever using KVO? -

strange grammar, want ask if there cases if don't kvo (key value observation), app can't things/features? thanks key value observing offers functionality , behaviors unique , useful developer, in same cases offering glimpse @ values otherwise opaque. for example, if want know precise duration of animation in cocoa otherwise black-box (for example, keyboard disclosure animation duration), kvo way know of establish that. beyond that, it's useful pattern programming applications involve data (go figure). such, yet tool in developer's toolkit. can without it? sure. there many tools can without, , 1 takes little bit of effort wrap head around initially. should make point of avoiding it? no, don't think - why you?

xamarin.ios - No devices attached in xamarin VisualStudio for ios -

Image
i'm having real trouble when try use ios emulator visual studio. created hello world app in vs using xamarin (latest stable version), set project main project, , when refresh connexion mac, can't select device should shown in selectlist. message "no device attached" : and if try use xamarin studio on host mac, okay, sample app builds on iphone emulator: thanks me ! are sure device connected mac , not windows machine? have tried debugging same device xamarin studio on mac?

How to indent a multi-line paragraph being written to the console in java -

can suggest method writing mutli-line string system console , having text block indented? i'm looking relatively lightweight because it's being used displaying command line program. note: approach described below not meet updated requirements described @billman in question's comments. will not automatically wrap lines longer console line length - use approach if wrapping isn't issue. simple option, use string.replaceall() follows: string output = <your string here> string indented = output.replaceall("(?m)^", "\t"); if you're unfamiliar java regular expressions, works follows: (?m) enables multiline mode. means each line in output considered individually, instead of treating output single line (which default). ^ regex matching start of each line. \t causes each match of preceding regex (i.e. start of each line) replaced tab character. as example, following code: string output = "foo\nbar\nbaz\n"

html - Play Flac files on website -

is there way play flac files on website, preferably using html5 and/or jquery? i don't know in-browser flac player. but, if after loseless file format, can consider mp3hd , loseless, flac, backwards compatible mp3, means mp3 player can play it.

url - Trying to open an application with parameter via an Application Protocol Handler -

i trying figure out issue application protocol handler i've created. following directions listed on msdn ( http://msdn.microsoft.com/en-us/library/aa767914%28v=vs.85%29.aspx ), able register application, pdf annotator , open via url. issue experiencing when try pass parameter along call. application open, file parameter gets passed not opening within application. my registry key verbatim dictated msdn. html code follows: pdfannotator:c:\path\to\file\file.pdf the way understood protocol handler takes url , tries launch via command line. being said, able open pdf file in pdfannotator following command in prompt: pdfannotator.exe c:\path\to\file\file.pdf i've tried formatting file path in html differently thinking issue too. has else come across issue or similar? obligatory update future generations ( http://xkcd.com/979/ ) : the reason doing because half of pdfs application handled editable while other half read-only. trying keep read-only ones in brows

Symfony how to extend collection form field -

i'm trying extend collection form in order render own template... class contactfieldtype extends abstracttype { public function setdefaultoptions(optionsresolverinterface $resolver) { $resolver->setdefaults(array( 'collection' => array('type' => new contacttype()) )); } public function getparent() { return 'collection'; } public function getname() { return 'contactfield'; } } and use type in way: $builder->add('contacts',new contactfieldtype(), array( 'label_attr' => array('class' => 'contacts') )); i'm getting following error: the form's view data expected of type scalar, array or instance of \arrayaccess, instance of class myapp\mainbundle\entity\contact. can avoid error setting "data_class" option "myapp\mainbundle\entity\contact" or adding view transformer transforms instance of class myapp\mainbun

javascript - how can I log every method call in node.js without adding debug lines everywhere? -

i log user_id of person making request , method name of every method called javascript class. example: 35 - log_in 35 - list_of_other_users 78 - log_in 35 - send_message_to_user 35 - connect_to_redis 78 - list_of_other_users since async user 35 , 78 might doing stuff @ same time. want make sure each log line starts user_id can grep , see 1 user's activity @ time. is there super clever way without adding logger statements every method? i'm guessing web app, in case if using connect can use logger middleware logs user , url path, sufficient. otherwise, going have metaprogramming along lines of wrapping each function in wrapper function logging. function logcall(realfunc, instance) { return function() { log.debug('user: ' + instance.user_id + ' method ' + realfunc.name); return realfunc.apply(instance, arguments); }; } for work, class method's must named functions, not anonymous. function sendmessage() { //code

php - insert into database session variable -

can please ? trying insert session variable part of dtabase row. other fields enter correctly 4 session variables declared @ top dont enter blank field in database. can tell me how insert session variable data please <?php if(isset($_post['score'])) { require "dbconn.php"; $home = $_session['home']; $away = $_session['away']; $gameid = $_session['gameid']; $date = $_session['date']; $batsman = strip_tags($_post['batsman']); $bowler = strip_tags($_post['bowler']); $extras = strip_tags($_post['extras']); $wickets = strip_tags($_post['wickets']); $runs = strip_tags($_post['runs']); $over = strip_tags($_post['over']); $penalty=$runs+1; if ($extras == "none") {// sql insert statement add appropriate record / wide adds 1 + score onto bowler , total mysql_query (" insert statitstics2 (home,

jQuery's getScript function, wait for the retrieved variable -

i have jquery getscript function: jquery.getscript(script,function() { src = an_ajax_request; }); the problem is, need variable outside function, make string: if(src == "") string = "string"+src; //i empty src value here! but if getscript function takes longer load (loading async), src value in console, src still empty when try build string. question: how can make string generation wait src value retrieved getscript function? in ajax request, this. $.ajax({ url: "getsrc", success: function(src){ string = "string"+src; } });

php - prepared statements UPDATE -

i getting below error when try update query using mysqli prepared statements. wrong error message why unexpected? help. parse error: syntax error, unexpected '$prob' (t_variable) here query $mysqli = new mysqli("localhost", "root", "", "newlogin"); if ($mysqli->connect_errno) { echo "failed connect mysql: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $check = $mysqli->prepare("select * `vpb_uploads` `username` = ? , `firstname` = '' , `image_one` != ''"); $check->bind_param('s', $username); $check->execute(); $check->store_result(); if($check->num_rows < 1) { echo '<div class="vpb_error_info" align="left">sorry, seems have not added file yet.<br>please click on add files button first of add @ least 1 file before s

python - ValueError: math domain error -

i testing example numerical methods in engineering python . from numpy import zeros, array math import sin, log newtonraphson2 import * def f(x): f = zeros(len(x)) f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0 f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0 f[2] = x[0] + x[1] + x[2] -5.0 return f x = array([1.0, 1.0, 1.0]) print newtonraphson2(f,x) when run it, shows following error: file "example nr2method.py", line 8, in f f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0 valueerror: math domain error i have narrowed down log when remove log , add different function, works. assume because of sort of interference base, can't figure out how. can suggest solution? your code doing log of number less or equal zero. that's mathematically undefined, python's log function raises exception. here's example: >>> math import log >>> log(-1) traceback (most recent call last): file "<pyshell#59>"

sql server - Grouping multiple queries on same table , TQSL -

i have rather large table of inormation needs filtered differently several different work departments. created below query returns same number of columns should able union'd up. want make sure no duplicate rows returned, hence reason used union, keep getting error "msg 8120, level 16, state 1, line 53 column 'act_dw.dbo.inv-act.dnum' invalid in select list because not contained in either aggregate function or group clause." see issue here? looking 1 big table of records grouped deskname field per workgroup if possible. declare @inventoryasofeod date, @start date, @end date set @start = cast(dateadd(month, datediff(month, 0, getdate()),0) date) set @end = cast(dateadd(day, -(day(dateadd(month, 1, getdate()))), dateadd(month, 1, getdate())) date) if datename(dw, getdate()) = 'monday' begin set @inventoryasofeod = cast(dateadd(d, -3, getdate())as date) end else set @inventoryasofeod = cast(dateadd(d, -1, getdat

c++ - Sublime Text 2 (or/and Xcode): Alternating background color for consecutive methods/functions? -

i wondering if there way display methods/functions of .cpp file alternating background colors, spot these methods begin , end when browsing code. same question xcode? for example: // here starts light grey bg void method1(){ ... } // starts dark grey bg void method2(){ ... } // again light grey bg void method3(){ ... } // etc... thanks!

command line - Open Port 3306 via SSH -

i trying access remote mysql database godaddy vps. have enabled remote access on server need open 3306 port on godaddy's vps. told suppor need via ssh not able me further that. have connected server via ssh. have run following command: telnet myserver.com 3306 when rund command following message, shost not allowed connect mysql serverconnection closed foreign host . how open port allow me connect remote mysql database? use port forwarding. ssh -l 3306:localhost:3306 myserver.com (i assume ssh server running ssh myserver.com .) then, while connection active, connect database on localhost instead of myserver.com (e.g. test using telnet localhost 3306 ). more details in ssh manual .

php - autosum in pdf file -

i want auto sum in pdf, example, when tick checkbox, automatically calculate sum of ticked box. here code: if($books){ $i=1; foreach($books $b){ if($b->code){ $bodycontent .= '<tr><td>'.$i.'</td><td><input type="checkbox" name="g'.$i.'" value="0" /></td><td><input type="checkbox" name="d'.$i.'" value="0" /></td><td><input type="checkbox" name="u'.$i.'" value="0" /></td><td>'.$u->code.': '.$u->name.'</td></tr>'; $i++; } } $bodycontent .= '<tr><td></td><td><input type="text" name="g_total" size="3" /></td><td><input type="text" name="d_total" size="3" /></td><td><input type="text"

browser - VB.NET - Auto fill Rich Text Box in WebBrowser? -

hi everyone. i'm trying make program auto fill form in webbrowser. html code looks this: <body contenteditable="true" class="forum" spellcheck="true" style="height: auto;"> text here! <br></body> how make input text here? thanks.

image processing - Is the Sobel Filter meant to be normalized? -

the x-derivative sobel looks way: -1 0 +1 -2 0 +2 -1 0 +1 lets there 2 samples of image (0=black, 1=white): 0 0 1 1 0 0 0 0 1 & 1 0 0 0 0 1 1 0 0 if perform convolution i'll end 4 , -4 respectively. so natural response normalize result 8 , translate 0.5 - correct? (i wondering can't find wikipedia etc. mentioning normalization) edit: use sobel filter create 2d structure tensor (with derivatives dx , dy): b structure tensor = c d = dx^2 b = dx*dy c = dx*dy d = dy^2 ultimately want store result in [0,1], right i'm wondering if have normalize sobel result (by default, not in order store it) or not, i.e.: a = dx*dx //or = (dx/8.0)*(dx/8.0) //or = (dx/8.0+0.5)*(dx/8.0+0.5) a mathematically correct normalization sobel filter 1/8, because brings result natural units of 1 gray-level per pixel. in practical programming, isn't right thing do.

PHP Sort XML Elements by Date -

below xml file <?xml version="1.0"?> <calender> <task> <date>00/00/0000</date> <title>my birthday</title> <description>today birthday!</description> </task> <task> <date>04/08/2013</date> <title>test</title> <description>swdefswde</description> </task> <task> <date>04/02/2013</date> <title>test</title> <description>test</description> </task> <task> <date>04/01/2013</date> <title>egfwe</title> <description>wefwef</description> </task> <task> <date>04/03/2013</date> <title>ssdv</title> <description>ssdvs</description> </task> </calender> i'm trying add them array, , resort elements date [then rewrite xml file sorted xml]. can please me? i have tired following code doesnt work [cant add them array] $xml_

java - I am trying to log text from the console to a text file, and the text file isn't being created -

here code, wondering why isn't logging anything. when type console says: hello apr 08, 2013 10:13:47 pm java.util.logging.logmanager$rootlogger log info: hello however, nothing being logged files. import java.io.ioexception; import java.util.scanner; import java.util.logging.filehandler; import java.util.logging.level; import java.util.logging.logger; import java.util.logging.simpleformatter; public class main { public static void main(string[] args) throws ioexception{ while (1 == 1) { string text; scanner in = new scanner(system.in); text = in.nextline(); filehandler filetxt; simpleformatter formattertxt; logger logger = logger.getlogger(""); logger.setlevel(level.info); filetxt = new filehandler("../loggedtext.txt"); formattertxt = new simpleformatter(); filetxt.setformatter(formattertxt); logger.addha

Correct combination of escape characters to inject PHP in javascript? -

i've tried combination know of can't right! echo <<<eof <a href="javascript:popup('$comments')">popup!</a> eof; i want pass string contained in $comments popup, can't seem right combination of escape characters , concatenation. pls! tia edit: html goes string mentioned. $comments.= "<b>" . $row['comname'] . "</b><br><i>" . $row['comment'] . "</i><br><br>"; you need escape string valid javascript/json first preserve javascript syntax, escape javascript preserve syntax of html it's embedded in: $js = sprintf('javascript:popup(%s)', json_encode($comments)); printf('<a href="%s">popup!</a>', htmlspecialchars($js)); since quite pain, should try go unobtrusive javascript , separates javascript html.

php - How to I disable the textbox by default and enable it later? -

how disable textbox default , let user enable via checkbox? <input type="checkbox" id="sccb" name="science" value="science"> <script type="text/javascript"> $(document).ready(function(){ $('#sccb').click(function(){ if (this.checked) { $('#cns').removeattr("disabled"); } else { $("#cns").attr("disabled", true); } }); }); </script> <input type="text" id="cns" name="coornamescience" disabled="disabled" size="30"></input> use disabled="disabled" textbox , use js/jquery enabled on click demo - http://jsfiddle.net/jacme/ <textarea rows="4" cols="50" disabled="disabled" id="mytextbox"> </textarea> <input type="checkbox" id="checkbox1" /> and use javascript/jquery -

ios - Setting constraints programmatically -

i'm experimenting how use uiscrollview. after trouble, got hang of it. i've seem hit snag. in simple app, have scroll view , in order work, have set view's bottom space scrollview constraint 0 described here , works fine. i'm doing through ib. now i've come across scenario have part programmatically. i've added below code in viewdidload method. nslayoutconstraint *bottomspaceconstraint = [nslayoutconstraint constraintwithitem:self.view attribute:nslayoutattributebottom relatedby:nslayoutrelationequal toitem:self.scrollview attribute:nslayoutattributebottom multiplier:1.0

c++ - Program stops parsing when last position of string is punctuation -

so i'm trying read words file, , rid of punctuation that. here logic stripping punctuation: edit: program stops running altogether, want make clear ifstream file("text.txt"); string str; string::iterator cur; for(file>>str; !file.eof(); file>>str){ for(cur = str.begin(); cur != str.end(); cur++){ if (!(isalnum(*cur))){ cur = str.erase(cur); } } cout << str << endl; ... } say have text file reads: this program. has trouble (non alphanumeric chars) it's own , love it... when cout , endl; string right after bit of logic, i'll get this program has trouble non alphanumeric and that's folks. there wrong iterator logic? how fix this? thank you. the main logical problem iterators see non-alphanumeric characters iterator gets increased twice: during erase moves next symbol , cur++ for loop increases it, skips every symbol after non-alphanumeric one. so a

playframework - Migrating from Play framework 2.0.4 to 2.1.0 is not working -

i have followed instructions migration http://www.playframework.com/documentation/2.1.0/migration still getting following errors: [error] .../app/views/index.scala.html:4: not found: value http [error] @import helper._ please provide feedback or input if have seen similar issues while migrating. note: index.scala.html similar http://www.playframework.com/documentation/2.1.1/javatodolist

how do you use the second parameter in the inflate method of the LayoutInflater class, Android -

the inflate method of layoutinflater abstract class has second parameter of inflate method takes viewgroup root. documentation, mentioned "optional view parent of generated hierarchy." can give example on how use parameter? , put in there? viewgroup can type of layout linearlayout . i have not quite understood parameter. if view inflating not part of layout entered here give error. don't understand purpose of it. more documentation: public view inflate (xmlpullparser parser, viewgroup root) added in api level 1 inflate new view hierarchy specified xml node. throws inflateexception if there error. important performance reasons, view inflation relies heavily on pre-processing of xml files done @ build time. therefore, not possible use layoutinflater xmlpullparser on plain xml file @ run time. parameters parser xml dom node containing description of view hierarchy. root optional view parent of generated hierarchy. returns root view of inflated h

unix - Error in installing SimpleDB::Class -

i try install simpledb::class cpan sudo cpan simpledb::class. needs dependency memcached::libmemcached. try install it, have following errors. ccld clients/memstat cc tests/atomsmasher.o ccld tests/atomsmasher cxx tests/tests_hashplus-hash_plus.o ./config/depcomp: line 611: exec: g++: not found make[2]: *** [tests/tests_hashplus-hash_plus.o] error 127 make[2]: leaving directory `/home/vanitha/.cpan/build/memcached-libmemcached-0.4406- oq4z_m/src/libmemcached' make[1]: *** [install-recursive] error 1 make[1]: leaving directory `/home/vanitha/.cpan/build/memcached-libmemcached-0.4406- oq4z_m/src/libmemcached' make: *** [install] error 2 unable build libmemcached: error running cd src/libmemcached && make install aborted. no 'makefile' created timb/memcached-libmemcached-0.4406.tar.gz /usr/bin/perl makefile.pl installdirs=site -- not ok running make test make had problems, won't test running make install make had problems, won't inst

redirect - How to fix my url in spring framework -

i working spring mvc3.2 , have registration form( http://my-server.com:8080/tracks/apks ). users post server , server return error message when validation fails. got error message server, url different wanted. here code: web.xml <servlet-mapping> <servlet-name>tracks</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> applicationcontext.xml <bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix"> <value>/web-inf/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> @controller @requestmapping("/apks") public class apkcontroller { @requestmapping() public modelandview index() { map<string, object> modelmap = new hashmap<string, object>(); modelmap.put("

r - Convert string to single digits and sum -

i've tried hours find solution thought easy task failed. i have string consisting of 3 different characters ('i','r' & 'o') length 1 6. e.g irrroo rrorrr iir rirro each character represents number i=1,r=2,o=3 need convert string single number, multiply position , sum result. e.g irrroo ---> (1*1)+(2*2)+(2*3)+(2*4)+(3*5)+(3*6) =52 iir ---> (1*1)+(1*2)+(2*3) =9 thanks in advance help. factors have numeric equivalents. can leverage nicely example: # original x1 <- "irrroo" # 1 2 3 levs <- c("i", "r", "o") # split string , convert factors, numeric x1f <- as.numeric(factor(strsplit(x1, "")[[1]], levels=levs)) # tally sum(x1f * seq_along(x1f)) or nice, single-line function: sumvalue <- function(x, levs=c("i", "r", "o")) sum(seq.int(nchar(x)) * as.numeric(factor(strsplit(x, "")[[1]], levels=lev

Speeding up maven assembly of multiple modules -

i'm having project of following form - pom.xml - projecta - pom.xml - src/main/ - java - startupscript - projectb - pom.xml - src/main/ - java - startupscript - projectassembly - pom.xml i want projectassembly produce tar.gz contain 2 folders 1 projecta , 1 projectb, in each folder, there project's dependencies , startupscript library. the "naive" way add assembly.xml file each project, file looks like: <assembly> <formats> <format>tar.gz</format> </formats> <basedirectory>/${project.artifactid}</basedirectory> <filesets> <fileset> <directory>${basedir}/src/main/startupscripts</directory> <outputdirectory>/startupscripts</outputdirectory> </fileset> </filesets> <dependencysets> <dependencyset> <outputdirectory>/lib</outputdirectory> </dependencyset> </dependencys

android - Intercept Incoming SMS Message and Modify it -

is there way intercept incoming sms message, , modify before presenting user? can done natively on iphone / andriod? can done using phonegap? can done using monotouch / mono andriod? if yes of above, please provide pointers it? my preferred-solution priority-order follows: phonegap mono native thank in advance!! edit: for people wondering purpose of this, put word "label" in sms depending on content, when view sms, can see "important: blah blah blah", instead of "blah blah blah". try out this- //register class receiver in manifest file sms_received intent public class smsreceiver extends broadcastreceiver { private static final string sms_received = "android.provider.telephony.sms_received"; @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(sms_received)) { abortbroadcast();**this prevent message deliver user** bun

spreadsheet - How to eliminate empty rows in excel upload from PHP using PHPExcel upload? -

i in middle of development. want eliminate empty rows while upload excel php using php excel plugin. while($x<=$excel->sheets[0]['numrows']){ $y=1; while($y<=$excel->sheets[0]['numcols']){ $cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : ''; if($excel->sheets[0]['cells'][$x][$y] == $excel->sheets[0]['cells'][$x][1] ){ echo $cell; } else { echo $cell; } $y++; } $x++; } i used code values excel php, if excel has empty record result modified cells. how can fix this. if (!array_reduce( $excel->sheets[0]['cells'][$x], function ($state, $value) { return $state && !($value > ''); }, true )) { // execute while($y<=$excel->sheets[0]['numcols']) loop here }

c# - How to get events of type by reflection ignoring events on parent interfaces -

i have following code type type = ... var events=type.getevents( bindingflags.declaredonly | bindingflags.instance | bindingflags.public).tolist(); however returning me events declared on parent interfaces. example both uielement contentelement implement iinputelement which defines event // // summary: // occurs when mouse pointer moves while mouse pointer on element. event mouseeventhandler previewmousemove; but above call getevents binding flags set above returns event interface 2 concrete classes. how can filter out events defined on parent interfaces getevents? note generating extensions methods each event so public static iobservable<eventpattern<mousebuttoneventargs>> previewmouseleftbuttondownobserver(this iinputelement this){ return observable .fromeventpattern <mousebuttoneventhandler, mousebuttoneventargs> ( h => this.previewmouseleftbuttondown += h

Sort array by decimal then by string - Javascript -

i need sort array of format, using plain old javascript. var arr = ["0.01 basic", "0.01 sef", "0.015 basic"]; what need array sorted first decimal string , produce output below; arr = ["0.01 basic", "0.015 basic", "0.01 sef"]; i cannot use jquery in performing sort. plain old javascript. you can : arr.sort(function(a,b){ var @ = a.split(' '), bt = b.split(' '); if (at[1]!=bt[1]) return at[1]>bt[1] ? 1 : -1; return parsefloat(at[0])-parsefloat(bt[0]); }); if want sort big array, might faster cache keys. doesn't matter arrays. example : ["0.01 basic", "0.01 sef", "0.015 basic", "0.2 basic", "0.001 sef", "0.2 aaa"] -> ["0.2 aaa", "0.01 basic", "0.015 basic", "0.2 basic", "0.001 sef", "0.01 sef"]

node.js - "Object {} has no method 'cast' error" when trying to add item to mongoose array -

i'm trying create todo app using node.js, mongoose , backbone learning purposes. till defined these models: var taskschema = new mongoose.schema({ title: { type:string }, content: { type:string } , created: {type:date, 'default':date.now}, due: {type:date}, accountid: {type:mongoose.schema.objectid} }); var task = mongoose.model('task',taskschema); var accountschema = new mongoose.schema({ email: { type:string, unique: true}, password: { type:string } , name: { first: {type:string}, last: { type:string } }, birthday: { day: {type:number, min:1, max:31, required:false}, month: {type:number, min:1, max:12, required:false}, year: {type:number} }, photourl: {type:string}, biography:{type:string}, tasks:[task] }); var account = mongoose.model('account',accountschema); in addition, have following method adding task : var enter_new_task = function(options,callback){

exchange server - How to get occurence number of a recurrent meeting from the EWS using c#? -

below link modifying , deleting occurrence of recurrence meeting. http://msdn.microsoft.com/en-us/library/exchange/dd633618(v=exchg.80).aspx my question how can occurrence number ews or there way find it. appointment occurrence = appointment.bindtooccurrence(service, new itemid(srecurringmasterid), 3); in above code have hard coded occurrence number 3, how can info dynamically? there no direct way , following: get appointment recurringmaster. define start , ending time recurrence, if there no end time , goes forever, define number of days search within find appontments based on previous timings filter results based on type appointmenttype.occurrence, , count got the following code explains have written above. var occurrencescounter = 0; if (appointment.appointmenttype == appointmenttype.recurringmaster) { appointments = ppointment.service.findappointments(wellknownfoldername.calendar, new calendarview(appointment.start, (appointment.recurrence.en

php - Database connection could not be established; Invalid data source name (Only with PDO) -

i'm trying reach new pgsql database php. problem recieve error given in title. when try connect direct. works, when try connect pdo, gives error. what checked: php.ini. required extensions uncommented (both php_pgsql.dll , php_pdo_pgsql.dll ) made sure these 2 files in php folder. made sure database,host,user,pass , port correct using simple script (shown belown) this config file setting databases (i'm using 6 databases correctly. know fault not in file) "aeges":{ "pdo_driver":"odbc", "user":"xxxx", "password":"xxxx", "database":"test", "host":"localhost", "port":1233 }, "postgre":{ "pdo_driver":"pgsql", "user":"xxxx", "password":"xxxx", "database":"asn", "host":"localhost", "port&qu

How to reload form in c# when button submit in another form is click? -

Image
i have combo box in c# place in form named frmmain automatically fill when add (using button button1_click ) product in settings form named frmsettings . when click button button1_click want reload frmmain new added product visible. i tried using frmmain main = new frmmain(); main.close(); main.show(); i know code funny didn't work. :d this windows form! edit please see image of program better understanding. frmmain here settings frmsettings form like. so, can see when click submit button want make frmmain reload updated value added settings visible frmmain combobox. update: since changed question here updated version update products this products form: private frmmain main; public frmsettings(frmmain mainform) { main = mainform; initializecomponent(); } private void button1_click(object sender, eventargs e) { main.addproduct(textbox1.text); } it need mainform in constructor pass data it. and main form: private frmsettings sett

Show simple modal dialog using JQuery -

there simple following div: <div id="dialogg"> hello, world! </div> some css style: #dialogg { display: none; } and jquery code: <script src="assets/js/jquery-1.9.1.min.js"></script> <script src="assets/js/jquery-ui-1.10.2.custom.js"></script> <script src="assets/js/jquery-ui-1.10.2.custom.min.js"></script> <script type="text/javascript"> $(function() { $('#dialogg').dialog({ autoopen: false; width: 400; }); $('#dialogg').dialog('open'); }); </script> but see no dialogs! how can fix it? what's wrong? update: <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Исторический турнир</title> <link rel="stylesheet" type="text/css" href="assets/css/main-styles.

message queue - ServiceStack: How to make InMemoryTransientMessageService run in a background -

what needs done make inmemorytransientmessageservice run in background thread? publish things inside service using base.messageproducer.publish(new requestdto()); and exececuted inside service-request. the project self-hosted. here quick unit test showing blocking of current request instead of deferring background: https://gist.github.com/lmcnearney/5407097 there nothing out of box. have build own. take @ servicestack.redis.messaging.redismqhost - of need there, , simpler (one thread everything) going when compared servicestack.redis.messaging.redismqserver (one thread queue listening, 1 each worker). suggest take class , adapt needs. a few pointers: servicestack.message.inmemorymessagequeueclient not implement waitfornotifyonany() need alternative way of getting background thread wait incoming messages. closely related, servicestack.redis implementation uses topic subscriptions, in class used transfer workerstatus.stopcommand , means have find al

URLs wrongly formatted when sending emails. Rails 3.2 -

i have managed send emails (gmail) rails 3.2 application no apparent problems. however, urls genrated in email have :id param wrongly positioned. notificationmailer default :from => 'no-reply@somedomaiin.com' def report_spam(comment) @comment = comment mail(:to => "admin@somedomaiin.com", :subject => "inappropriate content report") end certainemail.html.haml reported by: " = link_to @comment.reports.last.user.name, users_url(@comment.reports.last.user) " %p content of accused comment: %br " = link_to @comment.body, events_url(@comment.event.id) " %p the email @ inbox looks nice reported by: " saben " content of accused comment: " created superb event!! " however, both links urls are: http://somedomaiin.heroku.com/saben/users http://somedomaiin.heroku.com/2/events and should be: http://somedomaiin.heroku.com/users/saben http://somedomaiin.heroku.com/events/2 this happens a

ssl - How to load multiple certificate files in Java? -

i'm trying create ssl connection certificates loaded 2 files (.p12 , .p7b). have tried following code load .p12 file char []passwkey = "1234567".tochararray(); keystore ts = keystore.getinstance("pkcs12"); ts.load(new fileinputstream("/home/user/desktop/file.p12"), passwkey); keymanagerfactory tmf = keymanagerfactory.getinstance("sunx509"); tmf.init(ts,passwkey); sslcontext sslcontext = sslcontext.getinstance("tls"); sslcontext.init(tmf.getkeymanagers(), null, null); sslsocketfactory factory =sslcontext.getsocketfactory(); httpsurlconnection.setdefaultsslsocketfactory(factory); sslsocket socket = (sslsocket) factory.createsocket("www.host.com", 8883); // create serversocket string[] suites = socket.getsupportedciphersuites(); socket.setenabledciphersuites(suites); socket.starthandshake(); but receive exception: jav

Calculating memory usage of a B-Tree in Java -

i've implemented simple b-tree whichs maps longs ints. wanted estimate memory usage of using following method (applies 32bit jvm only): class btreeentry { int entrysize; long keys[]; int values[]; btreeentry children[]; boolean isleaf; ... /** @return used bytes */ long capacity() { long cap = keys.length * (8 + 4) + 3 * 12 + 4 + 1; if (!isleaf) { cap += children.length * 4; (int = 0; < children.length; i++) { if (children[i] != null) cap += children[i].capacity(); } } return cap; } } /** @return memory usage in mb */ public int memoryusage() { return math.round(rootentry.capacity() / (1 << 20)); } but tried e.g. 7mio entries , memoryusage method reports higher values -xmx setting allow! e.g. says 1040 (mb) , set -xmx300! jvm somehow able optimize memory layout, eg. empty arrays or mistake? update1: ok, introducing isle

ios - How Does iPhone's Email app recognize an Address? -

i have been playing around iphone , realized email app of iphone can recognize if line within email represents address. interestingly enough works many address patterns. tried usa , germany, france , spain. in cases address highlighted blue link phone number be. question algorithm behind address detection? check uidatadetectortypes in documentation . you'll find uidatadetectortypeaddress detects strings formatted addresses. add detector type uitextview .

c++ - Set struct elements to values within definition -

the compiler seems have no problem this. can safely assume object create of type have these defaults values? struct colorproperties { bool colorred = true; bool colorblue = false; bool isrectangle = true; }; colorproperties myproperties; will myproperties automatically contain element values noted struct? yes, can. it's c++11 feature. it's equal to struct colorproperties { colorproperties() : colorred(true), colorblue(false), isrectangle(true) {} // }; you can read proposal here quotes standard. n3376 12.6.2/8 in non-delegating constructor, if given non-static data member or base class not designated mem-initializer-id (including case there no mem-initializer-list because constructor has no ctor-initializer) , entity not virtual base class of abstract class (10.4), then — if entity non-static data member has brace-or-equal-initializer, entity initialized specified in 8.5; struct { a(); }; struct b { b(int);

android - "Authenticity check failed" error on server -

i migrate 5.0.0.3 worklight application deployed on 5.0.0.3 worklight server worklight studio 5.0.6 , deployment done on ipas. deployment successful on ipas , try execute android application tablet. i have issues authentication: in application descriptor, protected android application in application-descriptor.xml securitytest. i defined realms, securitytest , loginmodules in authenticationconfig.xml. use formbasedauthenticator , nonvalidatingloginmodule. all work challengehandler except when challengehandler.submitsuccess(). here, on server console have following error: com.worklight.core.auth.ext.authenticityloginmodule login fwlse0127e: authenticity check failed. securitytest use is: customercentricclientapp-strong-mobile-securitytest. here authenticationconfig.xml file: <?xml version="1.0" encoding="utf-8" standalone="no"?> <securitytests> <websecuritytest name="customercentricclientapp-web-securit

Regex to find anchor tags which are without http or https in the href attribute -

i have sample text on want run regex pull anchor tags href doesn't contain http|https in address part. i trying regex, , not complete yet. not able pluck anchor when not start http or https. link gskinner site - http://regexr.com?34ev0 <a.*?href=[""|'](http|https:\/\/)(?<link>[^""|']*)[""|'].*?> here sample string:- <br /><span style="font-size: 16px;"><strong><a target="_blank" href="http://www.yahoo.com">good link (yahoo)</a><br /><br /><a target="_blank" href="www.bbc.com">bad link (bbc)</a><br /><br /><a href="" id="anchorsocialmedia" onclick="showmodalpopup('anchorsocialmedia','/events/popup/socialmediasharemodal.aspx','650px','500px');">share event</a><br />badge perf testing<br /><br /></strong><