Posts

Showing posts from January, 2010

python - morse code to english python3 -

i want convert morse code english using python 3+ have managed convert english morse code using http://code.activestate.com/recipes/578407-simple-morse-code-translator-in-python/ but want convert morse code english i have attempted 1 charecter @ time, problem morse code letters not 1 charecter long english letters, e "." , s "...", problem have dictionary loop find "." , match e, instead of getting s "e e e" tried fix detecting spaces , doing word @ time, instead of looking letters in word searches entire word against dictionary i'm new python , dictionaries , don't know how differeniate between e "." , s "..." when searching dictionary here code # defines dictionary convert morse english code_reversed = {'..-.': 'f', '-..-': 'x', '.--.': 'p', '-': 't', '..---': '2', '....-': '4'

Elasticsearch analyzer couldn't found Exception -

i created index settings of analyzer , shows analyzer settings when call index properties. when try use index analyzer throws exception named " analyzer couldn't found". here analyzer settings; "settings":{ "index":{ "settings":{ "analysis":{ "filter":{ "turkce_lowercase":{ "type":"lowercase", "language":"turkish"}, "turkce_stop":{ "type":"stop", "stopwords_path":"/home/power/documents/stop_words.txt"} }, "analyzer":{ "turkce":{ "filter":["turkce_lowercase","turkce_stop"], "tokenizer&qu

sql - XML file parsing in oracle database -

i have 1 xml file named abc.xml in path c:/error_log/abc.xml. i want insert content of file in 1 table "employee" in oracle database through procedure. can me procedure how read xml file in oracle database.

Magento Exception Error: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'magentoce.tax_calculation_rule' doesn't exist -

i have installed magento, home page clicked on product, giving error: 347147223 . there has been error processing request sqlstate[42s02]: base table or view not found: 1146 table 'magentoce.tax_calculation_rule' doesn't exist, query was: (select `main_table`.`tax_calculation_rate_id`, `main_table`.`tax_calculation_rule_id`, `main_table`.`customer_tax_class_id`, `main_table`.`product_tax_class_id`, `rule`.`priority`, `rule`.`position`, `rule`.`calculate_subtotal`, `rate`.`rate` `value`, `rate`.`tax_country_id`, `rate`.`tax_region_id`, `rate`.`tax_postcode`, `rate`.`tax_calculation_rate_id`, `rate`.`code`, if(title_table.value null, rate.code, title_table.value) `title` `tax_calculation` `main_table` inner join `tax_calculation_rule` `rule` on `rule`.`tax_calculation_rule_id` = main_table.tax_calculation_rule_id inner join `tax_calculation_rate` `rate` on rate.tax_calculation_rate_id = main_table.tax_calculation_rate_id left join `tax_calculation_rate_title` `titl

Laravel commands and jobs -

i wondering difference between different command-like classes in laravel 5.1. far can tell laravel 5.1 has following available: console commands ( artisan make:console ) commands ( artisan make:command ) handlers ( artisan make::command --handler ) jobs ( artisan make:job ) i have come straight 4.2 5.1 don't know happened in between 4.2 , 5.1, have been told middle 1 ( just commands) not supposed used more - in when queue-able jobs became 'commands' in 5.0, laravel since decided against this, , they're in compatibility. however, i'm not 100% on point, clarification appreciated. my specific use-case want place put self-contained 'runnable' task. example, remove files older 5 days given directory (but anything). at first sounds console command - want able run artisan , start. may want on schedule (great, artisan schedule:run runs console commands). may want execute asynchronously code. console commands can run synchronously artisan::call(

java - Jtext field to listen without pressing enter -

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.documentevent; import javax.swing.text.document; import java.sql.connection; import java.sql.databasemetadata; import java.sql.drivermanager; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; @suppresswarnings("serial") public class save extends jpanel { connection con; statement st; resultset rs; string trailername; string blockname; string locationname; string newline = "\n"; string text; jcombobox<?> trailerlist; jcombobox<?> blocklist; jcombobox<?> locationlist; jtextfield textfield; jtextarea textarea; public save() { super(new borderlayout()); textfield = new jtextfield(20); textarea = new jtextarea(5, 20); textarea.seteditable(false); textfield.addactionlistener(new actionlistener() { public void actionperformed(actionevent evt) {

javascript - Angular-JS routing get data from MVC controller -

i have implemented code retrieve data mvc controller using angular-js using ngroute . have implemented is, have 2 action methods in mvc controller , @ client side have 2 menu buttons , clicking on each button, retrieves data respective action method. have used angular-route , angular factory method , ng-view till fine. can see angularjs doesn't go action method every time when click on button. once data have been retrieved, shows respective view. , in situation cannot retrieve fresh data database. if have call action method every time how can achieve ? this have implemented: accountcontroller: public actionresult getaccounts() { var repo = new accountrepository(); var accounts = repo.getaccounts(); var settings = new jsonserializersettings { contractresolver = new camelcasepropertynamescontractresolver() }; var jsonresult = new contentresult { content = jsonconvert.serializeobject(accounts, settings), contenttype =

php - Laravel download file from S3 route (not open in browser) -

i have following route load file given url, need download file (mp4, jpg, pdf) rather open in browsers in built viewer. // download cdn route route::get('cdn/{url}', function($url) { return redirect::away($url); })->where('url', '(.*)'); all files stored externally apparently resource::download() wouldn't work. all have available me amazon url: https://mybucket.s3.amazonaws.com/folder/filename.pdf any suggestions on how force browser download file s3? in case simple anchor link downloading file ... <a href="https://mybucket.s3.amazonaws.com/folder/filename.pdf"> file name </a>

php - Laravel Unit Testing AuthController -

i'm new unit testing , want try laravel 5.0. i created authtest , implemented method checking if user known (stored in database) , credentials correct. i don't know how test in best practice way. here i've done far: public function testifcorrectcredentialsareaccepted() { $credentials = [ '_token' => csrf_token(), 'username' => 'test', 'password' => 'test' ]; $user = user::create([ 'username' => $credentials['username'], 'firstname' => 'test', 'surname' => 'test' ]); $this->call('post', '/auth/login', $credentials); $this->asserttrue(\auth::check()); db::table('users')->where('username', $user->username)->delete(); } the known users stored inside database, credential validation done on adldap ldap-connector (laravel service provider extending laravel auth). am going right way, or failing

pdf - Force add new page in pyFPDF using python -

i'm using pyfpdf templates generate pdf want print 2 pages not 1 possible! example: elements = [ { 'name': 'company_logo', 'type': 'i', 'x1': 20.0, 'y1': 17.0, 'x2': 78.0, 'y2': 30.0, 'font': none, 'size': 0.0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'i', 'text': 'logo', 'priority': 2, }, { 'name': 'company_name', 'type': 't', 'x1': 17.0, 'y1': 32.5, 'x2': 115.0, 'y2': 37.5, 'font': 'arial', 'size': 12.0, 'bold': 1, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'i', 'text': '', 'priority': 2, }, { 'name': 'box', 'type': 'b', 'x1': 15.

security - how to connect to secure hbase cluster using SQuirreL SQL -

i trying setup squirrel sql client connect secure hbase cluster deployed on cdh5.4.3. i have copied kerberos keytab file, hbase-site.xml , core-site.xml in lib directory of squirrel sql. using phoenix-4.3.0-client containing required jars. the connection url format used is: jdbc:phoenix:[quorum]:[port]:[rootnode]:[principal]:[keytab] below error squirrel's logs: 2015-08-19 18:24:57,696 [pool-1-thread-1] info org.apache.hadoop.hbase.client.hconnectionmanager$hconnectionimplementation - getmaster attempt 1 of 35 failed; retrying after sleep of 100, exception=com.google.protobuf.serviceexception: org.apache.hadoop.net.connecttimeoutexception: 20000 millis timeout while waiting channel ready connect. ch : java.nio.channels.socketchannel[connection-pending remote=abc.xyz.com/10.201.15.151:60000] 2015-08-19 18:24:58,386 [pool-1-thread-1] info org.apache.hadoop.hbase.client.hconnectionmanager$hconnectionimplementation - getmaster attempt 2 of 35 failed; retrying after

hadoop - Hive Create Multi small files for each insert in HDFS -

Image
following been achieved kafka producer pulling data twitter using spark streaming. kafka consumer ingesting data hive external table(on hdfs). while working fine far. there 1 issue facing, while app insert data hive table, created small file each row data per file. below code // define topics read val topic = "topic_twitter" val groupid = "group-1" val consumer = kafkaconsumer(topic, groupid, "localhost:2181") //create sparkcontext val sparkcontext = new sparkcontext("local[2]", "kafkaconsumer") //create hivecontext val hivecontext = new org.apache.spark.sql.hive.hivecontext(sparkcontext) hivecontext.sql("create external table if not exists twitter_data (tweetid bigint, tweettext string, username string, tweettimestamp string, userlang string)") hivecontext.sql("create external table if not exists demo (foo string)") hive demo table populated 1 single record. kafka consumer lo

multithreading - Synconisized List/Map in Java if only one thread is writing to it -

the first thread filling collection continuously objects. second thread needs iterate on these objects, not change collection. currently use collection.synchronized... making thread-safe there fast way doing it? sorry not giving information context: it's simple: first thread (ui) continuously writes mouse position arraylist, long mousebutton pressed down. second thread (render) draws line based on list. even if synchronize list, it's not thread-safe while iterating on it, make sure synchronize on it: synchronized(synchronizedlist) { (object o : synchronizedlist) { dosomething() } } edit: here's written article on matter: http://java67.blogspot.com/2014/12/how-to-synchronize-arraylist-in-java.html

java - android spinner change the background color for specific items -

i have spinner , want change background color specific items. mean if object named: country , if have value section=true item of spinner have background color = blue . @override public view getview(int position, view convertview, viewgroup parent) { final kamcoreporttype report = values.get(position); if (convertview == null) { context mcontext = this.getcontext(); layoutinflater vi = (layoutinflater) mcontext.getsystemservice(context.layout_inflater_service); textview tv=(textview) convertview.findviewbyid(r.id.textview01); if (report.issection()) tv.setbackgroundcolor=blue //what ever how can that. on getview() method can do: if (yourcondition) { tv.setbackgroundcolor(getcontext().getresources().getcolor(r.color.blue)); } this should trick. @update if got right, want current item on getview() method, right? i assume adapter extending arrayadapter<t> . if case, can items using arrayadapter g

How do I declare Maybe of a mutable type in an non-pure native function in Frege? -

the native-gen tool generates native declaration showopendialog method in javafx.stage.filechooser so data filechooser = mutable native javafx.stage.filechooser native showopendialog :: filechooser -> window -> io file compiling leads message non pure native type file must mutableio file in io actions. now setting native showopendialog :: filechooser -> window -> mutableio file leads to filechooser.showopendialog has illegal return type method not pure, perhaps st s (mutableio file) work but following advice leads first error message again. the compiler accepts iomutable file return type, makes sense since io action returns mutable type. if possible, compiler error message should adapted avoid frustration on user side. however, in special situation, file can null , core type not file maybe file . using iomutable (maybe file) leads rather surprising message the type mutableio (maybe file) illegal, maybe file must native type

Adding new column to Excel Source in SSIS -

i working on ssis project. source excel file. working data it, querying database, , retrieving needed records. so, question is: how add programmatically new data column in excel source file , insert in these new records? i have question - how delete rows excel in sql task? i would 1. create new excel file new column(s) using "execute sql task". e.g. create table `walks` ( ` date` nvarchar(255), `id` nvarchar(255), `distance` decimal, `max` decimal, `flat time` nvarchar(255) ) process existing excel / database , populate new excel. move/copy (initially) original excel elsewhere perhaps delete once working! rename new excel file original. note: a) need delay validation package b) set data connection new excel file. c) provide variable hold path new exel file. d) need file system task precede "execute sql task" delete excel file (using variable excel path) "execute sql task" can create it!

c++ - Qt Layout relationship between QLayoutItem and QWidget -

this isn't clarified in documentation, happens when instance, call qboxlayout::insertwidget. allocates qlayoutitem, somehow associates widget , adds qlayoutitem layout? why need such indirection? i'm making custom layout , want able insert widgets @ index of layout, not aware of mechanics. because layouts operate layout items, not widgets. qlayoutitem contains list of it's own functions used position layoutitem inside layout, , resize/align it. take simple example: have vertical layout 300px wide. means each layout item add 300px wide. imagine adding 50x50 widget it. since layout has it's own geometry, sizehing, , other stuff, able insert widget (the layoutitem stay 300px wide, , widget stay 50px wide, nothing break), hard/impossible if operated widgets directly.

PHP isset get issue error in else statement -

this question has answer here: php parse/syntax errors; , how solve them? 12 answers i trying index.php?steamusr=username get's set var , if none specified displays error specified in else statement. i have tried if empty , isset. have been trying every combo can find , still nothing. current code, bottom error message. thanks! <?php if (isset($_get['steamusr'])) { $user = $_get['steamusr']; $myinv = 'http://steamcommunity.com/id/$user/inventory/json/295110/1/'; $content2 = file_get_contents($myinv); $json2 = json_decode($content2, true); $imgurlbase = 'http://steamcommunity-a.akamaihd.net/economy/image/'; foreach($json2['rgdescriptions'] $i){ $item = $i['market_name']; $icon = $i['icon_url']; $fetchdata = 'http://steamcommunity.com/market/priceovervie

excel - Comparing goegraphic points where X and Y are in two columns -

i have huge data set x , y coordinates in them. i'm looking see if 2 events close each other in proximity, , if so, highlight events or pull them out , put them in separate worksheet. x coordinates in column v y coordinates in column w i looking points within given distance of each other. want either highlight or put them in new worksheet. one question how report this. might have 2 points close each other far 2 other point close each other. my goal take list of thousands of events , pull out ones close each other on map without having search through them all. data set continuously growing huge time saver in long run. i'm not sure if want compare x coords. find 2 x coords close y coords far apart. not sure if want, things close in 1 aspect. if want loop rows subtracting 1 another. if want find distance between 2 geographic points see below. you can distance between 2 points using pythagorean theorem. dim origpoint double dim checkpoint double dim

oauth - .NET - Single Resource Server accepting bearer tokens from multiple Authorization Server -

scenario: exposing web api pre-registered applications. api publicly exposed, should available registered applications (clients). have chosen oauth2 authorization, , resource server accepts bearer tokens authorization server. we using thinktecture identityserver v3 oauth purposes. we have chosen oauth2 client credentials flow, , sharing secret server based applications. until good. have native ios mobile app needs access our protected api. read it's not idea share secret javascript/mobile apps. also importantly ios mobile app has own identity provider (adfs). before requesting token authorization server, user must have logged in ios app. considering scenario, please suggest how resource server can trust ios native app? thought of using implicit flow. because of fact ios mobile app has own authentication, authorization server needs way determine incoming request has been authenticated using external identity provider, , issue access token automatically ios app. how ma

Adding List Data queires in Anywhere Administration application in Maximo -

i using anywhere administration application in maximo. trying add several worklist queries workexecution app. (i have worklight.properties si.adminmode=true, , have run anywhere-admin-loader allapps ant). i have additional queries in there have been added using sql , work fine on mobile device. but when try add 1 using app there no values select in select value list querybase id. there additional saved queries in wotrack saved queries but if try , type 1 of values in error. has else come across , have solution. there bug on maximo's oracle database, fixed in 7.5.2.1 fixpack made select value list empty. issue you're hitting?

Javascript function returns undefined in other function -

i have function , want call in other function api key. if return value undefined. how can solve this? function getapikey(callback) { var db = app.db; db.transaction( function (tx) { tx.executesql("select api_key settings id='1'", [], function (tx, result) { var apikey = result.rows.item(0).api_key; alert(apikey); // here works return apikey; }); } ); } function getdata() { var mykey = getapikey(); alert(mykey); // undefined } you have callback being passed param, use it! can't return async calls! function getapikey(callback) { var db = app.db; db.transaction(function (tx) { tx.executesql("select api_key settings id='1'", [], function (tx, result) { var apikey = result.rows.item(0).api_key; callback(apikey); }); }); } function getdata() { getapikey(functio

gojs - how to set nodespacing in timeline layout -

i working on gojs timeline sample( http://gojs.net/latest/samples/timeline.html ) default functionality based on dates.i have added more number of nodes existing nodes due overlapping each other. how set nodespacing in layout. in prototype code in example, find part, rewrite: var bar = line.findobject("bar"); var length = 100; var cellw = 100; if (bar && numweeks > 0) { length = bar.actualbounds.width; cellw = length / numweeks; // set size of each cell bar.gridcellsize = new go.size(cellw, bar.gridcellsize.height); // offset account starting on non-first day of week bar.gridorigin = new go.point(convertdatetox(firstsunday), bar.gridorigin.y); } here have 3 options (actually two, 3. suggestion): change var s : var length = /*the length want bar have (you take number of cells * cellw below)*/ var cellw = /*the length want each cell have*/ make configurable : do timelin

r - Convert total records per species into record x species matrix -

imagine have 9 sampling records 3 species distributed such: sp1 sp2 sp3 3 1 5 what want obtain records x species matrix, , fill 1s , 0s such: sp1 sp2 sp3 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 the number of columns matches number of species , number of rows number of records. note each row represents unique record 1 species. another option create row/column index, use sparsematrix library(matrix) create sparse matrix, can converted matrix of 0 , 1s as.matrix . it not clear whether initial dataset matrix or not. assuming matrix 3 column , 1 row, column index replicating sequence of columns elements of 'm1'. should work if vector . data.frame , have use rep(seq_along(df1), unlist(df1)) . then, create sparsematrix , specifying row index sequence of 'ci' , column index ('ci') , value 'x' 1. library(matrix) ci <- rep(seq_along(m1), m1) m2 <- as.matrix(sparsematrix(seq_along(ci), ci, x=1)) colnames(m2) &l

ios - Which iDevice is best for iPhone apps testing? -

i planning buy idevices low cost (iphone or ipod) test iphone application ( ios 5 9) , confused,which 1 best test application. application info : need internet support iphone models maps music camera (back , rear) in market have lots of devices available iphone 4s, 5c, 5s, 6, 6 plus, ipad mini 2,3, ipad retina,etc,... i confusing 1 suitable app development , testing. peoples says iphone 4s cheapest price performance cant update os above 9. please tel me 1 device development , testing if ipod 6 generation suitable mean happy. please post ideas. it depends after. every single iphone that's available sale meets criteria besides being supported ios 9. if ios9 must i'll defer list of devices supported: iphone 6 plus , iphone 6 , iphone 5s , iphone 5c , iphone 5 , iphone 4s , ipad air 2 , ipad air , ipad 4 , ipad 3 , ipad 2 , ipad mini 3 , ipad mini 2 , ipad mini , ipod touch 5g , ipod touch 6g . think real questio comes down 2 things: going daily p

delphi - Why ever declare members public instead of published? -

declaring members published has advantages on public : ability read/write member in object insepoctor of ide rtti , uses so there ever benefit declaring members public instead of published ? published have downsides? or should always declare members published , rule? ps: not duplicate; read question , answers prior posting question. "possible duplicate" question explains difference between 2 keywords, doesn't gives guidance when either should used, or advantages/disadvantages of using either. declaring published imposes storage cost because size of executable swollen contain rtti. declaring public avoids cost. it's unlikely ever matter, given immense size of modern delphi executables, containing huge amounts of code never executes. for components can edited in object inspector, difference between public , published more significant. say, how component determines properties visible in object inspector. properties should visible there, ot

java - Spring Security + LDAP always returns BadCredentialsException -

i have been trying configure spring security work ldap little success. i have following configuration beans: @bean public activedirectoryldapauthenticationprovider activedirectoryldapauthenticationprovider() { activedirectoryldapauthenticationprovider provider = new activedirectoryldapauthenticationprovider("go.com.mt", "ldap://corporate.intra"); provider.setconvertsuberrorcodestoexceptions(true); provider.setuseauthenticationrequestcredentials(true); provider.setuserdetailscontextmapper(userdetailscontextmapper()); return provider; } @bean public userdetailscontextmapper userdetailscontextmapper() { userdetailscontextmapper contextmapper = new attributesldapuserdetailscontextmapper(); return contextmapper; } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.authenticationprovider(activedirectoryldapauthenticationprovider()); } i tried creating custom mapper suggested many answe

csv - Jenkins editable email notification attachment : Mail going without attachment -

the jenkins editable email notification in sending mail without attachment.the attachment in workspace of jenkins.path of attachment jenkins\workspace\projectname\test.csv .in attachments field of editable email notification specifying projectname/test.csv attachment not getting send. have tried **/projectname/test.csv , **/test.csv , /projectname nothing seems work. ps: file size 10mb. can use "email-ext plugin". more information available here : https://wiki.jenkins-ci.org/display/jenkins/email-ext+plugin

javascript - reactjs (+meteor) on browser resize change style but not rerender complete childs tree -

im changing style of component root div browser resize. triggers every single child render also. im in process of doing complex map many child components including tables , fb fixed table component. the component has basicly 3 child tables 1 of them gets new width/height main component. in there own divs. i started react few days ago, hope can give me tips. please let me know if unclear. resizing: getinitialstate: function() { return { windowwidth: window.innerwidth, windowheight: window.innerheight }; }, handleresize: function(e) { this.setstate({ windowwidth: window.innerwidth, windowheight: window.innerheight }); }, componentdidmount: function() { window.addeventlistener('resize', this.handleresize); }, componentwillunmount: function() { window.removeeventlistener('resize', this.handleresize); }, style object var style = { width: this.state.windowwidth, height: this.state.w

cassandra - JVM Crashed : Java Heap space -

we in process of testing cassandra, part of project save images (confidential images cannot placed on disk) directly database. we saved 380 images of 909 mb no issues in 8 mins. the heap size setting follows. max_heap_size="4g" heap_newsize="1024m" the total size of table 822 mb. the issue when try fetch 1 record runs fines, moment increase search id between 1 , 4, below error. info 12:51:52 concurrentmarksweep gc in 228ms. cms old gen: 172017888 -> 200306216; par eden space: 53693192 -> 30464688; par survivor space: 6681832 -> 0 java.lang.outofmemoryerror: java heap space dumping heap java_pid2548.hprof ... info 12:51:55 concurrentmarksweep gc in 452ms. cms old gen: 200301712 -> 200301512; par eden space: 53284648 -> 52721832; heap dump file created [275541785 bytes in 2.173 secs] error 12:51:55 exception in thread thread[messagingservice-incoming-/192.168.0.46,5,main] java.lang.outofmemoryerror: java heap space @ org.a

c# - VMWare API disconnect USB-Passthrough -

i using vmware workstation (v11) run virtual machine testing. i'd pragmatically add , remove usb-devices attached system. using vmware.vim; can connect server , query it. can remove devices cd-drives , other things. can't disconnect usb-passthrough-device. either : "invalid config" or "unknown error" (most due lib being interopt , not transporting information) my current code: using vmware.vim; var dongle = devs.singleordefault(i => i.deviceinfo.summary.contains("silicon")); if (dongle != null) { var usbdongle = (dongle virtualusb); usbdongle.connected = false; var spec = new virtualmachineconfigspec() { devicechange = new[] { new virtualdeviceconfigspec() { device = dongle, operation = virtualdeviceconfigspecoperation.remove, } } }; vm.recon

Google Analytics Multiple Custom Dimension -

i working on google analytics chart on site , in tracking code want 2 add 2 custom dimension (one user id). doing way, doing right ? ga('create', 'ua-xxxx', {'userid': spuserid}); ga('set', { 'dimension1': spuserid, 'dimension2': jobaidid }); ga('send', 'pageview'); yes, that's correct: ga('set', {'dimensionx': valuex, 'dimensiony': valuey, 'dimensionz': valuez}); ga('send','pageview'); you send them other hits too: ga('set', {'dimensionx': valuex, 'dimensiony': valuey, 'dimensionz': valuez}); ga('send','event', 'cat', 'action', 'label');

python - How to count everything in quotes as only one item -

i'm trying split following string: a = "2147486448, 'node[082, 101-107]', 8" right i'm using str(a).strip('[]').split(",") , output [2147486448, 'node[082,' '101-107]', 8] isn't want, expecting was[2147486448, 'node[082, 101-107]', 8] but can see in second item of list, contains ',', should second item 1 instead of split ',' i've read post [ how count occurrences of separator in string excluding in quotes still have no idea of should in case. , feel free delete post if guys think it's duplicate update: thanks @cyphase code works, when tried read line line txt file , each line: a = [] f = open(txt_file) row in f: a.append(ast.literal_eval(row)) a snippet of txt file : 423, 0, 0, 'default', 8, 8, 0, null, 1, 'sacimport', 2990, null, 286, 232, 0, 0, 1486, 576, -1, 98304, 'node581', 1, '476', 'batch', 4294901555, 6, 60, 1403

PHP built in functions complexity (isAnagramOfPalindrome function) -

i've been googling past 2 hours, , cannot find list of php built in functions time , space complexity. have isanagramofpalindrome problem solve following maximum allowed complexity: expected worst-case time complexity o(n) expected worst-case space complexity o(1) (not counting storage required input arguments). where n input string length. here simplest solution, don't know if within complexity limits. class solution { // function determine if input string can make palindrome rearranging static public function isanagramofpalindrome($s) { // here counting how many characters have odd number of occurrences $odds = count(array_filter(count_chars($s, 1), function($var) { return($var & 1); })); // if string length odd, palindrome have 1 character odd number occurrences // if string length even, characters should have number of occurrences return (int)($odds == (strlen($s) & 1)); } } ec

ios - How do I edit the HTML in a UIWebView? -

i have uiwebview loads html. how access html elements , change them? i want like: webview.gethtmlelement(id: main-title).value = "new title" if want edit in form, how can it: - (void)webviewdidfinishload:(uiwebview *)webview { nsstring *evaluate = [nsstring stringwithformat:@"document.form1.main-title.value='%@';", @"new title"]; [webview stringbyevaluatingjavascriptfromstring:evaluate]; } or if not in form, maybe (untested): - (void)webviewdidfinishload:(uiwebview *)webview { nsstring *evaluate = [nsstring stringwithformat:@"document.getelementbyid('main-title').value='%@';", @"new title"]; [webview stringbyevaluatingjavascriptfromstring:evaluate]; } note! assume editable field want change. otherwise talking parsing , concept works this: static bool firstload = yes; - (void)webviewdidfinishload:(uiwebview *)webview { if (firstload) { firstload = n

javascript - $(window).on("load") not triggered in postRender -

i have jquery code have trigger after page loaded, doing in postrender function call of view, postrender , window load event totally async, so, window load event might happen before in postrender adding listener load event, there replacement function in case, or missing something? thanks help you use flag keep track of window.load event in global scope , choose execution path in postrender() based on status of flag. // define in global scope var windowhasloaded = false; $(window).on('load', function(){ windowhasloaded = true; }); then in view.postrender() : // window has loaded, run if(windowhasloaded) { dostuff(); } // run on window load event else { $(window).on('load', dostuff); } var dostuff = function() { // stuff }

javascript - add array of polylines as distinct lines in googlemaps -

i'm working googlemaps api. i've looked answers q, found similar questions none seem work me. i want add array of polylines googlemap distinct lines distinct colors, not 1 continuous line. i'm pulling lat lng coordinates json file. array of polylines (themselves arrays of lat lng coords) variable in length. i can't figure out how run polyline.setmap run again until there no more sets of polylines left in array. here code in questions: paths = []; allstrms = []; $.getjson("json/basin/"+file+"", function(json) { // iterate through each year array in json (i = 0; < json.year.length; i++) { //only grab data 2013 if(json.year[i]["@attributes"].id == '2013') { //iterate through latlng array in each storm object (p=0; p < json.year[i].storm.latlng.length; p++) { //get each pair of lat / lng coordinates latlng array var path = new google.maps.latlng(parsefloat(json.year[i].storm.latlng[p].latitude), parsefloat(

c# - WPF Binding ICommand with ViewModel -

icommand: public class cmdaddedituser : icommand { public event eventhandler canexecutechanged; public vmaddedituser viewmodel { get; set;} public cmdaddedituser() { } public cmdaddedituser(vmaddedituser vm) { viewmodel = vm; } public bool canexecute(object parameter) { return true; } public void execute(object parameter) { this.viewmodel.simplemethod(); } } viewmodel: public class vmaddedituser { private employee _employee = new employee(); private cmdaddedituser command { get; set; } public vmaddedituser() { command = new cmdaddedituser(this); } public string txtfirstname { { return _employee.firstname; } set { _employee.firstname = value; } } public void simplemethod() { txtfirstname = "abc"; } } xaml: <window x:class="wpf.addedituserview" xmlns="http://schemas.microsoft.c

android - Modifying textviews reliant on threaded API calls? -

public view getview(int position, view convertview, viewgroup parent) { layoutinflater inflater = layoutinflater.from(getcontext()); view theview = inflater.inflate(r.layout.match_layout, parent, false); matchid = getitem(position); textview championname = (textview) theview.findviewbyid(r.id.championnametext); new thread( new runnable() { public void run() { selectedmatch = riotapi.getmatch(matchid); log.i(tag, string.valueof(selectedmatch)); // <-- returns matches } }).start(); championname.settext(string.valueof(selectedmatch.getduration())); // log.i(tag, string.valueof(selectedmatch)); <-- returns nulls return theview; } i've been running problem after problem trying make first app. understanding i'm not allowed api calls in main thread, tried using seperate thread. problem is, takes few seconds api return data, selectedmatch

angularjs - Whats the equivalent for ng-grid's "beforeSelectionChange" in ui-grid? -

in ng-grid , used use beforeselectionchange in following way: when user selects row, ajax call performed. while ajax call happenning set $scope.doingajaxcall = true , , prevent user changing selection, had in grid definition: beforeselectionchange: function () { return !($scope.doingajaxcall); }, which locks/freezes selection if ajax call happenning. now, in ui-grid (aka ng-grid 3), i don't know whats equivalent afterselectionchange . in section of documentation: http://ui-grid.info/docs/#/api/ui.grid.selection.api:publicapi see 2 events: rowselectionchanges rowselectionchangedbatch . these seem equivalent of old afterselectionchange and in section of documentation: http://ui-grid.info/docs/#/api/ui.grid.selection.service:uigridselectionservice see these 2 methods seem related need: raiseselectionevent(grid, changedrows, event) decideraiseselectionevent(grid, row, changedrows, event) but don't understand how use them important note: i

Converting JSON files to .csv -

i've found data downloading json file (i think! - i'm newb!). file contains data on 600 football players. here can find file in past, have downloaded json file , used code: import csv import json json_data = open("file.json") data = json.load(json_data) f = csv.writer(open("fix_hists.csv","wb+")) arr = [] in data: fh = data[i]["fixture_history"] array = fh["all"] j in array: try: j.insert(0,str(data[i]["first_name"])) except: j.insert(0,'error') try: j.insert(1,data[i]["web_name"]) except: j.insert(1,'error') try: f.writerow(j) except: f.writerow(['error','error']) json_data.close() sadly, when in command prompt, following error: traceback (most recent call last): file"fix_hist.py", line 12 (module) fh = data[i][