Posts

Showing posts from September, 2015

java - Are there any classes that implement javax.persistence.Parameter<T>? -

i'm using named queries fetch entities database using jpa , hibernate , came across puzzling me: how come there no default implementations of javax.persistence.parameter interface? i rather impressed how @staticmetamodel used criteriabuilder in jpa2 meaning type safety , don't have mess around setting string names. wanted apply similar of jpa1 ejb's i'm working on: dealergroup_.class: public dealergroup_ { public parameter<integer> id = new parameterimpl<integer>("id"); /// etc... } dealergroupfacade.class: // ... public dealergroup fetch(integer id) { typedquery<dealergroup> query = em.createnamedquery("dealergroup.fetchbyid", dealergroup.class); query.setparameter(dealergroup_.id, query); return query.getsingleresult(); } // ... i surprised find there no implementations of parameter interface - of course, implement myself absence makes me suspicious may mistake using in way? should implementing parameter

ruby on rails - 2 way delete relationship -

i have user_relations table. user_id | related_user_id ------------------------- 1 | 15 1 | 17 4 | 56 15 | 1 5 | 34 when destroy row (1 | 15) , want rails automatically delete parallel row (15 | 1) . is there rails way of doing this? this user_relation class: class userrelation < activerecord::base belongs_to :user, :class_name => "user", :foreign_key => "user_id" belongs_to :related_user, :class_name => "user", :foreign_key => "related_user_id" end yes, can write filter in userrelation model, after_destroy :delete_associated def delete_associated ur = userrelations.find_by_related_user_id_and_user_id(related_user_id, user_id) ur.delete if ur end update: to create associated record can write filter this, after_create :create_associated def create_associated userrelations.find_or_create_by_related_user_id_and_user_id(related_user_id, user_id) #check if exist

c# - ToolTip MouseOver function on text in RichTextBox -

Image
this question has answer here: displaying tooltip on mouse hover of text 7 answers im working on code-editor (windows form) , want know how make tooltip in text 1: sample when mousehover text "" tooltip show when mouseleave tooltip gone .or if mouseover different text, text in tooltip inside change . just in actual code-editor. with sample code? tooltip1.autopopdelay = 5000; tooltip1.initialdelay = 1000; tooltip1.reshowdelay = 500; //tooltip1.showalways = true; tooltip1.tooltiptitle = "<)( text tooltip )(>"; tooltip1.usefading = true; tooltip1.useanimation = true; anyone? pls in need .thanks . set tooltip control want show when hovers on it: mytooltip.show("tooltip text goes here", mybutton) or this.tooltip1.settooltip(this.targetcontrol, "my tool tip&

less - Sprites in LESSC -

is there addon lessc allow me to like: less .icon-xyz{ .sprite('image1.png'); } .icon-abc{ .sprite('image2.png'); } that outputs merged sprite in production mode, , stays individual images in development mode? similar how compass works sass there addon node.js: less-sprites. https://github.com/polycode/less-sprites it requires install imagemagick firstly.

mysql - How to achieve unique auto-incremented id for rows across multiple tables? -

i've got several tables in database, let's they're called table1, table 2, etc. tables have primary key column 'id' auto-increment. in current configuration happens when inserting table1, generated id 1. afterwards when inserting table2, generated id happens 1 well. how force absolutely unique ids across tables in database? want when inserting table1, generated id 1, , if afterwards inserting table2, generated id 2? i used mysql server on machine , did not have problem, when installed mysql on local machine, started occur. guess must kind of setting applied mysql configuration? thank you you can use uuid. insert mytable(id, name) values(select uuid(), 'some data'); read more uuid: http://mysqlbackupnet.codeplex.com/wikipage?title=using%20mysql%20with%20guid%20or%20uuid

c# - Dynamically looping through controls has no effect -

i have gui class. pass frmmain (form) gui contructor. have following method access child controls: public void assignevents(frmmain frm) { foreach (control ctl in frm.controls) { ctl.backcolor = color.greenyellow; log.adddata(ctl.name.tostring() + ".backcolor = " + ctl.backcolor.tostring(), 3); } } i new updated color in output (log), takes no effect on controls , still in default color. ideas i'm doing wrong? edit: i call this: // gui.cs public class gui { public gui(frmmain frm){ assignevents(frm); } } // frmmain.cs public frmmain() { initializecomponent(); gui = new m.gui (this); } based on comment, need try go recursively through each controlcollection set backcolor property. try changing code this: public gui(frmmain frm) { assignevents(frm.controls); } public void assignevents(control.controlcollection controls) { foreach (control

javascript - JQuery Modal Dialog with drop-down list and textarea embedded -

i'm new jquery forgive me if easy question. i trying create dialog box, onclick event, comprises of: 1) drop down list 2) text area (height possibly 300px) 3) yes/no buttons i have got stage can display dialog yes/no buttons, struggling include dropdown , textarea field. current code: function placeorder() { if ($('#dialogdiv').length == 0) { $('body').append("<div id='dialogdiv'><div/>"); } var dialogdiv = $('#dialogdiv'); dialogdiv.attr("title", "are sure want place order."); dialogdiv.html("are sure want place order? please select delivery option drop down , enter special requirements in text field."); dialogdiv.dialog({ modal : true, buttons : [ { text : "yes", class : 'green', click : function() { // functionality. }

jmx - InvocationException on connecting to MBean server from Spring -

i trying connect mbean server spring application. below code: public void connect() throws exception { mbeanserverconnectionfactorybean bean = new mbeanserverconnectionfactorybean(); bean.setconnectonstartup(false); properties environment = new properties(); environment.put("java.naming.factory.initial", "com.sun.jndi.rmi.registry.registrycontextfactory"); environment.put("java.naming.provider.url", "rmi://117.13.128.104:9308"); environment.put("jmx.remote.jndi.rebind", "true"); bean.setenvironment(environment); bean.setserviceurl("service:jmx:rmi://117.13.128.104/jndi/rmi://117.13.128.104:9308/agent/eodserver"); bean.afterpropertiesset(); mbeanserverconnection server = (mbeanserverconnection)bean.getobject(); system.out.println("test"); // after bean.getobject() - debug pointer on line. } the debug pointer set after bean.getobject() method call. o

javascript - controlling iframe margin and source from js (js inside iframe) -

i have iframe. want change src , margins of iframe javascript included in document open in iframe. i have tried following no use - document.popiframe.document.body.innerhtml="blah"; document.getelementbyid( 'popiframe' ).setattribute( 'src', '' ); $('.popiframe').attr('src', "about:blank"); how can this? an iframe window in window, change page displayed there (= not src attribute) change in other window : window.location.href = "http://www.google.com"; changing margin around iframe isn't possible see it...

append() function in jQuery -

i'd enable user double-click on li elements on webpage results in addition of li's text textarea below. the user can double-click more 1 li item. every time happens, new item appended of list in textarea. i have default text in textarea: "double click on movie name in accordion insert." hence, following html code: <!-- there list before have not included --> <div id="chosen"> <form action="process.php?stage=4" method="post"> <textarea name="g" row="5">double click on movie name in list above insert.</textarea> <input type="submit" /> </form> </div> and jquery: $(document).ready (function(){ $('li').bind('dblclick', function(){ //#accordion var text = $(this).html() + "; "; $("textarea").append(text); }); }); the code absolutely works under normal circumtances, stops working when click

unity3d - How to move a MonoBehaviour to an external assembly and don't get stuck in the "Missing (mono script)"? -

i have many scripts (monobehaviour) inside game project in unity3d, many of them referenced gameobjects in scenes. now want move of these scripts separated assembly (class library), because need use them in other projects , wish improve our code organization. so, when move scripts external class library project , put .dll inside de unity3d assets folder, gameobjects reference moved scripts warning "missing (mono script)". i imagine unity3d keeps track script references looking script name , assembly name. does knows way solve problem? unfortunately there no automated way of doing in unity. correct in unity maintains reference monobehaviour. have few options, none of them ideal: option 1: rename monobehaviours in project "mb_xxx" xxx name of script. through unity editor , unity maintain reference. import compiled dll monobehaviours in names want use. go through each object adding in appropriate monobehaviour dll , removing mb_xxx behaviour. us

Unable to write html from windows batch script using for loop -

after struggling 2 days still have not been able find solution problem windows batch script. what want read html file line line , if matching keyword found in particular line, replace line (html tags , variable combination) no matter whatever do, error " < expected @ time " whenever try push html tags file. looks batch script not html. here code: script.bat for /f "tokens=1,2,3,4,5,6,7" %%i in (output.txt) call :process %%i %%j %%k %%l %%m %%n %%o goto :sendreport :: procedure prepare report :process setlocal enabledelayedexpansion set ubename=%1 set ubever=%2 set ubestat=%3 set rundate=%4 set starttime=%5 set endtime=%6 set totaltime=%7 set findwhat=%ubename%%ubever% :: letter find in file set replacewith=^<tr^>^<td^> %ubename% ^</td^>^<td^> %ubever% ^</td^>^<td^> %ubestat% ^</td^>^<td^> %rundate% ^</td^>^<td^> %starttime% ^</td^>^<td^&

vba - Word (2010) Update date and keep formatting using Macro -

i have following vba code insert date in format of code @ bookmark locations. inserting date each time open file without deleting old boookmark text added delete text @ top of code deletes format , inserts text there way keep formatting? sub autoopen() ' ' autoopen macro ' ' activedocument.bookmarks("mydate").range.delete activedocument.bookmarks("mydate1").range.delete activedocument.bookmarks("mydate2").range.delete activedocument.bookmarks("mydate3").range.delete activedocument.bookmarks("mydate4").range.delete activedocument.bookmarks("mydate5").range.delete activedocument.bookmarks("mydate6").range.delete activedocument.bookmarks("mydate").range .insertbefore format(date + 1, "dddd dd mmmm yyyy") end activedocument.bookmarks("mydate1").range .insertbefore format(date + 2, "dddd dd mmmm yyyy") end

html - GWT historyFrame causes a blank line in the body part -

i want use preferred <!doctype html> in gwt index.html , want make use of (hidden) __gwt_historyframe iframe. when use both <body> starts blank line. code below show mean: <!doctype html> <html> <head> <title>hello world</title> <style> html, body { width: 100%; height: 100%; margin: 0; padding: 0; background-color: green; } #container { width: inherit; height: inherit; margin: 0; padding: 0; background-color: pink; } h1 { margin: 0; padding: 0; } </style> </head> <body> <iframe src="javascript:''" id="__gwt_historyframe" style="width:0;height:0;border:0;"> </iframe> <div id="container"> green bar

maven assembly- sub folder -

i want use maven assembly plugin assembly '<plugin> <artifactid>maven-assembly-plugin</artifactid> <executions> <execution> <id>dist</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptors> <descriptor>src/main/dist.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin>' my descriptor file : <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation

Why does perl not warn when redeclaring a variable in an inner scope? -

as bit of perl novice, ran bug accidentally did (example simplified): my $i=0; for(my $i=0;$i<10; $i++) { print $i; } print $i; # $i zero, code expected 9 from why don't warning when redeclare perl foreach control variable? understand behavior expected; should not warning unless re-declaration in same scope. however, can not understand why case. why perl not issue warning here? seems me cause of errors, , not intended. there common case normal programming style, warning annoying? perl doesn't tend warn style issues, find hard believe intentionally want have same var name @ different scope depths. the case might useful comes mind is { $x = $x; ... changes $x ... } # $x restored here. on plus side, there perlcritic rule identify such problem.

iphone - Core plot : Unable to set date/minute in x-axis -

am breaking head on since yesterday , can't work! plain x-axis line, y-axis line (not ticks or labels!) , chart title! please help! seems simple, elusive! am plotting last 5 values of memory usage of server. values each minute approximately (sometimes, it's 2 minutes once). example, 1 set of last 5 values might want show this: date (vs)  memory usage (bytes) 2013-05-02 11:50:33 +0000 - 157888512.000000 2013-05-02 11:51:33 +0000 - 157839360.000000 2013-05-02 11:52:14 +0000 - 157888512.000000 2013-05-02 11:56:36 +0000 - 157863936.000000 2013-05-02 11:57:48 +0000 - 157888512.000000 i refresh graph every minute.  the 'numberforplot', 'numberofrecordsforplot' seems called, no plotting seen/visible in graph. my graph initialized method : -(void) initializegraph { nslog(@"view_visualizer.initializegraph"); if ((self.graph == nil) || (self.graph == null)) { self.graphhostview = [(cptgraphhostingview *) [cptgrap

memory - what does "exited abnormally with signal 9: Killed: 9" mean -

how read error codes appear in console? <warning>: ....... -exited abnormally signal 9: killed: 9 <warning>: ....... -1 err = bad file descriptor (0x00000009) here signal 9 mean, there more signals apart it. documentation available it. i kind of error, when app. launched xcode terminated "stop" button in xcode toolbar. {another way error , press home button, double tap home button , close app. } things worse when launch app. again , tapping on app. icon on ipad screen, app crashes , throws "libmobilegestalt copysystemversiondictionaryvalue: not lookup releasetype system version dictionary" from finding on stack overflow , see error found in ios 6 devices. this url states it's sigkill error , happens when "application being terminated immediately, without chance clean or catch , handle signal" so, think releasing objets in "-(void) didreceivememorywarning" not solve it, definite solution? -(void) didreceive

asp.net - Access Facebook Album -

i creating 1 site in user login trough his(er) facebook a/c. algo give functnality user can access there facebook album in site can access there pic in site. can me on topic?? for have use facebook's graph api. public const string authorize = "https://graph.facebook.com/oauth/authorize"; public const string access_token = "https://graph.facebook.com/oauth/access_token"; using can authorize user , facebook return access token using can call "https://graph.facebook.com/oauth/authorize?client_id=" + facebookclientid + "&redirect_uri=http://localhost:1388/fbcoverpage/fbcallback.aspx&scope=user_photos"; this api , have set redirect uri g et response on page. , have set client id application id created on facebook thank you.

c# - Iterating through JSON using System.Json -

i'm exploring capabilities of .net 4.5 system.json library there isn't documentation, , it's quite tricky search due popular json.net library. i wondering basically, how i'd loop through json example: { "people": { "simon" : { age: 25 }, "steve" : { age: 15 } } } i have json in string, , want iterate through , display ages of everyone. so first i'd do: var jsonobject = jsonobject.parse(mystring); but i'm @ loss of next. i'm surprised parse method returns jsonvalue not jsonobject. what want is: foreach (var child in jsonobject.children) { if (child.name == "people") { // foreach loop on people // name , age, eg. person.name , person.children.age (linq or something) } } any ideas? using json.net , linq string json = @"{ ""people"": { ""simon"" : { age: 25 }, ""steve"" : { age: 15 } } }"; var people = jsonconve

sqlalchemy - get attribute names of class python/ get column names of query -

i want have column names of sqlalchemy query not find how can this. i tried few ways first way have tried make new class, because names had different of column names class dosierweergave(): def __init__(self, code_arg, year_registr, period_registr, staynum, status): self.code_arg = str(code_arg) self.year_registr = str(year_registr) self.period_registr = str(period_registr) self.staynum = str(staynum) self.status = str(status) and maked object of this a = dosierweergave(187,2010,4,"0000010000", "inbehandeling") i right names not in right order. know how can columnnames (class attributes) in right order. another way use function: columns.keys() headerdosiers = dosiers2.__table__.columns.keys() but got column headers , not find how can filter them has idea how can fix problems or has got better way it what want column names; if want print them, create str function: def __str__(self): st

java - show a list of word and definition using hashmap -

i trying create simple game with list of words using hashmap. want is. want show user word list in scrambling way. example word hello "loeh". user have enter answers, , if answer right user point. can tell how able scramble key in map list display user; this code have far; public class game extends applet { /* * (non-javadoc) * * @see java.applet.applet#init() */ // create list words answers. probbaly map list map<string, string> words = new hashmap<string, string>(); // add words , definition list words.put("hi", " form salutation"); here concept go with. for each letter in word listofletters.add(letter) while(listofletters.notempty()) scrambledword += listofletters.pop(randomnum(0,listofletters.size)) print scambledword pop here both returning letter , removing list. if code psuedo code out java , have errors post edit , ill debug.

objective c - how to parse JSON from URL with basic authentication -

is there can provide me different steps need parse json form api using basic authentication? thanks in advance use nsjsonserialization that: nsjsonserialization apple doc

c++ - Can't connect to a port, but netstat shows what port LISTENING -

while trying connect error: "no connection made because target machine actively refused it." but netstat shows: tcp 0.0.0.0:my_port my_pc:0 listening only problem can think app bound port under step-by-step debugging, paused. how can workaround it. basicly need know somehow if bound port. (i can't use so_exclusiveaddruse ) i think can't connect because app uses port in debug paused mode, so, first time connect doesn't "clear connection". if want check if given port in use, can bind() , check failure. if don't want create socket , bind it, can instead loop through arrays returned gettcptable() , gettcptable2() , gettcp6table() , gettcp6table2() , getudptable() , , getudp6table() functions. table2() not report ips , ports in use, process ids own them (from can access additional information, file names). these same functions netstat uses internally information.

pip install and python setup.py behave differently -

i have setup.py compiles c code using gcc. installs binary. when using python setup.py install, binary runs fine. when using pip install package, /lib/i386-linux-gnu/libc.so.6: version `glibc_2.0' not found does know why case , how can work around issue? thanks.

javascript - Alert user for unsaved changes in page within panels using jquery -

i have situation here, need stop user if user has left unsaved changes on page. i got information on internet moving current page other page like var warnmessage= "you have unsaved changes"; $('input:not(:button,:submit),textarea,select').change(function () { window.onbeforeunload = function () { if (warnmessage != null) return warnmessage; }; }); $('input:submit').click(function(e) { warnmessage = null; }); this works fine when closing tab or url getting changed. i have panels on page 3 different panels;each submit, cancel , reset. now, need alert user when happens open panel; last panel has unsaved changes user should alerted if he/she has unsaved changes on panel, submit/reset/cancel button clicked should confirm user. is possible?

php - Why this expression return error and how can I resolve? -

this question has answer here: weird php error: 'can't use function return value in write context' 11 answers this code: if(!empty(trim($_post['post']))){ } return error: fatal error: can't use function return value in write context in ... how can resolve , avoid 2 checks ( trim , empty ) ? i want check if post not blank space. in documentation explains problem specifically, gives alternate solution. can use trim($name) == false.

Finding a path in Rails folder -

i wanted debuging purpsoes learn how use logging, used write "puts" every , see them in console. logging need simple rails.logger.debug('hello place') i found looks logging goes somewhere this: #{rails.root}/log/#{rails.env}.log but still having problem navigating such path :) ok if rails thats get: /users/ericcartman/.rvm/gems/ruby-1.9.3-p374/bin/rails so how should navigate there? in dev environment. the logs found in log directory of rails application. so enter rails s start application, try ls -l log list log files.

mysqli - how to create a search bar input to search every columns of the table using php -

i creating search bar search query every column of database table , prompt output doing php , mysqli dont have idea how show output. can me here code if(!$db) { require("includes/db.php") echo 'error: not connect database.'; } else { if(isset($_post['querystring'])) { $querystring = $db->real_escape_string($_post['querystring']); if(strlen($querystring) >0) { $query = $db->query("select * mdb name '%" . $querystring . "%' or grno '%". $querystring ."%' or `address` '%". $querystring ."%', `city` '%". $querystring ."%' or pin '%". $querystring ."%' or mobile '%". $querystring ."%' or `email` like'%". $querystring ."%' order vouchno limit 8"); if($query) { $catid

java - Derby doesn't allow isolation level to be set at TRANSACTION_SERIALIZABLE for concurrent access -

i'm using derby database , trying create db objects concurrently. as know default isolation level in transaction_read_committed. but don't want allow phantom reads db , hence, want set isolation level transaction_serializable. all bit of code. if(jdbctemplate.getdatasource().getconnection().gettransactionisolation() == connection.transaction_read_committed) { logger.info("the connection isolation transaction_read_committed"); } else { logger.info("please set connection isolation transaction_read_committed"); } jdbctemplate.getdatasource().getconnection().settransactionisolation(connection.transaction_serializable); if(jdbctemplate.getdatasource().getconnection().gettransactionisolation() == connection.transaction_serializable) { logger.info("the connection isolation transaction_serializable"); } as expected, see log

javascript - Asp.net listbox used client side -

i have 2 asp.net listbox control in page lbox1 , lbox2 lbox1 filled in code behind . user can select items on lbox1 , clicking on button selected items goes in lbox2. using javascript becouse don't want postback on each click. this javascript function : function updatelist() { var sel = document.getelementbyid("lbox1"); var listlength = sel.options.length; (var = 0; < listlength; i++) { if (sel.options[i].selected) document.getelementbyid("lbox2").add(new option(sel.options[i].value)); } } now need send on server side content of lbox2 using button. think using simple asp button onserverclick event not work becouse in server side lbox2 never filled! how can ? you'll need add button , js function copies values lbox1 control <asp:hiddenfield> control. once post back, selected values available in hidden control's value property.

ruby - Error calling Javascript in Camping App -

i want learn webapps. decided learn doing , chose start simple camping (i). small & (ii). know ruby. i think comfortable html , css side of things , using mab. decided step , add javascript fails work. here offending code snippet view: div.image link :rel => 'stylesheet', :href => 'styles.css' script :type =>"text/javascript", :src => 'display_date.js' # hash argument go @ end. button 'display date', :type => "button", :onclick => "displaydate" end the javascript file looks this: function displaydate() { document.getelementbyid("demo").innerhtml=date(); } when click 'display date' button on screen firefox webconsole reports -- [18:32:46.762] referenceerror: displaydate not defined it not work on ie either. camping file , javascript file in same directory. please advise. result better adding javascript inline results in stack error

logic programming - Using pyDatalog for constraint stores -

consider following rules: pydatalog.create_atoms('x') pydatalog.create_atoms('y') pydatalog.create_atoms('a') pydatalog.create_atoms('b') b(x,1) <= (x<0) b(x,y) <= (x==1) & (y>0) a(x,y) <= b(x,y) & (x>0) and problem of finding constraints satisfy: a(x,1) the question is: can use pydatalog come list [(x==1)] ? or [(x>0), (x==1)]? thanks, unfortunately not, @ least current version :-) pydatalog can solve discrete constraint problems, not general constraint problems 1 describe. pydatalog can return values, not criteria x>0. note: can combine first 4 statements in one: pydatalog.create_atoms('x, y, a, b')

delphi - How to Get Local IP by SocketHandle? -

i developing chatroom application - use tserversocket , tclientsocket send , receive text can socket.sockethandle computer sent me, how local ip (or computernetname) of computer. tcustomwinsocket has remoteaddress , remotehost properties peer's ip , hostname values, respectively. not need use sockethandle property unless want call winsock api functions directly, getpeername() , getnameinfo() .

javascript - Dynamically assign value to dom -

i have html page show user profile username,place,about etc. getting value using ajax in jquery. have question how assign retrieved value dom: first method wait till data dynamically create dom , append target div $.ajax({ url: "profiledata", type: "post", success:function(data){ $("<div><label>"+data.name</label><br/> <label>"+data.place</label></div>").appendto("target div"); } in method more append of string happen doubt memory consumed process. second method use id assign value: $.ajax({ url: "profiledata", type: "post", success:function(data){ $("#uname").text(data.name); $("#place").text(data.place); } <div><label id="uname"></label><br/> <label id="place"></label></div> which 1 efficient i

javascript - Open file link with application on user click -

this question has answer here: open google earth , load specific kml file when user clicks link on web page 1 answer in website have link kml file . when user clicks on link ,i want open kml file google earth application. in android can using intent , providing content type. how same desktop ? no but not solve problem. is there way ask user consent if yes open using script? can run client side script this. as mentioned on answer have linked to : you can't run arbitrary program on client machine web page. or without consent. can installing browser plug-in after user consent or otherwise asking user actions. allowing security hazard. you can use standard web page actions. result can depend on client side user configuration. it mention in linked answer can use web base google earth. , of course can use simple client side script ask confir

r - using stringr to split vectors, unexpected result length -

something simple i'm messing in using stringr manipulate character vectors. have data frame of following sort library(stringr) d1 <- data.frame(x = str_c(rpois(10, lambda=5), rpois(10, lambda=10), sep = "_")) and want after underscore separate variable. use of str_sub results in vector of length 20, , i'm @ loss explain why. d1$y <- str_sub(d1$x, str_locate(d1$x, fixed("_"))+1) error in $<-.data.frame ( *tmp* , "y", value = c("_12", "_7", "_15", : replacement has 20 rows, data has 10 could direct me how write str_sub call in right way? this want doing (check out output of str_locate see why wasn't working you, note str_sub recycles arguments): d1$y = str_sub(d1$x, str_locate(d1$x, fixed("_"))[,1] + 1, -1) or in base r: d1$y = sub("^[^_]*_", "", d1$x)

Reduce array "resolution" in LabView -

Image
really simple question, can't around visual programming. have array of size 600. want reduce size of 10 grabbing number every 60 index of array. know how in normal programming language, can't figure out labview. can have pity , me out? i've attached i'm @ far, it's sad. what have way if needed fixed sized array. important if running on fpga or need reduce jitter on rt target. what have not easiest way this. easier way accumulate new array shift register so: as can see- if index multiple of 60 element appended array. otherwise, in false case, array passed through unmodified. you should know that, although method easier use, cause memory allocations increase size of array being accumulated. isn't problem.

Returning PDF from ASP.NET Web API crashes IE -

i'm using httpresponsemessage display files through web api. if use content disposition type attachment have no problems. i've been asked have them open directly in browser (disposition type attachment). changed type inline , works fine in every browser except ie. "internet explorer has encountered error , needs close" error when try use ie. here's code i'm using httpresponsemessage response = new httpresponsemessage(httpstatuscode.ok); byte[] filebytes = null; using (filestream fs = new filestream(strpath, filemode.openorcreate, fileaccess.readwrite)) { filebytes = new byte[fs.length]; fs.read(filebytes, 0, filebytes.length); } response.headers.clear(); response.content = new bytearraycontent(filebytes); cachecontrolheadervalue cch = new cachecontrolheadervalue(); cch.private = true; response.head

exception - How to handle Python 3.x UnicodeDecodeError in Email package? -

i try read email file, this: import email open("xxx.eml") f: msg = email.message_from_file(f) and error: traceback (most recent call last): file "i:\fakt\real\maildecode.py", line 53, in <module> main() file "i:\fakt\real\maildecode.py", line 50, in main decode_file(infile, outfile) file "i:\fakt\real\maildecode.py", line 30, in decode_file msg = email.message_from_file(f) #, policy=mypol file "c:\python33\lib\email\__init__.py", line 56, in message_from_file return parser(*args, **kws).parse(fp) file "c:\python33\lib\email\parser.py", line 55, in parse data = fp.read(8192) file "c:\python33\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] unicodedecodeerror: 'charmap' codec can't decode byte 0x81 in position 1920: character maps <undefined> the file contains multipart email, part

Dynamic php form -

i'm trying login form change based on if user 'new' or 'existing'. example if 'existing user' selected display 'username', , 'password' input fields. while choosing 'new user' 'username','email','password', , 'passwordconfirm'. <select id="login_type" name="logintype"> <option value="register">a new user</option> <option value="login">an existing user</option> </select> tried code below got stuck when read html form inside if else. can to? <?php if (isset($_post['login_type']) && $_post['login_type'] == 'an existing user') { <div> <label for="uname_input">username:</label> <input id="uname_input" name="uname" type="text" required="required" placeholder="enter username"/> <br />

php - Is calling a function in OOP slow or is it the overhead? -

this question has answer here: is object-oriented php slow? 11 answers i building application heavy repetition of functions. for instance: $class = new class; for($i; $i < 1000; $i++) { $class->get_something(); } i have read many articles on oop , why slow, still don't understand "slow" part is. people keep using world "overhead," loading actual class? once require class, same speed when call function or variable? you touching old debate between making 1 large query data, or looping on many smaller ones receive them. , answer lies in specifics of implementations. in cases faster call 1 function on , over, while other times kill performance. "overhead" calling function on , on pretty minimal, it's "guts" of matter.

javascript - bootstrap: more than one modal -

i'm using 2 bootstrap modals on site: <!---- modal 1 ----> <div id="send-pm" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="send-pm" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="mymodallabel">send foobar pm</h3> </div> <div class="modal-body"> <p>one fine body…</p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">cancel</button> <button class="btn btn-primary">send</button> </div> <!---- mod

Maven Javadoc Plugin During Site Goal: javadoc: error - java.lang.OutOfMemoryError: Please increase memory -

i have been struggling increase memory of javadoc plugin via pom file. reason mac build slave fails during site goal outofmemoryerror . tried adjusting maxmemory of javadoc plugin via pluginmanagement section of pom (as per maven-javadoc-plugin documentation ): ... <build> ... <pluginmanagement> <plugins> ... <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-javadoc-plugin</artifactid> <version>2.8.1</version> <configuration> <maxmemory>512m</maxmemory> </configuration> </plugin> </plugins> <pluginmanagement> ... </build> ... this didn't seem anything, build still failed out of memory error. so decided put directly in plugin declaration instead (see build-plugins-plugin section below: ... <build> ... <pluginmanagement> <plugins>

range - How do I count cells that are between two numbers in Excel? -

i need formula count number of cells in range between 10 , 10.000: i have: =countif(b2:b292,>10 , <10.000) but how put comparison operators in without getting formula error? if have excel 2007 or later use countifs "s" on end, i.e. =countifs(b2:b292,">10",b2:b292,"<10000") you may need change commas , semi-colons ; in earlier versions of excel use sumproduct this =sumproduct((b2:b292>10)*(b2:b292<10000)) note: if want include 10 change > >= - 10000, change < <=

asp.net - Specified cast is not valid when reading a Float column -

well stuck... again. sailing smooth until now. reading data db (something usual) giving me specified cast not valid error. not first time i've dealt error; earlier on had date column. anyway, have table need read. data type float. code using: dim rdr = sqlcmd.executereader while rdr.read theresults.add(new userdata { .balavailable = rdr.getfloat(0), .branch = rdr.getint32(1) }) end while this running under function; class... class userdata dim theresults = new list(of userdata) property branch integer property balavailable single end class and input part... dim clientno integer = 0 dim myresults = getdata(clientno) if integer.tryparse(txtinput.text, clientno) if myresults.count = 1 txtbalavail.text = cint(myresults(0).balavail) else everytime input value gives me specified cast not valid error. system.data.sqlclient.sqlbuffer.get_int32() +5270501 system.data.sqlclient.sqldatareader.getint32(int32 i) +62 i be

mysql - SQL Only equal to day and month not year -

i have database users stores birthday. y-m-d, , im trying every user has same birthday. year can difference between each user. so how turn this: select username table_name birthday='$birthday' working script? $birthday gets data form, inputs example: 2002-02-02. , if users have birthday echo out. problem checks year, , im trying month , day, not year. i have tried (exact(month ...) didnt work. missing? you can something select username table_name month(birthday)=month('$birthday') , day(birthday)=day('$birthday')

R loop: name objectives by variable -

i need read daily netcdf files every month , give each name ended date library(raster) year<-2004 startmonth<-1 for(monthd in 31){ days<-formatc(monthd, width=2, flag="0") month<-formatc(startmonth,width=2,flag="0") sm=raster(paste(year,month,days,"1.nc",sep=""),varname="sm") monthd<monthd+1 } in end should have raster objectives named sm01 sm02 . . . sm31 for january. there must simple way it, i'm fresh in coding. you want take mean of set of raster files. package raster has built-in object types handling situations such this. much more efficient create rasterstack , use calc find mean: days<-formatc(1:31, width=2, flag="0") files <- list( paste("2004" , "01" , days , "1.nc" , sep="" ) ) ## first 3 filenames: files[[1]][1:3] # [1] "200401011.nc" "200401021.nc" "200401031.nc" sms <- stack

java - Export runtime value of a variable in NetBeans -

i'm using netbeans java programming , want export value of variable file, since can't copy , paste big array list. there command @ runtime? you can dump heap tools jmap (part of jdk). have snapshot of application memory. but don't think there's way "paste" values on netbeans fields/variables. can go , change them manually. if current array have 4 elements , 1 saved have 9? how object references?

asp.net mvc - MvcSiteMapProvider custom path for display templates -

is possible place display templates in custom folder, example, in displaytemplates/sitemap ? create sub-folder , move views , they'll still work. no other set-up required!

Using Netty 4, how do I write a handler that can inject messages on a periodic basis and still pass messages through? -

i trying write class injects message channel every minute. have figured out how accomplish using code below, think flush method wrong. after flushing upstream messages, noticing socket gets closed. public class pinger extends channeloutboundmessagehandleradapter<bytebuf> { private static final bytebuf dummy = unpooled.wrappedbuffer("dummy".getbytes()); @override public void connect(channelhandlercontext ctx, socketaddress remoteaddress, socketaddress localaddress, channelpromise promise) throws exception{ super.connect(ctx, remoteaddress, localaddress, promise); ctx.executor().scheduleatfixedrate(new repeattask(ctx), 0, 60, timeunit.seconds); } private final class repeattask implements runnable { private final channelhandlercontext ctx; public repeattask(channelhandlercontext ctx){ this.ctx = ctx; } public void run() { if(ctx.channel().isactive()){ ctx.

javascript - How can I add a "for" in a Highcharts series? -

i have .php file executes query, query adds textfields depending on results, example: $query = mysqli_query($mysqli, "select year,period users"); $num_users = mysqli_num_rows($query); for($i=1; $i<=$num_users; $i++) { $row = mysqli_fetch_array($query); echo "<input type='text' id='year$i' name='year$i' value='".$row['year']."'>"; echo "<input type='text' id='period$i' name='period$i' value='".$row['period ']."'>"; } echo "<input type='text' id='count' name='count' value='$num_users'>" so output x-number of inputs, may 1 40 inputs containing year , period, catch values of fields following: count = parseint(document.getelementbyid('count').value); for(i=1;i<=count;i++) { var custom = "year" + i; window[custom] = parsefloat(document.getelementbyid(&#

ios - Centering a UIImageView inside a UIScrollView -

i trying center uiimageview in scroll view. here code tried no results. uiimageview *iv = [[uiimageview alloc] initwithimage:[uiimage imagenamed:kreceiptdetailscrollviewbackgroundcornered]]; [iv setcontentmode:uiviewcontentmodecenter]; [[self scrollview] insertsubview:iv atindex:0]; anybody know what's wrong this? you set image view's content mode center, means image not scaled , can larger image view displays it. uiimage *image = [uiimage imagenamed: kreceiptdetailscrollviewbackgroundcornered]; uiimageview *iv = [[uiimageview alloc] initwithimage: image]; iv.contentmode = uiviewcontentmodescaleaspectfit; iv.frame = [self scrollview].bounds; [[self scrollview] addsubview: iv];

c# - Cannot convert string to DateTime within a LINQ expression -

i using linq xml expression deserialize xml data list of objects. object collection fields: public class dataobject { private string name { get; set; } private datetime date { get; set; } } and here's linq query: xdocument linqxml = xdocument.parse(datatodeserialize.outerxml) list<dataobject> myobjects = (from object in linqxml.descendants("object") select new dataobject { name = object.element("name").value, date = convert.todatetime(object.element("date").value) } when run this, linq query throws formatexception: "string not recognized valid datetime." the date string in xml formatted in utc: 2013-05-02t11:25:35-06:00 to test tried conversion of date time , correctly returns datetime object. datetime dt = convert.todatetime("2013-05-02t11:25:35-06:00"); and string converts new datetime object. if switch date field on object string type, , convert in method, converts. seems not work when part of linq

Magento update subtotal item -

i can't update subtotal item in cart. created module observe checkout_cart_product_add_after can subtotal price item: $subtotal = mage::getsingleton('checkout/cart')->getquote()->getsubtotal(); but can't update this, exmaple: $subtotal = $subtotal + 100; mage::getsingleton('checkout/session')->getquote()->setsubtotal($subtotal); mage::getsingleton('checkout/cart')->getquote()->setsubtotal($subtotal); mage::getsingleton('checkout/session')->getquote()->save(); mage::getsingleton('checkout/cart')->getquote()->save(); edit if run in observer print_r($subtotal); exit; correct updated subtotal. in cart page have still orginal subtotal without change. edit 2 i'm trying run modifysubtotal function sales_quote_collect_totals_after event, can't see on cart page updated subtotal price. below code of modifysubtotal observer.php: public function modifysubtotal(varien_event_observer $observe

c# - SimpleInjector Verification - is it possible to mark warnings as acceptable to make *new* items obvious? -

the simpleinjector verification feature time time has highlighted issues have needed fix. have couple of "potential" issues comfortable , way of telling simpleinjector these ok, tell me rest ... configuration warnings warnings in multiple groups have been detected. potential lifestyle mismatches 1 possible mismatch 1 service. iobjectmaterializedsubscriber objectmaterializedsubscriber (lifetime scope) depends on ieventpublisher (transient). potential single responsibility violations 2 possible violations. ilettergenerator<a> lettergenerator<a> has 9 dependencies might indicate srp violation. ilettergenerator<b> lettergenerator<b> has 9 dependencies might indicate srp violation. the first warning ieventpublisher transient fine. other 2 warnings (i assuming) caused me using simpleinjector decorator facility build chains of responsibility. i'd able mark these specific warnings accepted contai