Posts

Showing posts from February, 2012

r - Sum values of combinations within a group -

for analysis transform data from: data <- data.frame( customer = c("a", "a", "b", "b", "c", "c", "c"), product = c("x", "y", "x", "z", "x", "y", "z"), value = c(10, 15, 5, 10, 20, 5, 10) ) data # customer product value # 1 x 10 # 2 y 15 # 3 b x 5 # 4 b z 10 # 5 c x 20 # 6 c y 5 # 7 c z 10 to: product product sum value -------|-------|--------- x |y |50 x |z |45 y |z |15 basically want sum of value every product combination within customer. guess work of reshape package cannot work. thanks time. here 1 way, in 2 steps: 1) transform data long data.frame of pairs within customers. that, rely on combn provide indices of possible pairs: process.one <- function(x) { n

android - My activity closes down when i cancel or accept bluetooth enable request? -

there no error in logcat current activity closes down , previous activity opens. here code puttin bluetooth enabling request: bt.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { if (!(bluetooth.isenabled())) { log.e("blue",""+"not working"); status = "bluetooth not enabled."; toast.maketext(adduser.this, status, toast.length_short).show(); intent enablebtintent = new intent(bluetoothadapter.action_request_enable); startactivityforresult(enablebtintent, 1); } else { scand(); } } }); here onactivityresult: protected void onactivityresult(int requestcode, int resultcode, intent intent) { system.out.println(resultcode); log.e("resultblue",""+resul

java - Copy int array to array -

i have simple int array initialize this: int [][] temparray=bp.getarray();//get array other class(bp) //doing things temparray... when change temparray change bp.getarray(); . because referenced bp.getarray(); ? yes, if want new reference it's easy, have use arrays.copyof . other functions array.clone , system.arraycopy . arrays.copyof// java 6 feature. older versions switch system.arraycopy. public static int[][] deepcopy(int[][] original) { if (original == null) { return null; } final int[][] result = new int[original.length][]; (int = 0; < original.length; i++) { result[i] = arrays.copyof(original[i], original[i].length); } return result; } this deep copy 2d array.

Wpf dynamic design with Grid and data binding -

i creating dynamic ui using code.i adding grid page using loop,in multiple rows , 4 columns,so takes time load ui on page.i want load each child grid lazily, don't know how it, please help. here xaml file <scrollviewer grid.row="1" horizontalalignment="stretch" verticalalignment="stretch" cancontentscroll="true" horizontalscrollbarvisibility="auto" verticalscrollbarvisibility="auto" margin="0 0 0 0"> <grid x:name="maingrid" horizontalalignment="stretch" verticalalignment="top" margin="10" width="auto"> </grid> </scrollviewer> and pseudo code .cs file for (int column = 0; column < dsmacdtls.tables[0].rows.count; column++) { grid = new grid(); grid.width = 108; grid.height = 108; if (column % 4 == 0) { maingrid.rowdefinitions.add(new rowdefinition()); } else {

oop - difference between unidirectional association and dependency -

according wikipedia dependency relationship shows element, or set of elements, requires other model elements specification or implementation.[1] element dependent upon independent element, called supplier . so not same unidirectional association? use dependency when operation in 1 class uses object of other class parameter? how unidirectional association , dependency different. example helpful association means 2 associated entities linked semantically. dependency declares there a... well, dependency of sort. associations dependencies, while dependency not mean association. example, class 'a' depends on class 'b' if has method takes 'b' , passes argument function in class. if 'a' calls method of class 'b', should modeled association. disclaimer have read uml specification , asked myself question number of times. arrived @ at definition above, i'm still not sure 100% correct.

Monitoring c3p0 connections using Jconsole -

hi trying monitor connections opened c3p0 using jconsole. i following tutorial mentioned in http://amemon.wordpress.com/2007/07/15/monitoring-c3p0-using-jmxjconsole/ but when open jconsole under mbeans tab not able find package c3p0. ideas??

xml - XSL - Do I need a Value-of? -

<xsl:for-each select="/date/logs"> <rect> <xsl:attribute name="fill"> red </xsl:attribute> ......... portion of xsl transformation document. when process it, red comes out just &#10;&#9;&#9;red&#10;&#9;&#9; do need value-of select , variable. i'm not knowledgeable sorry poor explanation. could me please, in advance. you can use literal result elements including attribute values e.g. <xsl:for-each select="/date/logs"> <rect fill="red"/> </xsl:for-each> if want or need populate attribute value based on value in input doc use attribute value template e.g. <xsl:for-each select="/date/logs"> <rect fill="{@color}"/> </xsl:for-each>

java - 'try with resource' feature for File class -

i have 1 scenario trying implement java 7 'try resource' feature. my block contains object of bufferedwriter , file , want close using 'try resource' feature, instead of closing calling close method explicitly. but checked on net , saw file class not implement autocloseable interface, bufferedwriter does. how can manage scenario implement 'try resource' feature? try (bufferedwriter br = new bufferedwriter(new filewriter(path))) use simply, br closed automatically. eg. http://www.roseindia.net/java/beginners/java-write-to-file.shtml

java - The loss of key-value pair of Map output -

i wrote hadoop program on input of mapper text file hdfs://192.168.1.8:7000/export/hadoop-1.0.1/bin/input/paths.txt written ways of local file system (which identical on computers of cluster) program ./readwritepaths in 1 line , partitioned character | . @ first in mapper there reading quantity of subordinate nodes of cluster /usr/countcomputers.txt file, equally 2 read correctly, judging program execution. further contents of input file arrived in form of value on input of mapper , transformed line, segmented means of separator | , received ways added in arraylist<string> paths . package org.myorg; import java.io.*; import java.util.*; import org.apache.hadoop.fs.path; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.util.*; public class parallelindexation { public static class map extends mapreducebase implements mapper<longwritable, text, text, longwritable> {

php - performance: store a large mysql result in class vars VS result array -

hej folks, i wondering faster. suggest have big database table 50 columns , class handles these columns. the class constructor loads fields - , here starts question. is useful store every column in own class variable or juts unperformant? in case have array, e.g. $result keys table columns. or irrelevant? i tried write benchmark have vserver test results not clear. is 1 time function stores values in class vars faster searching whole array every 'get' method? thanks in advance :) p.s. php 5 i think answer question "it doesn't matter". in terms of application performance, code you're talking - iterating on loop in memory 50 times , manipulating data in memory, retrieving class data, or retrieving data associative array - blazingly fast. fast it's impossible measure differences under normal circumstances. in order notice difference between employee::$id, employee::$name vs employee::$result['id'], employee::$result[

java - Highlight nodes covered by XPath -

i want highlight nodes covered given xpath in html page source. i looked in htmlunit, not find thing in api. at present, thinking of doing following way: get xpath , page-source. break xpath smaller chunks , store them in xpath_chunk[]. apply chunk xpath_chunk[] starting 0. update css property of each node found each chunk(any change distinguishes text). now add next chunk , concate current. go step 3. in way, visit nodes covered xpath. more changes can remove elements unnecessarily highlighted. this complicated. there way ? i made rudimentary implementation using javafx's webengine + webview. register dom listener nodes of loaded website's document, can listen clicks on nodes. when clicking, change style of node , add css. webview reflect changes , render page correctly. the document webengine returns can accessed using xpath (it's w3d document), can traverse , modify nodes encounter (or use node furthest down, travel upwards using getparent

json - Valid UTF-8 string with Cyrillic symbols in C -

i try parse utf-8 json-message in c. pass following code parser: char *text = "{\"mdl\":\"users\",\"fnc\":\"getuserslist\"}"; and works. if message has cyrillic characters, both of parsers string " not valid utf-8 string ". example: char *text = "{\"mdl\":\"пользователи\",\"fnc\":\"получитьсписокпользователей\"}"; i used jansson c parser , ccan json parcer c. in main function have following call of setlocale : setlocale(lc_all, "ru_ru.utf8"); how can valid utf-8 string using cyrillic characters in it? the relationship between source encoding (the encoding used encode text in c source) , target encoding (the encoding used encode run-time strings) not obvious. see this question more discussion this. make sure source encoding utf-8, , compiler preserving this. or, can manually encode strings utf-8, replacing non-ascii characters backslash-e

regex - Java pattern Match for a specific pattern to match -

i try match pattern in given string static, following program: package com.test.poc; import java.util.regex.matcher; import java.util.regex.pattern; public class regextestpatternmatcher { public static final string example_test = "http://localhost:8080/api/upload/form/{uploadtype}/{uploadname}"; public static void main(string[] args) { pattern pattern = pattern.compile("{\\w+}"); // in case ignore case sensitivity use // statement // pattern pattern = pattern.compile("\\s+", pattern.case_insensitive); matcher matcher = pattern.matcher(example_test); // check occurance while (matcher.find()) { system.out.print("start index: " + matcher.start()); system.out.print(" end index: " + matcher.end() + " "); system.out.println(matcher.group()); } // create new pattern , matcher replace whitespace tabs pattern replace = pattern.compile("\\s+"); matcher m

node.js - Getting filetype in an Express route -

i have express route /doc/:id serves html representation of document, , want serve epub representation when appended " .epub ". express doesn't separate on period, however, if use /doc/:id.epub sets req.params.id " id.epub ". there way have file extension recognised separate parameter or need use regex extract it? i have looked @ res.format , seems effective when accepted header set, not if url typed browser, far can see. this works: app.get('/doc/:filename.:ext', function(req, res) { ... }); this requires part following /doc/ contains @ least 1 period, may or may not issue.

php - Passing file upload name from $_FILES to $_POST for storage in database -

i'm still new php i'm looking pass name of file that's uploaded can entered database corresponding form information. // uploading file if ($_files){ print_r($_files); mkdir ($dirname, 0777, true); move_uploaded_file($_files["file"]["tmp_name"],$dirname."/".$_files["file"]["name"]); } // form processing if($_post['formsubmit'] == "submit") { $varname = $_post['formname']; $varlat = $_post['formlat']; $varlong = $_post['formlong']; $varpic = $_files["file"]["name"]; $db = mysql_connect($dbhost,$dbuser,$dbpass); if(!$db) die("error connecting mysql database."); mysql_select_db($dbname ,$db); $sql = "insert new_submissions (locationname, latitude, longitude, picture) values (". prepsql($varname) . ", " . prepsql($varlat) . ", &

javascript - Strange behaviour of included JS file in node.js -

i making node app in current state simple, issue can't figure out. the generated html of express app looks this: <html style="" class=" js no-touch svg inlinesvg svgclippaths no-ie8compat"> <head> ... <script type="text/javascript" src="/javascripts/mouse.js"></script> ... </head> <body class="antialiased" style=""><div class="row"><div class="row"> <script> var mouse; var x = 0; var y = 0; window.onload = function() { alert(mouse());//=> undefined mouse = mouse(); mouse.setmousemovecallback(function(e){ //this line fails: "cannot call method 'setmousemovecallback' of undefined" x = e.x; y = e.y; alert("move"); }); } ... </html> the include script tag in header adds javascript file: function mouse(onobject){ var mousedown = [0, 0, 0, 0, 0, 0, 0, 0, 0], mousedowncount = 0; var mousedowncallba

tsql - how to find record count mismatch in a stored procedure in sql server 2008 R2? -

2 stored procedures developed .net developers. giving same record counts when pass same parameter? now due changes , getting mismatch record count i.e if first stored procedure giving 2 records paramemter , second sp giving 1 record. to find followed approach verified i counted total records of table after joining total tables used in joining 3.distinct / group used in 2 tables or not? finally not able find issue. how fix it? could body share ideas. thanks in advance? assuming same joins , filters, problem nulls. that is, either a clause has direct null comparison fail a count on nullable column. see count(*) vs count(1) more either way, why have same similar stored procedures written 2 different developers, appear have differences?

logging - Log delay in Amazon S3 -

i have hosted in amazon s3, , need log files calculate statistics "get", "put", "list" operations in objects. and i've observed log files organized weirdly. don't know when log appear(not immediatly, @ least 20 minutes after operation) , how many lines of logs contained in 1 log file. after that, need download these log files , analyse them. can't figure out how this. can help? thanks. what describe (log files being made available delays , being in unpredictable order) declared aws behaviour expect. nature of distributed system, aws s3 using provide s3 service, same request may served each time different server - have seen 5 different ip addresses being provided publishing. so solution is: accept delay, see delay experience , add time , learn living total delay (i expect 30 60 minutes, statistics tell more). if need log records ordered, have either sort them yourself, or search log processing solutions - have seen applic

linux - Bash - Need to use exit but then call another function? -

i'm writing little script use webcam on laptop , email across photo me. ffmpeg usage has have exit code work exit mail function not called. doing wrong? #!/bin/bash mail_addr=user@example.com ts=`date +%s` list=$(ls | tail -n 1) function mcheese(){ mkdir /tmp/cheese cd /tmp/cheese echo -e "cheese " | mutt -s "$ts cheese" $mail_addr -a $list } function cheese(){ ffmpeg -f video4linux2 -s vga -i /dev/video0 -vframes 3 /tmp/cheese/vid-$ts.%01d.jpg exit 0 } cheese mcheese you setup list in 1 directory, change directory , use it. unlikely work. use bash -x work out script failing.

sms - How to show the dialog of all the messaging options in android? -

Image
i trying send text messages selected contacts on phone using smsmanager default sends message using phone gsm message option. requirement show popup user choose messaging options such whatsapp , viber etc shown in image here code smsmanager sm = smsmanager.getdefault(); sm.sendtextmessage("9844598445", null, "hello there", null, null); please help try one uri uri = uri.parse("smsto:" + smsnumber); intent intent = new intent(intent.action_sendto, uri); intent.putextra("sms_body", smstext); startactivity(intent);

sql - Calculate Sum based on dates (Current, 7 Days,...) -

the following example of table working with: date -------- number -------total 2012-03-28 3 158 2012-03-29 4 168 2012-04-08 2 256 2012-04-12 1 155.98 2012-04-14 6 245.00 2012-04-20 10 156 2012-04-21 8 87 2012-04-26 3 158 2012-04-26 4 168 2012-04-29 2 256 2012-04-30 1 155.98 2012-05-02 6 245.00 2012-05-02 10 156 2012-05-02 8 87 i need derive table following this: total ----- current ----7days----14days 2451.96 1225.98 1869.96 1869.96 in case total sum(total), current -7 days todays date(05/02/2013) adds sum 05/02/2013-04/25/2013 7 days -14 todays date or -7 current. adds sum 05/02/2013-04/18/2013. so forth.

r - Normalizing faceted histograms separately in ggplot2 -

my questions similar normalizing y-axis in histograms in r ggplot proportion i'd add bit. in general, have 6 histograms in 2x3 facet design, , i'd normalize each of them separately. i'll try make sample data set here give idea: hvalues=c(3,1,3,2,2,5,1,1,12,1,4,3) season=c("fall","fall","fall","fall","winter","winter","winter","winter","summer","summer","summer","summer") year=c("year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2","year 1","year 1","year 2","year 2") group=c("fall year 1","fall year 1","fall year 2","fall year 2","winter year 1","winter year 1","winter year 2","winter year 2","summer year 1","summer ye

javascript - Open a link from a Iframe(fancybox) in a new window -

i'm building europe map raphael script using fancybox popup when clicking on country, it's displaying iframe . when clicking on link inside iframe new page opened inside iframe open link in new window. here script raphael : greek[state].click(function(){ $j.fancybox({ 'showclosebutton': true, 'href' : 'link.html', 'width' : 500, 'height' : 350, 'type' : 'iframe' }); }); the link.html file : <a onclick="window.open(this.href,'','resizable=yes,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,fullscreen=no,dependent=no,width=400,height=500,left=350,top=250,status'); return false" href="http://www.test.com"><img src="test-simotas.jpg" width="447" height="314"/></a> i can't find solution. do have idea?? in advance. maybe work: <a onclick="window.open(this.['data-href

xslt 1.0 - Need to group xsl:for-each-group with Muenchian method -

i not able retrieve unique list applying muenchian method. trying group based on "series title" attribute sample input xml: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <distribution> <manifestheader> <assets> <asset> <id>23341528</id> <createdate>2008-01-14t17:02:01z</createdate> <metadatas> <metadata name="psa.orig.source.showtitle">green home 2008</metadata> <metadata name="displayruntime">00:01</metadata> <metadata name="series title">desperate landscapes</metadata> </metadatas> </asset> <asset> <id>23341529</id> <createdate>2010-08-23t15:44:58z</createdate> <metadatas> <metadata

mysql - Multiply in update subquery select -

i'm trying update table based on 2 select subquery multipied produce value harga column here code : update bahanmakanan set harga = (select hargasatuan detail_bahanmakanan idbahanmakanan = "bm01")* (select jumlah bahanmakanan idbahanmakanan = "bm01") idbahanmakanan = "bm01" ; the error message return error code: 1093. can't specify target table 'bahanmakanan' update in clause you can using join , update bahanmakanan inner join detail_bahanmakanan b on a.idbahanmakanan = b.idbahanmakanan set a.harga = a.jumlah * b.hargasatuan a.idbahanmakanan = 'bm01' please backup first database before executing statement.

ruby - How do I use a regular expression to match a number as an integer? -

when match number using regular expression string: ?> 'testingsubject2981'.match /\d+$/ => #<matchdata "2981"> is somehow possible number integer without to_i s? the issue regular expressions work on strings, not on other data types. a regex has patterns match numbers, still find characters represent number, not binary values we'd use math. once engine returns matches, they're still characters, have use to_i convert them binary representations. mmm-kay?

javascript - Pass custom data to Google Analytics with Goal Tracking -

i'm using google analytics goal tracking track when user submits form on every page of website. tells me when form has been submitted, there way of passing through page name can track page form has been sent from? my goal tracking set event goal type , have configured goal use category, action , label following code on submit button, works fine: onclick="_gaq.push(['_trackevent', 'total form submits', 'submit', 'form submit']);" if set second dimension in events report "page" show path event triggered. goals can see info in conversions->goal urls report. can see goal triggered without additional code.

android - Fatal Exception: String can't be cast to Spannable -

my app works exception of few devices. on 1 such device, fatal exception in 1 of activities. error java.lang.classcastexception: java.lang.string cannot cast android.text.spannable ... ... at android.widget.textview.setenabled(textview.java:1432) stack trace 05-02 09:18:19.917: e/androidruntime(20587): fatal exception: main 05-02 09:18:19.917: e/androidruntime(20587): java.lang.classcastexception: java.lang.string cannot cast android.text.spannable 05-02 09:18:19.917: e/androidruntime(20587): @ android.widget.textview.setenabled(textview.java:1432) 05-02 09:18:19.917: e/androidruntime(20587): @ com.myapp.android.menu.loginfragment.checkifanyfieldisempty(loginfragment.java:512) 05-02 09:18:19.917: e/androidruntime(20587): @ com.myapp.android.menu.loginfragment.oncreateview(loginfragment.java:183) 05-02 09:18:19.917: e/androidruntime(20587): @ android.support.v4.app.fragment.performcreateview(fragment.java:1460) 05-02 09:18:19.917: e/androidruntime(20587): @ andro

android - Action Bar padding differences between devices -

Image
i have action bar defined in following manner: <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_refresh" android:icon="@drawable/menu_refresh" android:showasaction="always"/> <item android:id="@+id/menu_shelves" android:icon="@drawable/menu_shelves" android:showasaction="always"/> ... more items ... </menu> this main activity layout: <com.totalboox.android.views.borderedlinearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="6dp" > <view android:layout_width="match_parent" android:layout_height="?android:attr/actionbarsize" a

php - installed imagick not seen by php_info -

i not experienced on linux, , need here. have installed imagemagick, , can see version below: [root@zpanel temp]# convert -version version: imagemagick 6.8.5-4 2013-05-02 q16 http://www.imagemagick.org copyright: copyright (c) 1999-2013 imagemagick studio llc features: dpc openmp delegates: bzlib fontconfig freetype jng jp2 jpeg lcms png ps tiff x xml zlib but cannot see in php_info(check url : http://www.galepress.com/phpinfo.php ). have restarted httpd etc, no good. ps : have run following command , warnings: [root@zpanel temp]# php -m | grep imagick php warning: php startup: unable load dynamic library '/usr/local/src/imagick-3.0.1/modules/imagick.so' - libmagickwand.so.2: cannot open shared object file: no such file or directory in unknown on line 0 php warning: php startup: unable load dynamic library '/usr/lib64/php/modules/imagick.so' - /usr/lib64/php/modules/imagick.so: cannot open shared object file: no such file or directory in unknown on line 0

javascript - Adjusting spacing in a Highcharts chart dynamically -

here's problem: i have multiple charts under various tabs. after loading chart, add svg text , rect display additional legend after plot. each chart might have different legend can vary in length, space required may vary. i use spacingbottom value allow space legend displayed. set value manually before chart loaded (as in example below), can lots of work if text in legends changed. what can set spacingbottom value required number based on height of legend container? the example can seen here: http://jsfiddle.net/anlsz/1/ $(function () { var mylegends = [ '*: lorem ipsum dolor sit amet, consectetur adipiscing elit.', '<strong>np</strong>: pellentesque in sapien diam, ac tristique dolor. curabitur sit amet est nunc, eget egestas neque.', '<strong>np</strong>: pellentesque sollicitudin ultrices tristique. aenean pharetra nulla eget turpis tincidunt vulputate. sed pulvinar nisi et ante iaculis vulputate.

java - Internet Explorer destroys context on a:commandButton -

i experiencing issues when using a:commandbuttonin internet explorer. using <a:commandbutton> action add details object. working fine when use chrome or firefox. however, when clicking add button in internet explorer, context destroyed , new 1 created. some code: listpage.xhtml <a:commandbutton action="#{articledetail.add}" value="add" id="popadarticlebtn" rerender="#{facescontext.maximumseverity eq null ? 'articlepanel' : 'poparticle, errormsg'}" oncomplete="#{facescontext.maximumseverity eq null ? 'richfaces.hidemodalpanel(\'addarticle\');' : ''}"> and articledetail.java class: (getters & setters included) @name("articledetail") @scope(scopetype.conversation) @autocreate public class articledetail extends entityquery<articledetail>

PHP: Mysql ("SELECT WHERE ID NOT ") -

i trying exclude 'id' mysql_query still returning mentioned id. id '21' query returns '21' not wanted. did misspell in mysql? ("select * `gallery` `gallery_id` not in ('$notgallery')") or die (mysql_error()); function not_gallery($pic){ $pic = $_get['id']; $id = explode(".", $pic); $notgallery = $id; $notg = mysql_query("select * `gallery` `gallery_id` not in ('$notgallery')") or die (mysql_error()); while($not_row = mysql_fetch_assoc($notg)){ $notgimage[] = array( 'id' => $not_row['gallery_id'], 'user' => $not_row['user_id'], 'name' => $not_row['name'], 'timestamp' => $not_row['timestamp'], 'ext' => $not_row['ext'], 'caption' => $not_row['caption'], ); } print_r($notgimage); } i print_r'ed query , still returning '21&#

sql - Oracle: Mixing NVL with Outer Join -

i've got following query. the "left" table 1 alias "o". i want specify following. how can do? should use temp construct? and ( nvl (domb.domb_conto_corrente, ' ') != o.campo43 or nvl (abi.abi_descrizione, ' ') != o.campo41 or nvl (cab.cab_descrizione, ' ') != o.campo42) here's complete statement: select /*+ parallel(o 64) */ o.stato, count (1) conf_raggruppamenti_forn rgf, crd_rid_rel_domiciliazione crrd, crd_domiciliazioni domb, uff_abi abi, uff_abi_cab cab, conto_cliente_t809 o, eni_flussi_hub c, eni_monitor mon 1 = 1 --rgf - out , rgf.rgf_codice_raggruppamento(+) = o.campo1 --join tra out e la eni_flussi_hub , o.id_messaggio = c.flh_id_messaggio(+) , o.d_pubblicazione = c.flh_data_elaborazione(+) --join tra eni_flussi_hub e eni_monitor , c.flh_id_messaggio = mon.mon_id_me

python - Grabbing selection between specific dates in a DataFrame -

so have large pandas dataframe contains 2 months of information line of info per second. way information deal @ once, want grab specific timeframes. following code grab before february 5th 2012: sunflower[sunflower['time'] < '2012-02-05'] i want equivalent of this: sunflower['2012-02-01' < sunflower['time'] < '2012-02-05'] but not allowed. these 2 lines: step1 = sunflower[sunflower['time'] < '2012-02-05'] data = step1[step1['time'] > '2012-02-01'] but have 20 different dataframes , multitude of times , being able nice. know pandas capable of because if dates index rather column, it's easy do, can't index because dates repeated , therefore receive error: exception: reindexing valid uniquely valued index objects so how go doing this? you define mask separately: df = dataframe('a': np.random.randn(100), 'b':np.random.randn(100)}) mask = (df.b > -

Batch file compare two folders return files that aren't in one folder -

i'm trying make batch file compare 2 folders "core" , "custom" , return names of files aren't in custom. so far have code, of taken form question on stack overflow. creates "arrays" of files in each folder. how can compare them? @echo off setlocal enabledelayedexpansion ::build "array" of folders set foldercnt=0 /f "eol=: delims=" %%f in ('dir /b core') ( set /a foldercnt+=1 set "folder!foldercnt!=%%f" ) ::print menu /l %%m in (1 1 %foldercnt%) echo %%m - !folder%%m! echo( ::build "array" of folders set foldercnt=0 /f "eol=: delims=" %%f in ('dir /b custom') ( set /a foldercnt+=1 set "folder!foldercnt!=%%f" ) ::print menu /l %%n in (1 1 %foldercnt%) echo %%n - !folder%%n! echo( pause test.bat how about echo y|xcopy /l /d core\* custom\ which should list files in core not in custom or different version in core?

excel - VBA code for automating a sheet -

Image
1) have created form in vba , have given connection first sheet , when click on button form getting pop enter data, want is, want assign button in first sheet , when click on button form should appear , when insert data form, should appear in second sheet. 2) inserting data sheet 4 rows , after completion of if want modify particular column or particular row of data how can that, need suggest me on , request send me code how modify. 3) , request send me code clear sheet if want enter new data. i glad if helps me on these 3 points. private sub cmdadd_click() dim integer 'position cursor in correct cell b9. range("b9:p40").select = 1 'set first id 'validate first 4 controls have been entered... if me.txtfname.text = empty 'firstname msgbox "please enter firstname.", vbexclamation me.txtfname.setfocus 'position cursor try again exit sub 'terminate here - why continue? end if if me.txtsname.text = empty 'surname

String in alphabetical order Ruby -

i new ruby. have written solution in java public boolean checkorder(string input) { boolean x = false; (int = 0; < input.length() - 1; i++) { if (input.charat(i) < input.charat(i + 1) || input.charat(i) == input.charat(i + 1)) { x = true; } else { return false; } } return x; } i want same in ruby how can convert same ruby. thanks. def checkorder(input) input.chars.sort == input.chars.to_a end

jsf 2 - render composite component based on a Boolean condition -

i developed composite jsf 2 component, , working pretty well. in 1 of pages use custom component, necessary composite component should rendered according boolean condition. pretty similar rendered attribute works in jsf standard components. so tried implement this: <cc:interface componenttype="ciudadcomponent"> <cc:attribute name="paises" type="java.util.list" required="true" /> <cc:attribute name="departamentos" type="java.util.list" required="true" /> <cc:attribute name="ciudades" type="java.util.list" required="true" /> <cc:attribute name="name" type="java.lang.string" required="true" /> <cc:attribute name="value" type="org.colfuturo.model.to.ciudadto" required="true"## heading ## /> <cc:attribute name="etiquetapais"

ruby on rails - has_many nested form with a has_one nested form within it -

i trying make form model, has dynamic number of nested models. i'm using nested forms (as described in railscasts 197 ). make things more complicated, each of nested models has has_one association third model, added form. for wondering on normalization or improper approach, example simplified version of problem i'm facing. in reality, things more complex, , approach we've decided take. some example code illustrate problem below: #models class test attr_accessible :test_name, :test_description, :questions_attributes has_many :questions accepts_nested_attributes_for :questions end class question attr_accessible :question, :answer_attributes belongs_to :test has_one :answer accepts_nested_attributes_for :answer end class answer attr_accessible :answer belongs_to :question end #controller class testscontroller < applicationcontroller #get /tests/new def new @test = test.new @questions = @test.questions.build @answers = @qu

ios - Converting a value within 16-bit color range to a UIColor -

Image
i have value in 1 number range , want convert number in 16 bit color range - 65536 colors. how can use value in 65536 colour range uicolor? have method convert hex value color, how 1 convert unsigned int hex value , accurate? what best way color value within 65536 color range? [uicolor colorwithred: (color>>11)/31.0 green: ((color>>5)&0x3f)/63.0 blue: (color&0x1f)/31.0 alpha: 1] layout of 16-bit colors ( source ):

java - ListView with two adapters -

i'm developing whatsapp application received messages aligned left e sent messages aligned right. how should use listview , adapters keep both received , sent messages in same listview? i suggest create message class. class has 1 boolean example boolean sent; so if it's true know sent you. when create custom adapter list view, do: public view getview(int position, view convertview, viewgroup parent) { layoutinflater inflater = (layoutinflater) getcontext() .getsystemservice(context.layout_inflater_service); convertview = inflater.inflate(r.layout.rowcustom, null); message msg = getitem(position) if (msg.issent()) { // message sent } else { // message received } return convertview; }

c# - Dice returning 0 and no rolls -

playerdice = new dice(); int playerdiceno = playerdice.getfaceofdie(); messagebox.show("your roll" + playerdiceno); compdice = new dice(); int compdiceno = compdice.getfaceofdie(); messagebox.show("computers roll:" + compdiceno); above method when roll button clicked. below dice class: class dice { private int faceofdie; public void rolldice() { random rolldice = new random(); faceofdie = rolldice.next(1, 7); } public int getfaceofdie() { return faceofdie; } } i have stated variables compdice , playerdice : dice compdice; dice playerdice; i can't seem figure out why it's returning 0 both rolls on & over. can help? i can't seem figure out why it's returning 0 both rolls on & over. can help? you never call rolldice() , faceofdie variable never set, , has it's default value of 0. playerdice = new dice(); playerdice.rolldice(); // add int playerdice

SQL Server 'Execute As'/Revert pattern in a 'Try/Catch' Block -

i wish ensure using "best" pattern when using execute as/revert within try/catch block on sql server 2012. below code "seems" behave correctly... missing or there security concerns, "better" approaches, etc.? below code: create procedure [dbo].[tryitout] execute 'notable1access' --does not have access (select) table1! begin declare @execerrornumber int, @execerrormessage nvarchar(2048), @xactstate smallint begin try execute user='hastable1access' select *, 1/0 [simulateerror] [t1].[table1]; -- stored procedure call, select statement easier demo... revert --revert on 'hastable1access' end try begin catch; select @execerrornumber = error_number(), @execerrormessage = error_message(), @xactstate = xact_state(); revert -- revert on 'hastable1access' when in error... --do error processing in context of 'notable1access

c# - Pass variables and access methods of User Control from CodeBehind -

so have function renderwidget() in default.aspx.cs . idea of add user control page. public void renderwidget(string data) { control ctrl = page.loadcontrol("/widgets/widget.ascx"); datapanel.controls.add(ctrl); } this works fine, lovely jubbly. in other end, @ user control, have following code in widget.ascx.cs : public class widgetcontrol : system.web.ui.usercontrol { public string teststring = ""; public void test() { response.write("test"); } } the problem arises when try access either of properties in user control. when try add ctrl.test() or ctrl.teststring = "test" default.aspx.cs, error "'system.web.ui.control' not contain definition 'test'". feel there's basic i'm missing here. any appreciated, thanks! you have cast correct type: widgetcontrol widget = (widgetcontrol)ctrl; widget.teststring = "foo"; widget.test(); loadcontrol returns c