Posts

Showing posts from January, 2015

Python not creating file -

i'm trying write text file in python. file doesn't yet exist i'm using: def writetotextfile(players): file = open('rankings.txt', 'a') player in players: file.write(player.name, player.rating, player.school, '\n') file.close() i used 'a' append , thought create new file (based on documentation). on desktop (where i'm running script from) , there's no "rankings.txt" file found. any thoughts on how fix? thanks, bclayman the syntax write command incorrect. function accepts string argument. example: file.write("{}, {}, {}\n".format(player.name, player.rating, player.school)) i've mocked quick example of full script show in action: class player(object): def __init__(self, name, rating, school): self.name = name self.rating = rating self.school = school def writetotextfile(players): f = open('rankings.txt', 'a') ...

java - Unfortunately app has stopped [ Read EPub File ] -

when run project in eclipse, error: unfortunately app has stopped i unable run project. please me solve issue. this app simple read .epub book file usd http://www.siegmann.nl/epublib/android @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); webview webview = (webview) findviewbyid(r.id.webview); nl.siegmann.epublib.domain.book book=null; try { epubreader epubreader = new epubreader(); book = epubreader.readepub(new fileinputstream("/book/test.epub")); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } string baseurl = "/book/"; string data=null; try { data = new string(book.getcontents().get(1).getdata()); } catch (ioexception e) { ...

android - How can I populate a ListView(TwoWayView) with json? -

i have json saved @ apps data folder want use populate listview with. the json structure basic: { "somelist": [ { "first": "first item" "second": "second item" }, { "first": "third item", "second": "fourth item" }, { "first": "fifth item", "second": "sixth item" } ] } in set hardcoded text with viewholder.first.settext("first item"); viewholder.second.settext("second item"); is there way have retrieve data stored json file? the short answer yes there way. here steps: load file directory inputstream = getresources().openrawresource(r.raw.json_file); writer writer = new stringwriter(); char[] buffer = new char[1024]; try { reader reader = new bufferedreader(new inputstreamreader(is...

html - jsoup returning <thead> tags when <tr> tags are selected? -

i new jsoup , might using wrong. going contact mailing list jsoup instructs post here first . trying select <td> elements table first element returned <thead> . wrong way <td> elements given table? if so, right way? simple representative issue below: html: <table id="results_table"> <thead> <th>header1</th> </thead> <tbody> <tr> <td>td1</td> </tr> </tbody> </table> test: string pagehtml = ioutils.tostring(this.getclass().getresourceasstream("sample.html")); document doc = jsoup.parse(pagehtml); element table = doc.getelementbyid("results_table"); elements trs = table.getelementsbytag("tr"); system.out.println("size: " + trs.size()); system.out.println("first element: " + trs.get(0).html()); system.out.println("second element: " + trs.get(1).html()); received ...

python - How do I split on the space-separated math operators here? -

i have user calculator accepts both numbers , user-defined variables. plan split statement on space-delimited operator, e.g. ' + ': import re query = 'house-width + 3 - y ^ (5 * house length)' query = re.findall('[+-/*//]|\d+|\d+', query) print query # ['house-width + ', '3', ' - y ^ (', '5', ' * house length)'] expecting: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)'] using re.split capturing parentheses around split pattern seems work effectively. long have capturing parens in pattern patterns splitting on kept in resulting list: re.split(' ([+-/*^]|//) ', query) out[6]: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)'] (ps: i'm assuming original regex want catch // integer division operators, can't s...

regex - Regular Expression for Benchmark calculations in Python -

Image
i trying write regular expression capture latency of size 1 (i.e. 1.15). using following regular expression: (?!1\s+)([\d.]+) # osu mpi latency test v4.4.1 # size latency (us) 0 1.11 1 1.15 2 1.14 4 1.14 8 1.14 16 1.16 32 1.18 64 1.22 128 1.31 256 1.83 512 1.95 1024 2.28 2048 2.79 4096 3.20 8192 4.53 16384 6.96 32768 10.17 65536 15.63 131072 26.01 262144 46.70 524288 88.15 1048576 171.87 2097152 339.42 4194304 668.69 i expecting 306 values end 293. not sure if regular expression written incorrectly. size of text file huge (306...

r - Iterating a list of data frames through a function -

i have written function strip down data frame contain columns want plot. want iterate list of data frames through function, each individual data frame contains info relevant plot. here function: clean_data <- function(show_df){ show_data <- show_df[,c(1:2,7)] colnames(show_data) <- c("week", "weeklygross", "avgticketprice") #turns weeklygross numeric values show_data$weeklygross <- gsub('[^a-za-z0-9.]', '', show_data$weeklygross) show_data$weeklygross <- as.numeric(show_data$weeklygross) #turns avgticketprice numeric values show_data$avgticketprice <- gsub('[^a-za-z0-9.]', '', show_data$avgticketprice) show_data$avgticketprice <- as.numeric(show_data$avgticketprice) show_data } and here code when attempt iterate list of data frames through function: df.list <- list(atw_df, cly_df, gent_df, kin_df, mo_df,on_df, van_df, war_df) new_list <- lis...

ruby - Regex that matches a pattern but does not match ":" -

i have regex looks types of hostnames like: .*-.*(nmtg)*|.*(\.nms) . how modify not match: 11.22:33:44:55-66 ? should match: cs25-admin.nmtg.company.com cs25-admin but should not match: 11.22:33:44:55-66 two basic ways: you can replace "match anything" . "match except colon" [^:] everywhere you can prepend expression "no colons here end of string" (?!.*:) edit signus said, regexp non-specific , open-ended; match more think. example, "----thricenmtgnmtgnmtg" full match, , "(-_-)" . better policy , easier specify want, rather go listing exceptions. regexps suggested signus example. they still match within strings: "dont match this: example.com" still match "example.com" part. if want, cool. if not, want anchor start , end of string, surrounding regexp /^.....$/ .

android - Is incentivised sharing allowed / possible? -

i encourage user engagement in app rewarding them once off advantage (a kind of power-up guess) when share on social media (twitter, google+ or facebook). my first question is, considered acceptable google play store? my next question (assuming answer first yes), how sure user has completed share not reward cancelled share intents? my initial attempt has focussed on facebook , have set facebook sdk, registered app facebook , can complete share, others have shown share result same regardless of whether user cancelled or posted. note similar questions have been asked here , here . none of these have satisfactory solutions. this answer sounds promising, don't recognise "session" type part of facebook sdk . my implementation @ moment uses in fragment in response user's button press: if (sharedialog.canshow(sharelinkcontent.class)) { sharelinkcontent linkcontent = new sharelinkcontent.builder() .setcontenttitle(...

Extract string using regex in Python -

i'm struggling bit on how extract (i.e. assign variable) string based on regex. have regex worked out -- tested on regexpal. i'm lost on how implement in python. regex string is: http://jenkins.mycompany.com/job/[^\s]+ what want take string , if there's pattern in there matches regex, put entire "pattern" variable. example, given following string: there problem http://jenkins.mycompany.com/job/app/4567. should fix this. i want extract http://jenkins.mycompany.com/job/app/4567 and assign variable. know i'm supposed use re i'm not sure if want re.match or re.search , how want. or pointers appreciated. import re p = re.compile('http://jenkins.mycompany.com/job/[^\s]+') line = 'there problem http://jenkins.mycompany.com/job/app/4567. should fix this.' result = p.search(line) print result.group(0) output: http://jenkins.mycompany.com/job/app/4567.

javascript - Dropdown child menu not displaying any data? -

i have simple dropdown menu in codeigniter form. when clicking dzongkhag(district) should display list of geogs(towns), but, instead not so. drop down menu have not best 1 come after trying (for many weeks) many times unsuccessfully. grateful if me out/solve/advice on this. here snippets. view.php <label >dzongkhag: </label> <select id="user_dzongkhag" name="dzongkhag" > <option>select dzongkhag</option> <option value="bumthang">bumtang</option> <option value="chhukha">chhukha</option> <option value="dagana">dagana</option> <option value="gasa">gasa</option> <option value="haa">haa</option> <option value="lhuentse">lhuntse</option> <option value="monggar">monggar</option> <option value="paro">paro</option> <option value="pema ga...

MySQL: How to remove value matching another column from beginning or end of column? -

i'm parsing through tv program data stored in sql table, , data has 2 columns, 1 program title whole (e.g. series name) , 1 program's subtitle (e.g. individual episode title). program subtitle quite contains series name within well, either @ beginning of string or @ end, or both, in following formats: e.g. title of "horizon" , correct subtitle of "the £10 million challenge", following possible combinations value in subtitle field: horizon: £10 million challenge the £10 million challenge: horizon horizon: £10 million challenge: horizon instead of colon followed space, separator space hyphen space so: "horizon - £10 million challenge - horizon" so want each row in table, if subtitle contains value in title column @ beginning of subtitle (followed ': ' or ' - ') or if value @ end of column (preceded ': ' or ' - ') or both, update subtitle remove prefix or suffix. can or point me in right direction? i...

Xamarin Labs Hybrid Web View not calling callback in some specific android devices -

i have hybrid web view labs calls js , show return... working in emulator , other devices such samsung galaxy s5... in galaxy s2 , on sony xperia not working.... took away code not important my class: public class testpage : contentpage { htmlwebviewsource hwvsource = new htmlwebviewsource(); hybridwebview hwv = new hybridwebview() { verticaloptions = layoutoptions.fillandexpand, horizontaloptions = layoutoptions.fillandexpand }; stacklayout stack = new stacklayout { verticaloptions = layoutoptions.fillandexpand, horizontaloptions = layoutoptions.fillandexpand }; public testpage () { this.hwv.registercallback ("datacallback", jscallback); //script receives list , call native('datacallback', list); .... this.hwvsource.html = @" <!doctype html> <html> <head> <script language=""javascript""> ...

java - Actual argument String cannot be converted to int by method invocation conversion - how to fix it -

hello have error: error:(36, 19) error: constructor draweritem in class draweritem cannot applied given types; required: int,int,class<? extends fragment> found: string,int,class<todofragment_> reason: actual argument string cannot converted int method invocation conversion note: c:\users\kisiel\androidstudioprojects\studentizer\app\src\main\java\pl\edu\ug\aib\studentizerapp\fragment\timetablefragment.java uses unchecked or unsafe operations. note: recompile -xlint:unchecked details. error:execution failed task ':app:compiledebugjava'. > compilation failed; see compiler error output details. information:build failed this code todofragment: package pl.edu.ug.aib.studentizerapp.fragment; import android.annotation.targetapi; import android.app.fragment; import android.os.build; import android.os.bundle; import android.text.editable; import android.text.textwatcher; import android.view.layoutinflater; import android.view.view; import android.view.viewgrou...

html - How to loop through an array and print each item into an <li> tag using PHP? -

i'm trying iterate through array using php. want items stored in <li> tag. i'm having trouble getting names print out. can count of array items printed, not names. <ul> <?php $names = array('mike', 'chris', 'jane', 'bob'); for($i=0; $i < count($names); $i++) { echo "<li>" . $i . "</li>"; } ?> </ul> <ul> <?php $names = array('mike', 'chris', 'jane', 'bob'); foreach($names $name) { echo "<li>" . $name . "</li>"; } ?> </ul>

xml parsing - Read specific content of POM xml file through groovy xmlSurper and download dependecy -

i have below pom file.i want use xmlslurper groovy code read specific content of pom file can tell me how write code read specific content through groovy xmlslurper.i want read groupid artifact id,classifier , type of scope runtime in below pom file. <?xml version="1.0" encoding="utf-8"?> <project xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <modelversion>4.0.0</modelversion> <groupid>com.ss.engine</groupid> <artifactid>nti</artifactid> <version>4.0.0.110</version> <description>configuration management gradle plugin</description> <dependencies> <dependency> <groupid>com.ss.engine</groupid> <artifactid>license</artifactid> <version>4....

java - Tomcat Custom LoginModule -

i have web application accesses external data source. data source has own access control decided secure web application using external data source authentication provider. created custom jaas loginmodule. authentication works great when deployed on tomcat upon successful authentication external data source, returns session key (ex. e2e9c2bf-d1ce-43f4-bc2f-37984c5b28f7) should used subsequent requests data. my problem i'm unable find way store key in loginmodule used later. thought creating http session request , storing attribute work doesn't seem possible in loginmodule running on tomcat. have suggestions? in advance.

c# - Throwing Exceptions in Unity -

i'm working on simple script utilizes canvas inputfield , button. when player presses button, script checks text of inputfield. problem having if nothing entered, unity exits unassignedreferenceexception. i tried catching exception must doing horribly wrong: public class quiz : monobehaviour { public gameobject quizpanel; public gameobject input; public void checkanswer(){ text answer = (input.getcomponent<text>()) text; try { if (answer.text == "george washington") { debug.log("true"); } }catch (unassignedreferenceexception) { debug.log ("wrong answer"); } } } i have reasons believe input variable somehow invalid. i'll advise make try/catch encapsulate of code: public void checkanswer(){ try { text answer = (input.getcomponent<text>()) text; if (answer.text == "george washington...

jssor - Arrow Navigation is displayed but does not function -

i using jssor slider 18.0 jquery 1.3.2. arrow navigator show on slides seems disabled. not work , neither style change on hover. in addition using jssor.slider.mini.js using jquery jsuggest, jquery validate , uupaa-suketrans.js. hope there nothing conflicting. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"> var options = { $autoplay: false, $autoplaysteps: 2, $autoplayinterval: 3000, $pauseonhover: 1, $arrowkeynavigation: true, $slideduration: 500, $mindragoffsettoslide: 20, $slidespacing: 0, $cols: 1, $align: 0, $uisearchmode: 1, $playorientation: 1, ...

vb.net - Recovery on Failure for a Windows Service Application -

i having trouble getting feature recovery on failure work windows service application. set in restart application on first failure. test in use line of code system.environment.exit(-1) this causes application end okay doesn't restart. it reasonable suppose service process exiting without setting service status stopped constitute failure. however, isn't case. (perhaps backwards compatibility; there might many third-party services such change break.) however, if process exits result of unhandled exception, considered service failure , triggers recovery options. if want cause service fail, raise exception (and don't catch it).

swift - Read and write data from text file -

i need read , write data to/from text file, haven't been able figure out how. i found sample code in swift's ibook, still don't know how write or read data. import cocoa class dataimporter { /* dataimporter class import data external file. class assumed take non-trivial amount of time initialize. */ var filename = "data.txt" // dataimporter class provide data importing functionality here } class datamanager { @lazy var importer = dataimporter() var data = string[]() // datamanager class provide data management functionality here } let manager = datamanager() manager.data += "some data" manager.data += "some more data" // dataimporter instance importer property has not yet been created” println(manager.importer.filename) // dataimporter instance importer property has been created // prints "data.txt” var str = "hello world in swift language." for reading , writing should ...

html - Date in Javascript Div loop not updating correctly -

i'm trying generate 3 divs in loop , insert datetime in each iteration . problem i'm running while function generates 3 div's correctly appends same time 3 div's leaving me (javascript newbie) believe date() function being executed once . if explain me going on appreciate it. ideally replace date function graph's , have graph load in each div. function gengraphs () { (i=0; < 3; ++i) { var divtag = document.createelement("div"); divtag.style.width ="1000px"; divtag.style.height ="600px"; divtag.id = "graph"+i; document.body.appendchild(divtag); divtag.innerhtml = date(); // divtag.appendchild(getgraph(divtag)); // divtag.innerhtml = getgraph(divtag); } } the server executing script fast enough (in milliseconds) date() returned not visibly different. try delay or use increment variable i

android - How to turn on activity-based application into a fragment -

i learn programming mobile applications. decided convert 1 application of activity fragment, have problem. maybe of able me. package pl.edu.ug.aib.studentizerapp.fragment; import android.app.fragment; import android.os.bundle; import android.text.editable; import android.text.textwatcher; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.arrayadapter; import android.widget.button; import android.widget.edittext; import android.widget.listview; import android.widget.tabhost; import android.widget.textview; import android.widget.toast; import org.androidannotations.annotations.efragment; import java.util.arraylist; import java.util.list; import pl.edu.ug.aib.studentizerapp.r; import pl.edu.ug.aib.studentizerapp.todolist.databasehandler; import pl.edu.ug.aib.studentizerapp.todolist.task; @efragment(r.layout.fragment_todo) publ...

class - How to make dictionary element an object in python? -

how make dictionary element object in python? i made class… class qs: def __init__(self,list1,id,quest="",mark=1): self.__list1=list1 self.__id=id self.__quest=quest self.__mark=mark self.__list1.update({self.__id:{self.__quest:self.__mark}}) how can store objects in dictionary can call functions in class this? dictionary[1].print() what want class includes dictionary in it: class questioncollection: def __init__(self): self.listofquestions = dict() def print(self,question_number): print(dictionary[question_number]) then this: classobject = myclass() classobject.listofquestions[1] = qs(...) classobject.print(1) or, classobject = myclass() print(classobject.dictionary[1]) then, extend class include other functions operate on entire dictionary.

java - Instantiate Parameterized Type class with Class<?> variable -

(note: have searched multiple questions on in similar domain, never encountered answer specific idea). consider if have class or enum foo each instance has class<?> type field: public enum foo { (integer.class), b (double.class), c (string.class); public final class<?> type; foo(class<?> type) { this.type = type; } } then have generic class bar<v> : public class bar<v> { private v value; // default constructor public bar() {} // getter public v getvalue(){ return value; } // setter public void setvalue(v value){ this.value = value; } } is possible instantiate instance of bar type class<?> type field of given foo without knowing specific type of foo.type ? instance, call in either static method, or kind of factory method. edit: to specify function of bar: bar wraps around value simple getter/setter, , has consistent interface, unknown type. bene...

Visual Studio How to add Python module to Intellisense -

Image
how add custom python module visual studio intellisense code completion tool? situation: working on python module references module have saved in /mypython/foo.py. if start type foo.somedef intellisense recognize accessing module , suggest code completion. visual studio's intellisense recognize custom python modules after have been placed in "site-packages" folder under "lib" folder in python's directory. for example: /python27/lib/site-packages/mypython inside of folder "mypython", put plain text file called "__init__.py". otherwise intellisense not recognize package. you may have click "refresh db" under python environments tab.

ios - Unit testing secret keys -

i using cocoapods-keys , trying test if method returns valid url secret api key. test suite looks this: it(@"should return valid url api", ^{ nsurl *url = [apiroutes apiurlwithpath:path parameters:nil]; expect([url absolutestring]).to.equal([nsstring stringwithformat:@"http://www.api.com/api/v2/places?api_key=my_api_key"]); }); but real method returning valid api key hash (e.g. 8s97f89asf89asf987saf) , test fails. how can test this? should create fake implementation of class in test file? the way go mock url , api key apiroutes holds , test expected complete mock url. way test logic , not specific value of url.

osx - mongod.lock file permissions on shared system -

i working on shared mac os x 10.6 system, , having trouble setting instance of mongodb. not have way of attaining root privileges. i have set separate --dbpath standard /data/db directory. when run mongod custom configuration file, common 10310 error: 2015-06-02t12:18:53.110-0700 kern.sched unavailable 2015-06-02t12:18:53.115-0700 [initandlisten] mongodb starting : pid=88680 port=27017 dbpath=/mir/ew/ntellis/mongodata 64-bit host=fornax.astro.berkeley.edu 2015-06-02t12:18:53.115-0700 [initandlisten] 2015-06-02t12:18:53.115-0700 [initandlisten] ** warning: soft rlimits low. number of files 256, should @ least 1000 2015-06-02t12:18:53.115-0700 [initandlisten] db version v2.6.10 2015-06-02t12:18:53.115-0700 [initandlisten] git version: 5901dbfb49d16eaef6f2c2c50fba534d23ac7f6c 2015-06-02t12:18:53.115-0700 [initandlisten] build info: darwin bs- osx-108-x86-64-2.10gen.cc 12.3.0 darwin kernel version 12.3.0: sun jan 6 22:37:10 pst 2013; root:xnu-2050.22.13~1/release_x86_64 x8...

javascript - Angular ngGrid Tree Control: Make a round trip on group expand -

i trying use nggrid make of "tree-control" can build dynamically calling api's. nggrid allows grouping on rows, yet nature of requires rows present @ beginning. unfortunate fact api pull generation data file integrity monitoring system insanely slow , stupid. instead, wish build "tree" dynamically on expansion of each generation. i trying inject children ( ngrows ) group-row ( ngaggregate ) on callback, yet not think calling correct constructor ngrows fact rows ignored control through use of aggregatetemplate option on gridoptions nggrid , have been able intersept expansion of group quite easily. (maybe not easily, still) i've replaced ng-click of default template: ng-click="row.toggleexpand()" with: ng-click="$parent.$parent.rowexpanded(row)" i know it's bit of hack, can later. now, gets job done. the way discovered how work way $scope rowexpanded function setting breakpoint in nggrid 's " row.to...

css - Applying &:before to top level of menu only -

i have following html structure cannot edit: <div id="menu"> <ul class="nav nav-pills nav-stacked"> <li class="active"><a href="#">home</a> <ul class="sub-menu"> <li class="active"><a href="#">home</a></li> <li><a href="#">profile</a></li> <li><a href="#">messages</a></li> </ul> </li> <li><a href="#">profile</a></li> <li><a href="#">messages</a></li> </ul> </div> i using sass style triangle inserted before text inside link: #menu{ width:300px; .nav li{ a{ border-bottom: 1px solid #ededde; &:before { content: ""; display: inline-block; width: 0; ...

c# - Why the "View Heap" result does not match with 'Process Memory Usage' in Visual Studio -

Image
i trying use visual studio track memory usage in app. in 'diagnostic tools' window, shows app using 423 mb. thank go 'memory usage' , 'viewheap', when click on snapshot, table of size of objects. but when add number up: = 3317228 +403764+354832+264984+244836+195748+144032+28840+16452+13920+13888+3428+2100+20 = 5004072 = 4.77 mb my question why number 4.77mb not match 423mb see on "memory" chart. expect see table on left breakdown of 423 mb went. please tell me missing? why view heap size not match memory chart size? there dozens of potential reasons this, including jitter , debug tools , debug symbols , just code , garbage collection et al. we'll go through 2 of big ones. just code the just code feature of visual studio tends hide allocations, exceptions, breakpoints, , other non-code meta-data user, not loaded .pdb file or open project. see msdn code details. debugging symbols , tools when debugging any project ...