Posts

Showing posts from July, 2011

java - System.currentTimeMillis measuring time -

when use system.currenttimemillis() measure time, safe? e.g. when time-shift happens (summer->winter time) produce error? no, system.currenttimemillis() returns number of elapsed milliseconds since unix epoch (midnight @ start of january 1st 1970, utc). not depend on local time zone @ all. in other words, if call once per second, always increase 1000 (the "about" due clock accuracy , impossibility of calls being exactly 1 second apart). doesn't matter if local time zone changes offset utc, or if change whole time zone - irrelevant. in theory, leap seconds make of trickier - in practice applications can away notionally sticking fingers in ears , saying "i'm not @ home mr leap second."

javascript - What is the correct pattern to the text? -

i have string follows: var str = "visit {inside string}"; i want replace {inside string} 'myschool'. i tried doing below var n = str.replace(/[{][^\s*][^\*}]/,'myschool'); but not working expected. any pointer? you can use var n = str.replace(/\{[^}]*\}/,'myschool'); note if have more 1 replacement you'll have use g flag : var n = str.replace(/\{[^}]*\}/g,'myschool');

Phantomjs login, redirect and render page after pageLoad finishes -

i have website login form. if user not logged , tries access internal page redirected default page. instance if try access http://siteurl.phantomprint.aspx redirected http://siteurl/default.aspx?returnurl=phantomprint.aspx. , after login automatic redirect take place page. after redirect want render page phantomjs , save pdf. problem rendering takes place before page load finished , can render page if use timeouts. in case, if page loading takes longer normal resulted pdf not proper one. below can find java script code: var page = require('webpage').create(); var index = 0, page.onconsolemessage = function (msg) { console.log(msg); }; var steps = [ function () { //load login page page.open("http://siteurl.phantomprint.aspx", function () { //enter credentials page.evaluate(function () { console.log("filling inputs"); var usernameinput = document.getelementbyid("txtusername&quo

sql - variable assignment is not allowed in a cursor declaration -

i trying use cursor in sql , getting "variable assignment not allowed in cursor declaration." & "incorrect syntax near keyword 'as' " error. following query : declare @descriptor nvarchar(420) declare cur_descriptor cursor static select @descriptor = descriptor (select * ix_mesh terms = 'tumors') child select terms ix_mesh descriptor = @descriptor open cur_descriptor fetch next cur_descriptor @descriptor while @@fetch_status = 0 begin print @descriptor fetch next cur_descriptor @descriptor end close cur_descriptor deallocate cur_descriptor any suggestions?? what hard error message? cursor declaration: declare cur_descriptor cursor static select @descriptor = descriptor ----------^ (select * ix_mesh terms = 'tumors') child that assignment no-no. do: declare cur_descriptor cursor static select descriptor (select * ix_mesh terms = 

python - Increase C++ regex replace performance -

i'm beginner c++ programmer working on small c++ project have process number of relatively large xml files , remove xml tags out of them. i've succeeded doing using c++0x regex library. however, i'm running performance issues. reading in files , executing regex_replace function on contents takes around 6 seconds on pc. can bring down 2 adding compiler optimization flags. using python, however, can done less 100 milliseconds. obviously, i'm doing inefficient in c++ code. can speed bit? my c++ code: std::regex xml_tags_regex("<[^>]*>"); (std::vector<std::string>::iterator = _files.begin(); != _files.end(); it++) { std::ifstream file(*it); file.seekg(0, std::ios::end); size_t size = file.tellg(); std::string buffer(size, ' '); file.seekg(0); file.read(&buffer[0], size); buffer = regex_replace(buffer, xml_tags_regex, ""); file.close(); } my python code: regex = re.compi

valgrind on Android does not listen to vgdb -

on android, running valgrind 3.9.0 --vgdb=yes creates fifo pipe should listen vgdb commands (along pipe reverse direction , piece of shared memory). however, command such vgdb instrumentation on hangs forever. this tested on armv7 emulator android 4.0.3 (which reported work on readme.android) , on galaxy note ii android 4.3.1 based cyanogenmod valgrind built export hwkind=generic , --with-tmpdir=/data/local/inst ; other options according readme.android file both devices rooted , running insecure adbd's two valgrind builds tested, 1 built ndk-r6 , 1 ndk-r9d. result same on configurations both devices able run valgrind neither runs listen vgdb for reference, valgrind command , output follows: # ./valgrind -v -v -v --vgdb=yes sleep 1000 ==3640== memcheck, memory error detector ==3640== copyright (c) 2002-2013, , gnu gpl'd, julian seward et al. ==3640== using valgrind-3.9.0 , libvex; rerun -h copyright info ==3640== command: sleep 1000 ==3640== --3640-- valgrin

python - NumPy array acts differently based on origin (np.max() and np.argmax()) -

i have function creates numpy array data file. want maximum value in array , index of value: import numpy np def dostuff(): # open .txt file lists # copy lists numpy array # nested loops , values copied numpy array called print print np.max(a) print np.argmax(a) dostuff() running gives: [[ 0.64 0.47 0.22 0.1 0.05 0.02] [ 2.19 9.13 10.68 6.44 3.36 1.77] [ 1.84 8.81 12.6 8.31 4.45 2.35]] 2.35 0 clearly has gone wrong np.max() , np.argmax(). can shown following code def test(): = np.array([[0.64, 0.47, 0.22, 0.1, 0.05, 0.02], [2.19, 9.13, 10.68, 6.44, 3.36, 1.77], [1.84, 8.81, 12.6, 8.31, 4.45, 2.35]]) print print np.max(a) print np.argmax(a) test() this gives: [[ 0.64 0.47 0.22 0.1 0.05 0.02] [ 2.19 9.13 10.68 6.44 3.36 1.77] [ 1.84 8.81 12.6 8.31 4.45 2.35]] 12.6 14 ...which have expected. have no idea why these 2 (apparently) i

ruby on rails - Nice array from pluck -

i have model , love pluck method can use. if this: @x = awesomemodel.all.pluck(:column_one, :column_two) then multidimensional array: @x[][]. sad skills, work them using numbers: @x[0][1] how can can use pluck or similar method access array this: @x[0][:column_two] if concerned structure of db, should do: @x = awesomemodel.all.select(:column_one, :column_two) then you'd keep fast db query advantage + have awesomemodel instances, column_one , column_two filled or if desire manually: @x = awesomemodel.all.pluck(:column_one, :column_two).map |array| openstruct.new({column_one: array[0], column_two: array[1] }) } end then can use regular model: @x[0].column_one # or @x[0][:column_two]

java - How to validate if a bean instance has been wired? -

i'm creating small framework provides abstract base classes have implemented when using library. how can create validation routine checks if indeed classes have been implemented? i thought maybe use @conditionalonmissingbean of spring-boot, nothing far. anyhow, goal be: @configuration @enableautoconfiguration public class appcfg { @conditionalonmissingbean(basecarservice.class) //stupid exmaple public void validate() { system.out.println("missing bean!!"); } } //must implemented public abstract basecarservice { } how can achieve this? you can calling applicationcontext.getbeansoftype(basecarservice.class) when context has been initialized (for example bean implements contextloaderlistener ), i.e. following: public class beansvalidator impelements contextloaderlistener { public void contextinitialized(servletcontextevent event) { if (applicationcontext.getbeansoftype(basecarservice.class).isempty()) {

php - Best way to group array with same value -

i need solve :) i've array array ( [0] => array ( [order_id] => 121 [item_id] => 4344 [item_name] => product [item_price] => 123 [item_type] => product [paypal_address] => email@test.com [qty] => 4 [currency] => eur ) [1] => array ( [order_id] => 121 [item_id] => 3444 [item_name] => product1 [item_price] => 444 [item_type] => product [paypal_address] => email@test.com [qty] => 2 [currency] => eur ) [2] => array ( [order_id] => 121 [item_id] => 1233 [item_name] => product2 [item_price] => 120 [item_type] => product [paypal_address] => email2@test.com [qty] => 18 [currency] => eur ) ) i loop on , group them values new array. for example: pick items in array have same paypal_address sum price, sum qty , move new array. this want achieve, tip / suggestion ? edit: @ end want array or similar: array ( [0] => array ( [order_id] => 121 [items_id] => array

external - How to add a class to a dll without recompiling the dll? -

how add class dll without recompiling dll? i have library i'm using, , don't have source code. i not touch library able add new classes library. is possible? i create new dll whatever classes , functions need, can write them extension methods , appear if in same namespace. have add additional reference dll projects use existing library or use "ilmerge" merge dll's.

Intergrate proguard with android in mac os x -

i'm struggeling intergrated proguard android in mac os computer. proguard android sdk located @ : /users/thanhnguyen/documents/mr thao's music/android-sdk-macosx/tools/proguard proguard.sh file @ follow : proguard_home=`dirname "$0"`/.. java -jar $proguard_home/lib/proguard.jar "$@" my project.properties follow: proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt when try run proguard, errors occured : proguard returned error code 1. see console proguard error 1 output: error: /users/thanhnguyen/documents/mr thao (no such file or directory) @ com.android.ide.eclipse.adt.internal.build.buildhelper.runproguard(buildhelper.java:623) @ com.android.ide.eclipse.adt.internal.project.exporthelper.exportreleaseapk(exporthelper.java:259) @ com.android.ide.eclipse.adt.internal.wizards.export.exportwizard.doexport(exportwizard.java:313) @ com.android.ide.eclipse.adt.internal.wizards.export.exportwizard.access$0(e

Java 1.7 still telling me that strings in switch statements are incompatible -

i'm using java 1.7 in intellij , it's giving me compile error if i'm using pre-1.7. saying, "incompatible type. found 'java.lang.string'. required 'byte, char, short, or int'. i'm rattling brain trying figure out why is. thanks you need change language level in ide. check these settings: file > project structure > project > project sdk file > project structure > project > project language level file > project structure > modules > module > sources > language level file > project structure > modules > module > dependencies > module sdk also check compiler settings. adds arguments compiler: file > settings > compiler > java compiler > byte code version if use maven plugin enable auto-import. language level detected automatically pom.xml settings.

xml - Single definition of value used multiple times in log4cxx configuration -

i have log4cxx.xml configuration file defines multiple rolling file appenders. <?xml version="1.0" encoding="utf-8" ?> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <appender name="a" class="org.apache.log4j.rolling.rollingfileappender"> <param name="file" value="file1.log" /> <param name="maxfilesize" value="12mb" /> ... </appender> ... <appender name="g" class="org.apache.log4j.rolling.rollingfileappender"> <param name="file" value="file7.log" /> <param name="maxfilesize" value="12mb" /> ... </appender> <!-- loggers referencing a, b, ..., g --> i have 1 place, in file, define maximum file size. know can replace 12mb ${max_file_size} , value environment, not want have set environm

R internal memory allocation error handling -

i had question regarding triggering of error when memory allocation tries exceed memory.limit() such in > test <- 1:1e10 error: cannot allocate vector of size 74.5 gb in addition: warning messages: 1: reached total allocation of 3975mb: see help(memory.size) 2: reached total allocation of 3975mb: see help(memory.size) 3: reached total allocation of 3975mb: see help(memory.size) 4: reached total allocation of 3975mb: see help(memory.size) my main question how error message invoked? memory allocation event , r has internal event listener or function called before assignment of variable check estimated memory usage? if second true, can theoretically turn function off? ad comments: sorry, still don't it. error come from, meaning process responsible error message? how r know object exceeds allocation , return error? seems there 2 possibilities: r tries create object - system (or other processs) returns allocation not possible - r breaks execution , throws er

Search and print out information of .html datas in Powershell -

i want use powershell search in .html documents specific strings , print them out. let me explain first function works: use function search .html documents in path contain string "tag". after search string "id:", skip tag "</td><td>" , use following regular expression print out following 32 characters, id. below see part of html file , function. <tr valign=top><td>lokation:</td><td>\test1\blabla\asdf\1234\ws auswertungen</td></tr> <tr valign=top><td>beschreibung:</td><td></td></tr> <tr valign=top><td>eigentümer:</td><td><img align=middle src="file:///c:\users\d0262290\appdata\local\temp\23\user.bmp">&nbsp;wilmes, tanja</td></tr> <tr valign=top><td>id:</td><td>55c7b7f411e2661e001000806c38eba0</td></tr> </table></td><td><img align=middle src="file:///

angularjs - How to hide a div by clicking a button? (SOLVED) -

in angular.js learning project want hide 1 div , show when click button. in code, i'd first div hidden @ click (or destroyed?) , second div shown. want user experience of going page 1 page 2 in app. how make happen? index.html <ion-content ng-controller="startpagectrl"> <div class="list card" id="startcard" ng-show="showstartcard"> <div class="item item-image item item-text-wrap"> card 1 </div> </div> <div class="list card" id="secondcard" ng-show="showsecondcard"> <div class="item item-image item item-text-wrap"> card 2 </div> </div> <button ng-click="hidecard()" class="button button-full button-calm button icon-right ion-chevron-right"> start </button> </ion-content> cont

XML to string (C#) -

i have xml loaded url this: webclient client = new webclient(); client.encoding = encoding.utf8; try { string reply = client.downloadstring("http://example.com/somefile.xml"); label1.text = reply; } catch { label1.text = "failed"; } that xml belongs rss feed. want label1.text shows titles of xml. how can achieve that? example of label1.text this first title - 2nd title - , last title you can load xml xmldocument , use xpath value of each node you're targeting. xmldocument doc = new xmldocument(); doc.loadxml(reply); xmlnodelist nodes = doc.selectnodes("//nodetoselect"); foreach (xmlnode node in nodes) { //if value want content of node label1.text = node.innertext; //if value want attribute of node label1.text = node.attributes["attibutename"].value; } if not familiar xpath can check here : http://www.w

sockets - Java: I don't get the messages from other clients? -

does know whats wrong code? when write client1 see on server , on client1 not on client2. run() in client.java: public void run() { scanner input = new scanner(system.in); try { socket client = new socket(host, port); system.out.println("client started"); outputstream out = client.getoutputstream(); printwriter writer = new printwriter(out); inputstream in = client.getinputstream(); bufferedreader reader = new bufferedreader(new inputstreamreader(in)); string = input.nextline(); writer.write(clientname + ": " + + newline); writer.flush(); string s = null; while((s = reader.readline()) != null) { system.out.println(s); } writer.close(); reader.close(); client.close(); } if need server code or else as

ios8 - errSecUserCanceled not implemented in iOS 8 GM? -

using secitemcopymatching retrieve keychain in xcode 6 gm, errsecauthfailed after canceling request authenticate. the docs' comments errsecusercanceled when "user canceled operation." whileas errsecauthfailed "the user name or passphrase entered not correct". thus, expecting errsecusercanceled in return here. have others managed errsecusercanceled , or expected behaviour errsecauthfailed ?

Android : set bitmap in new pdf -

i want add few bitmaps in new pdf. i tried : document doc = new document(); page page = doc.getpages().add(); page.getparagraphs().add(img); doc.save(environment.getexternalstoragedirectory().getabsolutepath()+"/doc.pdf"); but i've few error, document isn't found, tried import android proposed me, nothings work. how work ? how can add few bitmap in pdf ? thx,

vbscript - .vbs script to change Connection Specific DNS suffix -

i'm looking way have .vbs file add connection specific dns suffix ethernet adaptor known name of lan the code forms past of small shell script that: changes primary dns suffix flushes dns checks ip details make sure had held changes startup type or service starts said service pings know server ensure network connectivity cant seem find code thats viable make first step work. have : 'add dns const hkey_local_machine = &h80000002 strcomputer = "." set oreg=getobject("winmgmts:{impersonationlevel=impersonate}!\\" & _ strcomputer & "\root\default:stdregprov") strkeypath = "software\policies\microsoft\windows nt\dnsclient" oreg.createkey hkey_local_machine,strkeypath strvaluename = "appendtomultilabelname" 'enabled strvalue = "mysuffix.com" oreg.setstringvalue hkey_local_machine,strkeypath,strvaluename,strvalue 'flush dns set shell = createobject("wscript.shell") shel

networking - Any ideas about the variation of the diameter of a network/graph as the number of nodes increases? -

my question regard increase/decrease of diameter of network. i'm thinking 1 adds more nodes existing network, density should increase , probability of edges created new nodes result in higher degree of clustering. if case, assumption diameter of network should decrease add more nodes, owing probability shorter geodesic paths can exist , become new diameter. wrong logic? or there better explanation or perhaps i'm missing? work leskovec, kleinberg, , faloutsos has examined question [ 1 , 2 ]. find: "first, graphs densify on time, number of edges crowing super-linearly in number of nodes. second, average distance between nodes shrinks on time, in contrast conventional wisdom such distance parameters should increase function of number of nodes."

android - Get access to particular item's layout in list view -

in android app main activity extends list activity . store there elements called items, layout defined itemlayout xml file , use custom adapter (called itemadapter ) transfer data list view in main activity. in itemlayout there's imageview , aim change image when user clicks on particular item in list view. in opinion easiest way achieve access particular item's (the 1 clicked) layout, there find imageview , call method setimagebitmap . how can "find" layout of clicked item? tried many things in method: @override protected void onlistitemclick(listview l, view v, int position, long id) { super.onlistitemclick(l, v, position, id); } but nothing worked. have add itemadapter? or possible in onlistitemclick(…) can't find out how? you're thinking in wrong way. adapter's way map data views. if want change how particular view looks given position, need change it's correlating data rendered view changes. attempting modify view direc

php - Updating with codeigniter -

i finished tutorial making news application on codeigniter user_guide. trying extend tutorial website loads text textarea can retyped , used update entry. want view article page same page updating. view loads correctly, when click submit, brings me localhost/ci/news/foo localhost/ci/news/view along 404. have tried imitate create, , altering model query, since i've been struggling while, have tried several ideas. i suspect problem 1 of following. something directing me ci/news/view misusing $slug variable misconnecting controller , model syntax in model query. i'll post relevent code. here's controller function view, updates happen. public function view($slug) { $this->load->helper('form'); $this->load->library('form_validation'); $data['news_item'] = $this->news_model->get_news($slug); $slug = $slug; $this->form_validation->set_rules('text', 'text', 'required');

ruby on rails - customizing csv format in activeadmin disables csv download link -

i have rails app mildly customized activeadmin table of registered users. app/admin/users.rb looks this: activeadmin.register user actions :index, :show preserve_default_filters! filter :referrer, collection: user.all.map{ |user| [user.email, user.id] } filter :referrals, collection: user.all.map{ |user| [user.email, user.id] } index column :id column("name") { |user| user.first_name + " " + user.last_name } column :email column("referrer", :referrer, :sortable => :referrer_id) column :referral_code column("created at", :created_at, :sortable => :created_at) column("referral count") { |user| user.referrals.count } actions end end this works expected. want customize layout of csv file download. add block right before last end: csv column :id column("name") { |user| user.first_name + " " + user.last_name } column :email

php - How do I properly refresh data on Wordpress using AJAX -

i trying refresh widget on dashboard in wordpress. my plugin written in php, trying add jquery/ajax refresh each widget when changes have been made. the function in php download , store file, , display information widget. the issue have this: files downloaded , stored. new information not show. stays same. believe might simple i've been trying work while no success. here sample of code: <?php add_action( 'admin_footer', 'my_action_javascript' ); // write our js below here function my_action_javascript() { ?> <script type="text/javascript" > jquery(document).ready(function($) { var data = { 'action': 'refresh_function', }; setinterval(function() { $.get(ajaxurl, data, function (result) { }); },20000); }); </script> <?php } add_action('wp_ajax_refresh_function', 'display_function'); php function: function display_function() { $co

excel vba - Run time error on Do Loop in VBA -

i wrote vba script perform bulk find , replace in excel. need perform function on 150,000 cells worth of data. use loop compare value on sheet values (find) , related codes (replace) on sheet b. i using index counter declared dim integer, loop controlling each iteration of index. vba script works, receive "run-time error '6': overflow" error message once index crosses 30,000? there limit how many times can iterate loop, or know of way perform bulk find , replace in excel? try this activesheet.cells.replace(oldvalue,newvalue,xlpart) activesheet.cells contains cells within sheet. hope helps

c# - MetaData with InheritedExport -

im trying export classes implement ijob interface while passing metadata @ individual class level. i've tried: export: [inheritedexport(typeof(ijob))] public interface ijob { int run(); } import: [importmany] public ienumerable<lazy<ijob, ijobmetadata>> jobs { get; set; } implementation: [ignorejob(false)] public class myjob : ijob { public int run() { return 5; } } attribute setup: [metadataattribute] [attributeusage(attributetargets.class, allowmultiple = false)] public class ignorejobattribute : exportattribute, ijobmetadata { public ignorejobattribute(bool ignore) : base(typeof(ijobmetadata)) { ignore = ignore; } [defaultvalue(true)] public bool ignore { get; set; } } the above not pass metadata if remove inheritedexport attribute , add export attribute individual implementation of ijob works fine... take @ this: how use mef inherited export & metadata? it t

django - Using Python Social-auth how to retrieve fields stored in session from custom pipeline -

my app uses python social-auth login allowing accounts "connect". in mind have custom pipeline follows: social_auth_pipeline = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'jdconnections.utils.get_username', #<<here 'social.pipeline.social_auth.associate_by_email', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' ) i have set: social_auth_fields_stored_in_session = ['connection',] in app view call social-auth follows e.g twitter: return httpresponseredirect(reverse('social:begin', args=('twitter',)) + "?connection=" + request.post.get('origin') ) this works fine , head out twitter , auth

haskell - How do I work with cabal-install when I can't control the path? -

i on stuck on vista machine on not admin. installed haskell platform place control. problem far know on able control path. when try run cabal.exe, error. h:\haskell\platform\lib\extralibs\bin>cabal.exe install cabal-install cabal.exe: program ghc version >=6.4 required not found. how make can use haskell platform home user. can temporarily adjust path, , if so, what? i think problem here windows path needed updated make sure ghc executable there.

Is session.cookie_secure in php.ini automatic? -

simple answer requested: if put session.cookie_httponly=on session.cookie_secure=on in php.ini file website, automatically turn php cookies secure , httponly, or still need put in true, true parameter slots 6 , 7 in cookie itself? the answer yes. setting in php.ini enough (however, saw "true" setting used instead of "on"). session cookie without httponly flag set https://www.owasp.org/index.php/httponly#using_php_to_set_httponly you can verify setting these values, restarting webserver , accessing site browser, e.g. firefox. open "site information", , choose "security" tab , click on cookies. there can see if it's marked secure.

Joomla category list issue -

this difficult explain i'll best. i have site number of articles grouped different menus, allows me present relevant content visitor depending on interested in. each article may in number of menus. i have categorised each article based on menu relevant to. have done in order create landing page using category list component. the issue have urls in category list output not relate active menu, when article in number of menus. when click on article takes different menu. issue fixed if unpublish article other menus. understand because single article menu id takes precedence on category menu id's. i need fix selects active menu id rather default. any appreciated. joomla cannot want default. in short, have multiple urls each article , want joomla automatically know context article displayed in in order display right url. joomla can't this. what need want override layout module category , create code right url based on context in. not easy thing how shoul

cocoa - Create dynamic columns on NSTableView on reload -

Image
i'm creating nstableview , have problem change tablecolumns. header appear black on terminate reload of data. for (int = 0; < sqlite3_column_count(stmp); i++) { nstablecolumn *tablecolumn = [nstablecolumn new]; nsstring *columnname = [nsstring stringwithutf8string:sqlite3_column_name(stmp, i)]; [tablecolumn setidentifier:columnname]; nscell *cell = [[nscell alloc] inittextcell:columnname]; [cell setfont:[nsfont boldsystemfontofsize:[nsfont smallsystemfontsize]]]; [tablecolumn setheadercell:cell]; [tableview addtablecolumn:tablecolumn]; } how reloading header without lost style? edit 1 for (int = 0; < sqlite3_column_count(stmp); i++) { nstablecolumn *tablecolumn = [nstablecolumn new]; nsstring *columnname = [nsstring stringwithutf8string:sqlite3_column_name(stmp, i)]; [tablecolumn setidentifier:columnname]; nstextfieldcell *cell = [[nstextfieldcell alloc] inittextcell:columnname]; [cell settextcolor:[nscolor whi

java - How to send parameters to existing hidden fragment from activity -

i have mainactivity navigationdrawer. when click on navigation, new fragment created. clicking on next navigation point, old removed , new added transaction. sometimes open new window within navigation point. in case hide old fragment , add new fragment. problem: i have fragmenta edittext. when click on edittext field new fragmentb opened. old fragmenta hidden. fragmentb has list items. when click on 1 of items want close fragmentb , fill value of listitem in edittext of fragmenta. tried many things, it's not working. transfer listitem information mainactivity communicator interface. works. however, way mainactivity fragmenta problem. can't put item value bundle arguments because fragment there. tried call public function exists in fragmenta, everytime want call function mainactivity not possible, because there no such function. have no idea updating edittext in fragmenta , hope help. sorry bad english. ok let me see if understand, have mainactivity , 2 fra

javascript - Iterating jquery objects -

i attempting iterate , output values of choices property using jquery each( ). code seems output array index , not string values. why this? here jsfiddle var allquestions = [ { question: "who prime minister of united kingdom?", choices: ["david cameron", "gordon brown", "winston churchill", "tony blair"], correctanswer:0 }]; $(info[0].choices).each(function(value){ $('#answers').append($('<li>').text(value)); }); you have confused $(selector).each() http://api.jquery.com/each/ with $.each(array, callback) http://api.jquery.com/jquery.each/ you want use second form iterating on arrays.

Single bar barchart in ggplot2, R -

i have following data , code: > ddf var1 var2 1 aa 73 2 bb 18 3 cc 9 > > dput(ddf) structure(list(var1 = c("aa", "bb", "cc"), var2 = c(73l, 18l, 9l)), .names = c("var1", "var2"), class = "data.frame", row.names = c(na, -3l)) > > > ggplot(ddf,aes(x=var1, y=var2, fill=var1))+ geom_bar(width=1, stat='identity') this creates barchart 3 bars. how can create single stacked bar data. want have these 3 bars stacked on top of each other rather being separate bars. this you're looking for: ggplot(ddf, aes(1, var2, fill=var1)) + geom_bar(stat="identity") you can't specify different x positions , asked them stacked @ same time. have specify they're on same x-position in order them on top of each other.

python pdb unt at end of loop -

i have been using pdb's "unt" command step on list comprehensions single command. works unless list comprehension happens @ end of loop. "unt" command steps on entire loop. it seems me flaw in definition of "unt" command. there reason why wasn't defined continuing execution until current line changes, rather waiting increase? the reason i've encountered far list comprehension spanning multiple lines can stepped out of using "unt" works now. proposal, "unt" remain in list comprehension.

bash - Sending packets in Netcat from an address without binding -

i've set promiscuous mode ifconfig eth0 promisc , in python can send packets without binding doing raw sockets. i've done command nc -vs 192.168.11.1 -p 22 192.168.11.2 22 see if can send packets computer without having bound address of machine. feature possible in netcat or have bind? machine has no address settings, in promiscuous mode can see traffic. update: in python created hex string use struct , send out. utilize ifconfig set promiscuous mode (because couldn't figure out how in python) inside bash script runs python script, once it's set seems select eth0 automagically without me setting thing. i wasn't if netcat or not , nothing in utility seems indicate this. might make python script make work raw sockets, if possible. i don't think possible netcat unless allows use of raw sockets (bound interface). given have no address settings, instructive @ routing table: $ route kernel ip routing table destination gateway

html - Long button press on iOS (Javascript) -

is possible make button able have long button press on ios? have searched on , not found solutions problem. @ first if long press button try select (for copying). using css, disabled this, still doesn't register long button press. think because possibility might scrolling page not long press in first place. purpose of want button disappear on long press. here jsfiddle works on pc, doesn't on iphone (there div commented out because doesn't matter if long press on div or button, can create artificial button using div): http://jsfiddle.net/ynklmz5n/3/ thanks in advance. var menutoggle = document.getelementsbyclassname("hide")[0]; menutoggle.style["-webkit-user-select"] = "none"; menutoggle.addeventlistener("mousedown", vanish); menutoggle.addeventlistener("mouseup", vanishclear); var timer; function vanish() { longpress = false; timer = settimeout(function() { menutoggle.style.display = "none"

How to check the number of cores Spark uses? -

Image
i have spark.cores.max set 24 [3 worker nodes], if inside worker node , see there 1 process [command = java] running consumes memory , cpu. suspect not use 8 cores (on m2.4x large ). how know number? you can see number of cores occupied on each worker in cluster under spark web ui:

Ping remote arbitrary command execution on linux -

i'm trying execute code on remote machine (virtual), runs webserver single post form, intended simple ping. on other side following script (part of it): exec("/bin/ping -c 4 ".$_post["addr"]); "addr" data entered in post form goes. calls /bin/ping , appends whatever data enter. question how can leverage shell? think since ping command runs root privileges should easy i'm still new game , couldn't find useful info on how this. appreciated :)

angularjs - How do I format start and end dates into custom format in Javascript? -

i have event has start date , end date follows: var startdate = '10/9/2014 10:00:00 am' var enddate = '10/10/2014 5:00:00 pm' so event starts thursday , ends on friday i display in following format thursday & friday oct 9-10 and if single day thursday oct 9th and longer 2 days thursday - sunday oct 9 - 12 i think momentjs might way go doing have not used yet , thought post question while try work out on own , see guys suggest. unfortunately, there's no javascript date constructor allows pass in culture information uses localized date formats. best bet use constructor takes year, month, , day separately: var parts = datestring.split('/'); var date = new date(parseint(parts[2], 10), parseint(parts[1], 10), parseint(parts[0], 10));

Using variable for column reference in Excel VBA -

first off - i'm totally new vba. i'm trying understand syntax used if want use variable column header part of range call. ex: if <= range("table4[*variable*]")(i).value i'm passing column name function variable (byval variable string), error. if use actual column name works great. should using different syntax? the issue you're trying pass string "variable" column header , not string you're passing in method. try this, pass in term set in variable "variable": "table4[" & variable & "]"

Why do python's different forms for import behave differently for circular imports? -

i'm creating python 2.7 library following directory structure: $ pwd ~/code/myproject $ tree . |- myproject | |-- __init__.py | |-- exception.py | |-- myproject.py here contents of 3 files: $ cat __init__.py import myproject $ cat myproject.py . import exception $ cat exception.py . import myproject when import new library second project, exception in raised: traceback (most recent call last): <snip> file "~/code/myproject/myproject/exception.py", line 1, in <module> . import myproject importerror: cannot import name myproject i understand fix change contents of exception.py to: import myproject ... don't know why. best practices seem recommend using relative imports files in package. why import behaviour change when exception.py changes from . import myproject import myproject ?

keyboard - iOS 8's documentContextBeforeInput only returns partial text -

i using ios 8's provided keyboard extension's textdocumentproxy.documentcontextbeforeinput text user has entered in order perform sort of modification it. i noticed while method documentcontextbeforeinput work fine chucks of texts, periods "." inserted, documentcontextbeforeinput able return text occurs after period. for example, testing following text: "this sentence 1. , sentence 2" when using documentcontextbeforeinput placing cursor @ end, return "and sentence 2", , not entire text has come before it. has encountered issue, , if have discovered workaround? thanks!

infiniband - How to use SRQ with different connections in libibverbs -

how use srq when connected more 1 connections. lets say, there 3 connections namely process 0, 1 , 2. creating srq, need call struct ibv_srq *ibv_create_srq(struct ibv_pd *pd, struct ibv_srq_init_attr *srq_init_attr); for above call need provide protection domain, in knowledge, protection domain allocated specific each connection call ibv_alloc_pd(id->verbs) in id created each channel. basically, question how assign srq different qp belonging different connection id different protection domain, or in other words, different connections can have same protection domain? a single srq or pd cannot shared among multiple processes. point of srq reduce number of receives need posted when single process has many qps. , sharing srq among processes wouldn't make sense. when post receive srq, buffer have come address space of 1 of processes. if receive on different process's qp used work request, process wouldn't able access data had received (since buffer b

linux - Shell Error: Jenkins not reading sub command -

for reason, jenkins having issues running section of code: svn merge --reintegrate ../branches/${branch_to_merge} --username "${ldap_user_id}" --password "${ldap_user_passwd}" >$logfile 2>&1 however when written below...it works!!!? cd ${workspace}/workspace/trunk svn merge ../branches/${branch_to_merge} --username "${ldap_user_id}" --password "${ldap_user_passwd}" >$logfile 2>&1 am missing something?

Decoding Particular Element of JSON In PHP -

i trying decode json i reading json through stomp. there different json datasets need work out json dataset has come through. reading title. however there 1 particular dataset having trouble reading foreach (json_decode($msg->body,true) $event) { if(isset($event['schemalocation'])) { $schedule_id=($event['schedule']['schedule_start_date']); $signalling_id=($event['schedule']['schedule_segment']['signalling_id']); echo $schedule_id; } in above example isset function works fine , $schedule_id obtains right answer however $signalling_id gives error of undefined index: here dump of part of json (its rather long............).the piece of json signalling_id towards end of json. variable signalling_id appreciated. array(7) { ["schemalocation"]=> string(72) "http://xml.networkrail.co.uk/ns/2008/train itm_vstp_cif_messaging_v1.xsd" ["classification"]=>

scala - How do I make a trait that I can mix into mapped fields to that I don not have to override the same properties for many fields in a database? -

in scala lift framework, how make trait can mix mapped fields don not have override same properties many fields in database? i eliminate redundancy in code below. specifically, not want have repeatedly add: override def writepermission_? = false override def readpermission_? = false override def shoulddisplay_? = false override def show_? = false override def dbdisplay_? = false for several db fields. thinking way go write trait looks this: trait privatefield extends ...??? { override def writepermission_? = false override def readpermission_? = false override def shoulddisplay_? = false override def show_? = false override def dbdisplay_? = false } and mix object overrides follows: object owner extends mappedlongforeignkey(this, user) privatefield object status extends mappedint(this) privatefield etc. way approach problem? if so, suggestions on how write trait? below code want reduce redundancy. class mytable extends longkeyedmapper[mytable] id

Haskell lenses: how to make view play nicely with traverse? -

i trying learn lenses implementing in haskell. have implemented view combinator follows: {-# language rankntypes #-} import control.applicative import data.traversable type lens s = functor f => (a -> f a) -> s -> f s view :: lens s -> s -> view lens = getconst . lens const however when try use in conjunction traverse following error message: prelude> :load lens.hs [1 of 1] compiling main ( lens.hs, interpreted ) ok, modules loaded: main. *main> :t view traverse <interactive>:1:6: not deduce (applicative f) arising use of ‘traverse’ context (traversable t) bound inferred type of :: traversable t => t -> @ top level or (functor f) bound type expected context: functor f => (a -> f a) -> t -> f (t a) @ <interactive>:1:1-13 possible fix: add (applicative f) context of type expected context: functor f => (a -> f a) -> t -

algorithm - N th term of series:0,1,3,6,10,15,21, -

0,1,3,6,10,15,21,... each term gets incremented in order of natural numbers tried generate nth of series ended tle here's code s=0 for(int i=1;i<=n;i++) s=s+(i-1); can me better algorithm. this series, gives n sum of natural number 0 n . there simple formula calculating (n * (n+1)) / 2 .

Clarifying RxJava Observable Threading with Retrofit -

at http://square.github.io/retrofit/ talks asynchronous, there phrase "observable requests subscribed asynchronously , observed on same thread executed http request" wanted clarify. so in case thread execute http request: lets main thread makes call observable getuserphoto(@path("id") int id)? main thread or thread subscribe request execute http request? regarding documentation, thread execute request. if result of request change in view, may need observe (consume) result in main thread. in case, add call observeon method before subscribe observable.

regex - Regular expression for condition until next space -

how write regular expression grabs capital letter located anywhere subsequent character until space? input: cake pietypeapple crumble tart toasttexas price for example, want grab "apple" despite not being preceded space. want "crumble". want "texas" though not of components upper case. i use gsub(pattern, replacement = "", x = string) following output output: cake pietype tart toast price thanks! you can use regmatches extract these substrings. > x <- 'cake pietypeapple crumble tart toasttexas price' > regmatches(x, gregexpr('[a-z]\\s+', x))[[1]] # [1] "apple" "crumble" "texas" alternatively, if want strict on matching letter characters only. > regmatches(x, gregexpr('[a-z][a-za-z]+', x))[[1]] if want replace them, use following avoid excess space left in between words. > gsub('[a-z][a-za-z]+( [a-z][a-za-z]+)*', '', x) # [1]