Posts

Showing posts from July, 2010

scala - How do I match types that don't have a specific typeclass instance? -

this question has answer here: using context bounds “negatively” ensure type class instance absent scope 1 answer i define behavior types don't have instance typeclass: // given trait sometypeclass[t] // when have implicit sometypeclass[t] def f[t: sometypeclass](x:t):unit = ??? // when don't have instance def f[t !: sometypeclass](x: t):unit = ??? we handle difference within typeclass need create instances support generic behavior. is there way negate type bound? way make function !: compile? (i in vanilla scala, without scalaz, shapeless, etc) is there way negate type bound? no! syntax [t: sometypeclass] shorthand (implicit val t: sometypeclass[t]) , , there no way "negate" that. overload method create ambiguity. but can "nest" type classes. trait existslowpri { implicit def no[a]: exists[a] =...

Simple Haskell program not behaving correct -

i'm new haskell , trying write simple program find maximal element , it's index intput. receive values compare 1 one. maximal element i'm holding in maxi variable, it's index - in maxidx . here's program: loop = let maxi = 0 let maxidx = 0 let idx = 0 let idxn = 0 replicatem 5 $ input_line <- getline let element = read input_line :: int if maxi < element let maxi = element let maxidx = idx hputstrln stderr "inner check" else hputstrln stderr "outer check" let idx = idxn + 1 let idxn = idx print maxidx loop even though know elements coming starting bigger smaller (5, 4, 3, 2, 1) program enters inner check time (it should happen first element!) , maxidx 0. doing wrong? in advance. anyway, let's have fun. loop = let maxi = 0 let maxidx = 0 let idx = 0 let idxn = 0 ...

Python Pandas - Moving Average with uneven period lengths -

Image
i'm trying figure out how deal time series data in pandas has uneven period lengths. first example i'm looking @ how calculate moving average last 15 days. here example of data (time utc) index date_time data 46701 1/06/2016 19:27 15.00 46702 1/06/2016 19:28 18.25 46703 1/06/2016 19:30 16.50 46704 1/06/2016 19:33 17.20 46705 1/06/2016 19:34 18.18 i'm not sure if should fill in data 1 minute increments, or if there smarter way... if has suggestions appreciated thanks - kc you can this. resample @ frequency want (or downsampling) you have pay attention here resampling strategy. has consistent meaning of data. here have arbitrary used bfill (back fill use next valid value) strategy more appropriate ffill (forward fill propagates last valid value). compute moving average. maybe have deal index note: syntax rolling has been introduced in pandas 0.18.0 . possible same thing in previous version pd.rolling_mean . # ...

html5 - How to check file MIME type with javascript before upload? -

Image
i have read this , this questions seems suggest file mime type checked using javascript on client side. now, understand real validation still has done on server side. want perform client side checking avoid unnecessary wastage of server resource. to test whether can done on client side, changed extension of jpeg test file .png , choose file upload. before sending file, query file object using javascript console: document.getelementsbytagname('input')[0].files[0]; this on chrome 28.0: file {webkitrelativepath: "", lastmodifieddate: tue oct 16 2012 10:00:00 gmt+0000 (utc), name: "test.png", type: "image/png", size: 500055…} it shows type image/png seems indicate checking done based on file extension instead of mime type. tried firefox 22.0 , gives me same result. according the w3c spec , mime sniffing should implemented. am right there no way check mime type javascript @ moment? or missing something? you can det...

javascript - codemod from ForInStatement to ForStatement -

Image
i have codemod want transform for (var key in foo){} into for (var keys = 0; key < foo; key++){} i managed far: return j(file.source) .find(j.forinstatement) .replacewith(p => { var prop = p.node.left.declarations[0].id; var v = [j.variabledeclarator(prop, null)]; var vardec = j.variabledeclaration('var', v); var binary = j.binaryexpression('<', prop, j.identifier('foo')); var ue = j.updateexpression('++', prop, false); var block = j.blockstatement([]); var forin = j.forstatement(vardec, binary, ue, block); return forin; }) .tosource(); and that brought me far : for (var key; key < foo; key++) {} i'm still bit lost creating things scratch... question: am doing correct? feels quite verbose, maybe way go. how finish? missing example foo.length ... ps: felix , if reading this, point me can send pull requests improve docs! happy ...

xml - VB.net Get text/string from html element -

i'm having major trouble trying bits of elements , returning strings. have few exmaples of trying strings , not failing hard. html phrasing difficult me appreciated. explantion of need : i need strinsg of different elements off site when entering ip http://www.ip-tracker.org/ i need pretty details labels or text boxes. or xml phrasing http://ip-api.com/xml/8.8.8.8 so here exmaple i've used far haven't got far it. exmaple 1 : dim client new webclient dim ip string dim city string dim region string private function getip() try dim page string = client.downloadstring("http://www.ip-tracker.org/locator/ip-lookup.php?ip=82.16.38.43/") ip = page.substring(page.indexof("ip address:") + 80) ip = ip.substring(0, city.indexof(" </td") + 30) textbox2.text = ("ip address: " + ip) catch ex exception city = "unable lookup" end try return 0 end function to ...

jquery - window.location.href not working -

my website http://www.collegeanswerz.com/ . i'm using rails. code searching colleges. want user able type in colleges name, click enter, , taken url, rather seeing search results (if user types in name properly. if not want show search results). i'm using "a" , "stackoverflow.com" placeholders while try work. i'm using window.location.href based on this: how redirect webpage in javascript/jquery? javascript $("#search_text").submit(function() { if ($("#search_field").val() == "a") { window.location.href = "http://stackoverflow.com"; alert('worked'); } }); layout file <%= form_tag("/search", :method => 'get', :id => 'search_text', :class => 'form_search') -%> <div id="search"> <%= search_field_tag :search, params[:search], :placeholder => 'enter college', :id => "search_f...

git - Different Commits - Error: The following untracked working tree files would be overwritten by merge -

i trying set production, testing , development environments site. came time of pushing first minor change production. however, when try it, gives following error: error: following untracked working tree files overwritten merge: changelog.txt copyright.txt blockquote install.mysql.txt install.pgsql.txt install.sqlite.txt install.txt license.txt maintainers.txt readme.txt upgrade.txt misc/arrow-asc.png misc/arrow-desc.png misc/configure.png misc/draggable.png the list of files goes on , omitted them brevity. my production , development .gitignore identical. namely, follows: # ignore configuration files may contain sensitive information. sites/*/settings*.php .htaccess # ignore paths contain user-generated content. sites/*/files sites/*/private <<<<<<< head ======= # compiled source # ################### *.com *.class ...

javascript - window.close and self.close do not close the window in Chrome -

the issue when invoke window.close() or self.close() doesn't close window. there seems belief in chrome can't close script window not script created. patently false regardless supposed still it, if requires pop alert confirm. these not happening. so have real, functional , proven method of closing window using javascript:window.close() or javascript:self.close() expected , happens fine in every browser not chrome based? suggestions appreciated , looking javascript specific solution, nothing jquery or third party implementation. update: while of has been suggested has serious limitations , usability issues, latest suggestion (specific tampermonkey) using // @grant window.close in script header trick on tabs can't handle close method. while not entirely ideal , doesn't generalized every case, solution in case. ordinary javascript cannot close windows willy-nilly. security feature, introduced while ago, stop various malicious exploits , annoy...

angular - Angular2: Stuggling to understand this strange behavior -

i have widgetcomponent use in angular2 app. app in fact 2 different apps within one: desktop version (boot-desktop) , mobile version (boot-mobile). widgetcomponent have used in desktop version, , working on mobile version , want use widgetcomponent in mobile version. however, error when attempt utilize widgetcomponent in mobile version: browser_adapter.ts:78error: uncaught (in promise): typeerror: cannot read property 'query' of null @ resolvepromise (zone.js:538) @ zone.js:515 @ zonedelegate.invoke (zone.js:323) @ object.ngzoneimpl.inner.inner.fork.oninvoke (ng_zone_impl.ts:67) @ zonedelegate.invoke (zone.js:322) @ zone.run (zone.js:216) @ zone.js:571 @ zonedelegate.invoketask (zone.js:356) @ object.ngzoneimpl.inner.inner.fork.oninvoketask (ng_zone_impl.ts:56) @ zonedelegate.invoketask (zone.js:355) this error not occur in desktop version of app. so tried experiment. cloned widgetcomponent, ie cr...

javascript - How to save attribute which is being overridden as nil? -

Image
the ranking saves if user saved under note first in chronological order. challenges/show <% @challenge.dates_challenged.first(@challenge.days_challenged + @challenge.missed_days).each_with_index |date, i| %> <% if @notes.any? { |note| note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") } %> <% @notes.each |note| %> <% if note.notes_text.present? %> <% if note.notes_date.strftime("%m/%d/%y") == date.strftime("%m/%d/%y") %> <div class="notes-notes-background"> <% if note.ranking == 1 %> <%= image_tag '1.png', class: 'note-emoticon' %> <% elsif note.ranking == 2 %> <%= image_tag '2.png', class: 'note-emoticon' %> <% elsif note.ranking == 3 %> <%= image_tag '3.png', class: 'note-emoticon' %> ...

ios - NSFetchedResultsController notifies its Delegate of delete changes when a managed object is modified, and never notifies for Insert or Update -

i have uitableviewcontroller , delegate nsfetchedresultscontroller . nsfetchedresultscontrollerdelegate functions set per "typical use" in apple's documentation , table view controller fetched result controller's delegate property. i have view controllers presented on top of table view managed objects can modified. these modifications done on same managed object context. there 1 managed object context constructed in application, , accessed globally. (i have put print statements in object context construction sure not accidentally re-constructing elsewhere.) when modify 1 of managed objects, delegate function controller:didchangeobject called, nsfetchedresultschangetype always .delete . when create managed object, delegate function not fire @ all. however, when manually call call performfetch() , tableview.reloaddata() , cells restored correct state: removed row comes back, not-inserted rows created. the result deleting object works expected (the cel...

java - Which of the two JDBC query batching approaches is faster? -

i trying run update statements in multiple batches using rownum on table has millions of records. the first approach batch queries , running executebatch() method below, for (i = num; < limit; += num) { string query = "update table set somecolumn ='t' rownum<=" + i; preparedstatement = dbconnection.preparestatement(query); preparedstatement.addbatch(); } preparedstatement.executebatch(); dbconnection.commit(); second approach run 1 batch update statement , committing after every batch shown below, string query = "update table set somecolumn ='t' rownum<=?"; preparedstatement = dbconnection.preparestatement(query); int count = 1; while (count > 0) { preparedstatement.setint(1, num); count = preparedstatement.executeupdate(); dbconnection.commit(); } i thought second approach cleaner since commits after every batch, first approach taking lesser time second approach. can explain me why so? or if there...

php - Adding outputted table row to another table using codeigniter -

outputted row table ,am trying add of contents table using form inside outputted row not inserted database. not getting error. here view <?php foreach ($h->result() $row) {?> <div class="row invoice-info"> <div class="col-sm-1 invoice-col"> </div> <div class="col-sm-3 invoice-col"> <img src="<?php echo base_url()?>/res/images/goods/1.png"> </div> <div class="col-sm-4 invoice-col"> <address> description: <?php echo $row->description;?><br> location address: <?php echo $row->l_area;?><br> destination address: <?php echo $row->d_area;?><br> date: <?php echo $row->dom;?><br> time: <?php echo $row->tom;?> </address> </div> <d...

vba - Need a loop to enter formulas/data in excel table columns -

i in need of nested loop add formulas 4 particular columns in table ("table1"). loop mimic previous loop regarding naming of these same 4 additional columns ("colnames"). the bottom portion of code works fine, know how work loop. sub attstatpivinserttablecolumns_2() dim lst listobject dim currentsht worksheet dim colnames variant, formnames variant '<~~ note: varient, go when working arrays dim olc listcolumn, oldata variant dim integer, d integer set currentsht = activeworkbook.sheets("sheet1") set lst = activesheet.listobjects("table1") colnames = array("aht", "target aht", "transfers", "target transfers") = 0 ubound(colnames) set olc = lst.listcolumns.add olc.name = colnames(i) next ***below code needs looped*** 'lst.listcolumns("target aht").databodyrange.formular1c1 = "=350" 'lst.listcolumns...

jQuery getScript not running fail method on connection refused -

i'm trying account script not loading might blocked china's firewall. edited hosts file direct google.com , www.google.com 127.0.0.1. when run following $.getscript('https://www.google.com/recaptcha/api.js').done(function(){ console.log('done'); }).fail(function(){ console.log('fail'); }); i done when not blocked don't fail when blocked. see connection refused in console when trying load script. am missing in documentation? how can test or run fallback if script fails load. why fail not firing? i've tried manner of stuff work can't figure out. i tried writing long hand no avail well. $.ajax({ url: "https://www.google.com/recaptcha/api.js", datatype: 'script', error: function(){ console.log('test'); }, cache: false, complete: function(){ console.log('complete'); }, success: function(){ console.log('success'); } }); ...

html - Expand elements to width of div -

i have 27 hyperlink elements in container div. hyperlinks alphabet letters this: a | b | c | d | e | f | g | h | | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z | all the div width of page. right now, have class on anchor tags sets left , right padding 3px , have spacing in between pipes. problem letters float left , left bunch of white space right of letters. how achieve spacing letters (i.e. padding), letters expand width of container div? thinking padding dynamic in such way set based on width of container div. <style type="text/css"> .container { width:100%; } .alphabetlinks { padding: 0px 3px; } </style> <html> <div class="container"> <a class="alphabetlinks">a</a> | <a class="alphabetlinks">b</a> | </html> update: solution must support ie9 , above. option 1 - modern browsers you can use flexbox that .container { display: flex ...

android - Passing Strings from listview that has not been populated -

i pass string tag_question_content = "content"; string tag_question_subject = "subject"; , string tag_question_chosenanswer = "chosenanswer"; when click on item want, string displays in next activity string tag_question_subject = "subject"; reason because string populating listview. not want other 2 strings populated in listview, want pass them next activity can displayed there. can show me way pass these 2 other strings without populating them. public class listview extends listactivity { arraylist<hashmap<string, string>> questionlist; final string tag_results = "results"; final string tag_question_subject = "subject"; final string tag_question_numanswers = "numanswers"; final string tag_question = "question"; final string tag_question_content = "content"; final string tag_question_chosenanswer = "chosenanswer"; ...

javascript - express.session.MemoryStore not returning session? -

it easy setting sessions , using them in php. website need deal websockets. facing problem set sessions in node.js. can push data without using sessions , work fine when more 1 tab opened new socket.id created , opened tabs wont function properly. have been working on sessions , had problem accessing sessionstore, logging session not grabbed. have tried session.load no luck how session object , use in way opening other tabs wouldnt effect functionality , push data server client on tabs? var express=require('express'); var http = require('http'); var io = require('socket.io'); var cookie = require("cookie"); var connect = require("connect"), memorystore = express.session.memorystore, sessionstore = new memorystore(); var app = express(); app.configure(function () { app.use(express.cookieparser()); app.use(express.session({store: sessionstore , secret: 'secret' , key: 'express.sid'})); app.u...

iphone - Mask specific subViews of UIView? -

i working on project. have uiview has several subviews. need know how mask subviews parent view, or mask 1 particular view. there way add refinement checks masktobounds property? direction or suggestion appreciated. what mean masking? if want hide particular view, create standalone additional view , change frame whichever view want hide. bring standalone view front of view want hide, add using insersubview :abovesubview , variants of it. more on it, see this . this requires able access them using specific outlets, or through tags know of subviews array, allow conditional masking. if want hide instead of "masking" other content, obvious choices are: set it's hidden property yes . set it's alpha property 0.0 (or fade out effect)

multithreading - Java: Two threads communicating via streams is company, three's a crowd -

in code segment, create pipe , attach scanner on 1 end , printstream on other in order communicate between several consumer , producer threads. create , start 3 threads: the first thread consumer thread. checks scanner see if line of text available consume, consumes it, prints stdout , sleeps few milliseconds , repeats. if there's nothing consume, prints message that, sleeps , repeats. the second thread in code segment nothing. more on below. 2.5 there's 3 second delay before 3rd thread launches. the third thread producer , produces text messages first thread consume. produces message, sleeps public static void main(string[] args) throws ioexception { pipedinputstream pis = new pipedinputstream(); pipedoutputstream pos = new pipedoutputstream(pis); scanner scan = new scanner(pis); printstream ps = new printstream(pos); new thread() { public void run() { int x = 0; while (true) {...

postgresql - How to exit PSQL CREATE FUNCTION screens -

i'm new writing functions in postgres.. i don't want exit psql entirely, (i know ctrl+d that,) seem stuck in create function screen. mattswheels=# create or replace function 99_cents(money) mattswheels-# returns money mattswheels-# language plpgsql mattswheels-# leakproof mattswheels-# $function$ mattswheels$# declare mattswheels$# new_price money; mattswheels$# size int; mattswheels$# begin mattswheels$# size := char_length(money); mattswheels$# return size; mattswheels$# end; mattswheels$# mattswheels$# \q mattswheels$# halp mattswheels$# ; mattswheels$# ; mattswheels$# ; mattswheels$# ; mattswheels$# mattswheels$# ; mattswheels$# \? try ctrl+c. discards last query not terminated quotes.

Rails 4 - how to reference a javascript source in vendor file -

i have discovered need amend gmaps rails setup inserting javascript files directly in app. rails 4 - gmaps4rails - map won't render i have cloned both infobox , markerclusterer repos , stuck in trying reference relevant files in app. i have folders of files came clone in vendor file. i understand javascript files need use are: infobox.js , markerclusterer.js these files located in: vendor/js-marker-clusterer/src/makerclusterer.js vendor/v3-utility-library/src/infobox.js i want use them in place of code in view: <script src="//maps.google.com/maps/api/js?v=3.18&sensor=false&client=&key=&libraries=geometry&language=&hl=&region="></script> <script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js"></script> <script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/src/infobox_packed.js' typ...

Arduino joining two int's -

hello have 2 variables timer1hh = 9 timer1mm = 7 i convert them strings, join them , "97" using code below: string string1= string(timer1hh); string string2= string(timer1mm); string string3; string3=string1+string2; serial.println(string3); thats fine want add leading 0 if below 10 like. "0907" so want able "if" between "0907" , "2034" type of thing. im totally blagged sprintf using "%02" , not working me. any great. pete see sketch: void setup() { int timer1hh = 9, timer1mm = 7; serial.begin(9600); //string string1= string(timer1hh); //string string2= string(timer1mm); //string string3; char out1[5]; sprintf(out1,"%.2d%.2d", timer1hh,timer1mm ); string string3(out1); //string3=string1+string2; serial.println(string3); } void loop() {} serial output: 0907

swift - Does converting UInt8(or similar types) to Int counter the purpose of UInt8? -

i'm storing many of integers in program uint8 , having 0 - 255 range of values. later on summing many of them result able stored int . conversion have before add values uint8 int defeat purpose of me using smaller datatype begin with? feel faster use int , suffer larger memory footprint. why go uint8 when have face many conversions reducing of speed , increasing memory well. there i'm missing, or should smaller datatypes used other small datatypes? you talking few bytes per variable when storing uint8 instead of int . these data types conceived on in history of computing, when memory measured in low kbs. apple watch has 512mb. here's apple says in swift book : unless need work specific size of integer, use int integer values in code. aids code consistency , interoperability. on 32-bit platforms, int can store value between -2,147,483,648 , 2,147,483,647, , large enough many integer ranges. i use uint8 , uint16 , uint32 in code deals c. , yes,...

angularjs - Angular dropdown not being selected -

i have dropdown in angular not selected. added value ng-model particular address of json_array selected however, not being set in dropdown. here object. 0: { id:1 locationid:1 name:"john doe" } 1 { id: 2 name: "jane doe"} in managed make dropdown using <select class="form-control" ng-model="approver" ng-options="approver.name approver.name approver in approverlist"> </select> and in angular controller $scope.approver = $scope.approverlist[1]; in jane doe not being selected. what cause of this. thanks! your html not correct, try this. <select class="form-control" ng-model="approver" ng-options="approver approver.name approver in approverlist track approver.id"> </select> read here angular team more information.

android - How to use Firebase List adapter -

i'm trying follow tutorial: https://www.youtube.com/watch?v=2j6spwavp0m but implementing on complex app didn't work tried scratch.. i created simple mainactivity: public class mainactivity extends appcompatactivity{ firebase mref; com.firebase.ui.firebaselistadapter<string> myadapter; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mref = new firebase("https://<myurl>.."); myadapter = new firebaselistadapter<string>(this,string.class,android.r.layout.simple_list_item_1,mref) { @override protected void populateview(view view, string s, int i) { textview text = (textview)view.findviewbyid(android.r.id.text1); text.settext(s); } }; button addbtn = (button) findviewbyid(r.id.add_button); addbtn.setonclicklistene...

Realm.io and Facebook Android SDK problems -

i have android app uses realm database. right when add facebook sdk, app not work. error line: realmconfiguration config = new realmconfiguration.builder(this).build(); anyone same problem or solutions? regards, noel

database - MySQL v5.7.4 - Is there no longer a way to remove duplicates with "unique index"? -

so apparently after mysql v5.7.4, keyword ignore no longer supported, nukes useful duplicate-removing query: alter ignore table labs add unique index nodupes (ruid, test_sname, test_value, units, ref_range, entry_date); everywhere i've looked notes discontinued support of ignore , doesn't suggest replacement. is there still simple way utilize power of unique index remove duplicates without using ignore after mysql v5.7.4? many people consider thing creating index not delete records underlying table. 1 method use temporary table, truncate, , insert: create temporary table tokeep select distinct ruid, test_sname, test_value, units, ref_range, entry_date labs; truncate table labs; insert labs(ruid, test_sname, test_value, units, ref_range, entry_date) select ruid, test_sname, test_value, units, ref_range, entry_date tokeep; note: version assumes these columns in table. if there other columns, similar logic work.

Laravel restful api error 500(store and destroy) -

i new restful api,and met problem,problem :when request destroy delete method , store post method,both return 500 error.but use method request index , show,both ok.what problem? here codes , request: delete http://***.com/restfulprac/public/customers/10000001 get http://***.com/restfulprac/public/customers/10000001 post http://***.com/restfulprac/public/customers class customerscontroller extends controller { public function index(){ $customersinfo = customers::all(); return $customersinfo; } public function show($cust_id){ $customer = customers::where('cust_id',$cust_id)->first(); return $customer; } public function store() { echo "store"; } public function destroy() { return "success"; } } route::resource('customers','customerscontroller'); the apache access.log : "delete /restfulprac/public/customers/1000000001 http/1.0" 500 20246 ...

java - How to remove static variable but allow a variable to still be globally called? -

i using libgdx scene2d , tiled create 2d game. have class reads object layers , loads them game(which still deciding whether make singleton). problem in class gets updated, since split update , render 2 classes, have public static stage stage , want make not static. the problem thaat have mob class, includes players , monsters, , need stage class in order of objects in game , check collisions. in mob class don't think/want add stage constructor parameter because it's abstract class , have put in stage player class every time called. if additional information needed, because know guys aren't wizards, put asap. have 3 classes working here, tiledmaphelper class, worldcontroller class, , mob class. below class converts created level on tiled codeable objects game. static arraylists changed group class implemented stage class. stage class holds of objects in game. public class tiledmaphelper { public static final int tile_width = 512; public static f...