Posts

Showing posts from April, 2013

python - Count the number of lists that starts with the same item in a list -

so have list like: result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]] i want function returns count of number of lists starts (index[0]) variable "n" . so, if n = '1' in case 2, if n = '2' i 1 . edit: i've tried few things this, can't work. def count(list,n): result = [] value = 0 in list: if str(i[0]) == n: value = value + 1 sum.append[value] return len(sum) print count(result,1) result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]] lst2 = [item[0] item in result] lst2.count("1") result = [["1", "1", "a", 8.2],["1", "2", "c", 6.2],["2", "1", "a", 8.2]] def count(mylist,n): lst2 =

google chrome - HTML5 Notification Chrome45 -

html notification working in firefox41, not work in chrome45. function spawnnotification(thetitle,thebody,theicon) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle,options); } document.getelementbyid('notify').addeventlistener('click', function() { spawnnotification('title','text','aike.jpg'); });

c++ - Printing out value of variable of unknown type? -

i'm trying write simple function template in c++ in printing out value of variable of unknown type. problem can't figure out how since variable either pointer or primitive type. primitive type, can print value out; pointers require de-referencing. the following code gives me error: #include <iostream> #include <type_traits> using namespace std; template<typename t> void foo(t somevar) { if(std::is_fundamental<t>::value) { cout << "it's primitive! \n" << somevar << endl; } else { cout << "it's pointer! \n" << *somevar << endl; } } int main(int argc, char **argv) { int x = 5; foo(x); int *y = new int(); *y = 5; foo(y); delete y; return 0; } the error when compile is: test.cc: in function 'void foo(t) [with t = int]': test.cc:19:8: instantiated here test.cc:13:5: error: invalid type argument of unary '*' (have 'int') it&#

javascript - message passing from web page to contentscript.js in chrome extension -

this question has answer here: chrome extension - passing object page context script 2 answers want send status value contentscript.js in chrome extension page in browser, doing adding value newly created event passing extension, but receiving value 'undefined'. code follows. page.html <html> <head></head> <body> <script> var go = function() { var sam=1; var event = document.createevent('event',{"details": 1}); event.foo=sam; event.initevent('hello'); document.dispatchevent(event); } </script> <a href="javascript:go();">click me</a> </body> </html> trying access value of 'foo' , 'status'(either of ), getting both values 'undefined'. contentscript.js document.addeventlistener("hel

python - How show interactive charts in a GTK window? -

i need charts , it'll better if interactive. want that . packages, , bokeh seems interesting. but once i'll have beautiful chart... how insert in gtk window? you can use webkitgtk embed web pages.

makefile - How to filter out a file from wildcard match when an environment is not set -

i using gnu make. i have version this: mylist := $(filter-out $(if $(filter 1,$(exclude_file1)), file1.c),$(wildcard *.c)) it works well: when filter out "file1.c", set environment variable, exclude_file1. now want opposite: when environment variable not set, want exclude file1.c. could point me should change? mylist := $(filter-out $(if $(filter undefined,$(origin exclude_file1)),,file1.c),$(wildcard *.c)) or mylist := $(filter-out $(if $(filter-out undefined,$(origin exclude_file1)),file1.c),$(wildcard *.c)) or mylist := $(filter-out $(if ${exclude_file1},,file1.c),$(wildcard *.c)) etc. one advantage of first 2 formulations don't generate message when useful --warn-undefined-variables in effect.

java - can I use WeakHashMap instead of HashMap -

i going through weakhashmap in java. , have understood weakhashmap hashmap except key references weakreference . means key references eligible gc , , when garbaged, entry removed map. not available in hashmap . please correct me if wrong. i have 1 question on here. now in future if requirement have use map putting key , value,can go forward weakhashmap ? or need consider scenario weakhashmap wont fit hashmap fit? you need consider context decide whether correct / safe use weakhashmap. here's example weakhashmap not work (pseudo-code) map<name, details> map = ... ever: name = name user if lookup: details = map.get(name) display details else if create: details = details user map.add(name, details) with weakhashmap, there risk entries drop out of table, , user's lookups fail. hashmap, there no risk. there issue weakreference , built on more expensive ordinary references. use more space , time. mo

Min and Max are inversed in MySQL -

Image
i don't know why have when try min , max receive wrong response! here content date : and here mysql request : select min(`value`),max(`value`) weather_data `date`="2015-10-22" , `type`="temperature" but response of mysql request : do have idea of why have response? it looks value represented string. so, happily, min() , max() working correctly. if values can converted on system, can use: select min(`value` + 0), max(`value` + 0) weather_data `date` = '2015-10-22' , `type` = 'temperature'; the + silent conversion. if min , max both return 0, commas not recognized, replace them periods: select min(replace(`value`, ',', '.') + 0), max(replace(`value`, ',', '.') + 0) weather_data `date` = '2015-10-22' , `type` = 'temperature';

c++ - What is meaning of $g++ -std=c++11 main.cpp -o demo 2>&1 -

i want know meaning of following statement in unix - $g++ -std=c++11 main.cpp -o demo 2>&1 call gnu c++ compiler: g++ set language standard c++11: -std=c++11 the input source file main.cpp : main.cpp set output ( -o ) filename demo : -o demo redirect (the > character) standard error (represented 2 ) standard output (represented 1 ): 2>&1 both standard error , standard output linked console screen default.

amazon web services - How do I add inbound security rules for EC2 using DNS? -

i using appery.io, , need whitelist it's app server shown in tutorial using database hosted on amazon rds. how do using it's dns? i.e. aex1.appery.io aex2.appery.io i know can using it's ip address. however, use it's dns protect against ip address changes. from know , trying out on aws console , vpc documentation: http://docs.aws.amazon.com/amazonvpc/latest/userguide/vpc_securitygroups.html you can specify ip. only other way can think of is: place service in same vpc db. make periodically check changes in ip of url pasted. if changes, should update rules accordingly. allow access aws api, need give instance running on required permissions. read instance profiles. need create required role using iam , assign corresponding instance profile instance when launching instance. code should run on instance , have required permission based on role created. you can run program outside aws well. give access access_key , secretkey, region , set r

http live streaming - What does this error message "Received discontinuity error" mean? From Apple's mediastreamvalidator -

using apple's mediastreamvalidator validate m3u8 file, got error message: "received discontinuity error", didn't find explanation error message in https://developer.apple.com/library/ios/technotes/tn2235/_index.html does know error mean, , whether error cause issues? my mediastreamvalidator's version is: beta version 1.1(150608) below mediastreamvalidator's result: -------------------------------------------------------------------------------- test_1444446455_hls_64944_116-10.m3u8 -------------------------------------------------------------------------------- playlist syntax: ok processed 15 out of 15 segments: test_1444446455_hls_64944_116-10_00003.ts: error: (-12976) received discontinuity error --> track id: 258 test_1444446455_hls_64944_116-10_00007.ts: error: (-12976) received discontinuity error --> track id: 258 test_1444446455_hls_64944_116-10_00010.ts: error: (-12976) received discontinuity error

wordpress plugin - H5P timeline alignment -

i have running website has h5p timeline works in chrome in firefox outside canvas , off side. website here: http://www.tunapanda.org if scroll down little bit see timeline developed in h5p. timeline should show under heading "our history". in chrome, in firefox appears right of heading, large part outside window. any appreciated! i can't find content, seems have removed page. if you're still looking solve problem suggest updating h5p timeline or grabbing directly github getting wrapper , external timelinejs library . if still experience problems after suggest trying isolate problem , put code snippet , link jsfiddle or off-prod site can check out further.

yocto - Building a bitbake component locally -

i writing component goes yocto build, during development don't want build entire image. want checkout component(in own git repo), build using cross-compiler used building entire tree, , test before checking in(devtest) , building entire filesystem system test. have not found way that. if understand question correctly, want build sdk? run bitbake - c populate_sdk <image-name> that'll give nice sdk in tarball. execute tarball install on desired location. in shell you're developing application, source environment-.... file in installed location. configured crosscompile, long you're using eg cc instead of directly calling gcc.

assembly - Memory-Mapped Graphics Output -

i'm exploring drawing pixels , lines, using memory-mapped graphics. i'm using tasm in textpad, in windows. when click run whole screen turns blue , that's it, no pixels drawn. .model small .stack .data savemode db ? xval dw ? yval dw ? .code main proc mov ax, @data mov ds, ax call setvideomode call setscreenbackground call draw_some_pixels call restorevideomode mov ax, 4c00h int 21h main endp setscreenbackground proc mov dx, 3c8h mov al, 0 out dx, al mov dx, 3c9h mov al, 0 out dx, al mov al, 0 out dx, al mov al, 35 out dx, al ret setscreenbackground endp setvideomode proc mov ah, 0fh int 10h mov savemode, al mov ah, 0 mov al, 13h int 10h push 0a00h pop es ret setvideomode endp restorevideomode proc mov ah, 10h int 16h mov ah, 0 mov al, savemode int 10h ret restorevideomode endp draw_some_pixels proc mov dx, 3c8h mov al, 1 out dx,

python - why buildin login_required decorator not check user.is_active -

why django buildin login_required decorator not check is_active flag ? i have use decorator or auth type secure issue? my solution override decorator: from django.contrib.auth.decorators import login_required login def login_required(fn): @login def wrapper(*args, **kwargs): return fn(*args, **kwargs) if args[0].user.is_active else httpresponse() return wrapper

javascript - Floating icon over a link does not receive mouse click event -

i want display icon floating on right side of link when mouse on link. idea able click on icon display dialog. works long no link text under icon. if text long icon on text link executed. icon click handler never called. what can give icon priority on link? problem because icon floating? +------------------------------------------------------+ | link |icon| +------------------------------------------------------+ the html looks this: <div class="group-content ui-sortable"> <a title="gmail|http://mail.google.com/mail" class="link show-option " href="http://mail.google.com/mail" target="google"> <span title="link.opensettings" class="ui-icon ui-icon-gear link-settings" style="display: none; z-index: 9999;"></span> <span class="ui-icon link-icon ui-icon-link ui-sortable-handle"></

multithreading - Run two functions simultaneously without using pthread or other similar libraries -

i want run 2 functions simultaneously in c without using pthread or other libraries. delays in function shouldn't affect execution of other. void func1(){ /*do something*/ } void func2(){ /*do something*/ } how that? can provide algo. there no way run functions simultaneously without using multiple threads. can simulate concurrent execution coroutines . if there no platform restrictions better use multithreading. simple use pthreads or openmp if functions independent , there no data races.

c++ - Is the algorithm behind std::seed_seq defined? -

Image
does standard require output of seed_seq same different implementations of stl? in other words, following guaranteed produce same output on different standard compliant platforms, or not? std::seed_seq sseq = { 1701, 1729, 1791 }; std::array<unsigned int, 5> seq; sseq.generate(seq.begin(), seq.end()); (unsigned x : seq) std::cout << x << " " << std::endl; yes. algorithm defined in 23.54.7.1 [rand.util.seedseq] posting image loses formatting text

javascript - Access variable in Google Maps Events addlistener -

for(var in coordenadas){ google.maps.event.addlistener(marker[i], 'click', togglebounce); } togglebonce function: function togglebounce() { if (this.getanimation() != null) { this.setanimation(null); var = "i want access of variable i" } else { this.setanimation(google.maps.animation.bounce); } } in function togglebounce() how can access of variable ? variable passed in ...addlistener(marker[i]... the simplest solution add property of marker when create (just careful naming doesn't conflict existing property of google.maps.marker ). // or here (since didn't provide code creates markers) for(var in coordenadas){ marker[i]._index = i; google.maps.event.addlistener(marker[i], 'click', togglebounce); } function togglebounce() { if (this.getanimation() != null) { this.setanimation(null); var = this._index; } else { this.setanimation(google.maps.animation.boun

android - How to open phone default SMS inbox using cordova? -

i have created application in phonegap, need open default sms inbox on click on inbox icon showing counter unread sms. need open phone default inbox on click on notification icon. have tried many code , found can opencomposer , sent box not inbox. one solution open phone sms inbox : intent intent = new intent(intent.action_main); intent.addcategory(intent.category_launcher); intent.setclassname("com.android.mms", "com.android.mms.ui.conversationlist"); working me.

osx - Nginx server for static content -

what minimum needed start nginx server serve static content (js etc)? i've got: http { server { listen 80; location / { root /users/matt/dev; } } } events { worker_connections 1024; } but get: forbidden you don't have permission access / on server. i've run sudo nginx -s reload with config can access individual files. can example.com/example.js (try , can see works). with example.com want show content of root directory ( /users/matt/dev ) disabled. enable use autoindex : location / { root /users/matt/dev; autoindex on; } see more information here : the ngx_http_autoindex_module module processes requests ending slash character (‘/’) , produces directory listing.

html - I want to know how to apply css on datalist items. I want to change height and font size -

i want know 1 thing have apply datalist in form. want increase items font-size , want css on padding. <!doctype html> <html> <style> #banner .seach-main-con .text-box{width:100%; height:45px; border-radius:5px; margin:3px 0; background-color:#fff; font-size:15px;} #banner .seach-main-con option{padding:5px; font-size:15px;} #banner .seach-main-con .search-btn{width:100%; height:50px; border-radius:5px; margin:15px 0; background-color:#d83318; color:#fff; font-size:20px; border:0;} #banner .seach-main-con .dropdown-text{width:100%; height:45px; border-radius:5px; margin:3px 0; background-color:#fff; font-size:15px;} #banner .seach-main-con datalist{padding:5px; font-size:15px;} #banner .seach-main-con .datalist-option{width:100%; padding:5px; font-size:15px; background-color:#fff;} </style> <body> <form> <h3>keyword search form here</h3> <div class="height"></div> <input list="browsers" name="

php - How I get next auto-increment ID in mysql table? -

i need next auto-increment id mysql product table. this how tried it: select `auto_increment` information_schema.tables table_name = 'products'; when query running, can output this. +----------------+ | auto_increment | +----------------+ | 10 | | 1 | | 14 | +----------------+ 3 rows in set (0.02 sec) can tell me why shows 3 values. (3 rows) note: product table still empty. mysql> select * products; empty set (0.00 sec) run query show table status 'products' using php $result = mysql_query(" show table status 'products' "); $data = mysql_fetch_assoc($result); $next_increment = $data['auto_increment']; using mysqli $db = new mysqli('your_host', 'db_username', 'db_password', 'database'); if($db->connect_errno > 0){ die('unable connect database [' . $db->connect_error . ']'); } $sql = <<

java - Method using recursion causing code to fail at run time, involves global variable -

this question poorly worded, how make code run desired without getting hundred error messages @ run time when use recursion? faulty program public class collatz { public static int count; public static int pluscount() { return count++; } public static void collatz (int n) { if (n < count) { system.out.print(n + ""); } if (n == 1) return; if (n % 2 == 0) { pluscount(); collatz(n / 2); } else { pluscount(); collatz(3*n + 1); } } public static void main(string[] args) { int n = integer.parseint(args[0]); int[] array = new int [n+1]; (int = 0; <= n; i++) { count = 0; collatz(i); array [i] = count; } int max = stdstats.max(array); system.out.println(max); } } if change collatz() method public static void collatz (int n) { count ++; stdout.print(n + ""); if (n == 1 || n == 0) return; if (n % 2 == 0) collatz(n / 2);

reporting services - Divide by zero SSRS -

i need in adding logic following code handle divide 0 =iif(fields!coverage.value = 0, sum(fields!calculatedtotalincidents.value) / (reportitems!calculatedunitssold1.value), sum(fields!calculatedtotalincidents.value) / sum(fields!calculatedunitssold.value)) try this: =iif(fields!coverage.value = 0, sum(fields!calculatedtotalincidents.value)/ iif((reportitems!calculatedunitssold1.value)<>0, (reportitems!calculatedunitssold1.value),1), sum(fields!calculatedtotalincidents.value) / iif(sum(fields!calculatedunitssold.value)<>0, sum(fields!calculatedunitssold.value),1))

c# - "Collapse" and sum data table -

i have pivoted data table columns locations , there around 100. data little strange , i'm looking easy way sum (or collapse data). date, location 1, location 2, location 3 1/1/2001, 6, 0, 0 2/1/2001, 10, 0, 0 1/1/2001, 0, 5, 0 2/1/2001, 0, 4, 0 1/1/2001, 0, 0, 8 2/1/2001, 0, 0, 2 so can see there 0 fillers if sum i'd unique list of dates , "collapsed" result has no 0 fillers. again, have 100 columns , can't hardcoded need way sum these columns dynamically. there trick this? maybe in linq? i use combination of loops , linq: datatable pivotedtable = table.clone(); // same columns, empty var pivotcolumns = pivotedtable.columns.cast<datacolumn>().skip(1).tolist(); var dategroups = table.asenumerable() .groupby(r => r.field<datetime>("date").date); foreach(var date in dategroups) { datarow row = pivotedtable.rows.add(); // added table row.setfield("date", date.key); foreach(datacolumn c in pivotco

Connection To The Database Failed on install dotnetnuke -

i try install dotnetnuke 7. created user access dnn database , in properties of sql server set server authentication sqlserver , windows authentication .but when browse website show message :connection database failed try connecting database using sql server management studio using same credentials specify in dnn. might identify doing wrong. you'll want verify sql server accepts connections web server, assuming not on same machine.

MySQL - Call Multiple Procedures from Within a Procedure -

Image
i want call multiple procedures within procedure. in following sql, create 3 procedures. upd_r_money , upd_r_fuel both work expected when called individually command line. when call upd_all, first call within upd_all run; second call upd_r_money doesn't run. i can't figure out why happens - maybe in upd_r_fuel procedure causes upd_all procedure end early? newby writing procedures, , sql in general. there question here problem, answer i'm doing, , answer's link down. drop procedure upd_r_money; delimiter // create procedure upd_r_money(row_id int) begin declare money_rate int default 1; declare period int default 0; set period = (select timestampdiff(second, (select lastaccessed gamerows id = row_id), now())); update gamerows set money = money + period * money_rate, lastaccessed = now() id = row_id; end; // delimiter ; drop procedure upd_r_fuel; delimiter // create procedure upd_r_fuel(row_id int) fuel: begin declare fuel_rate int default 1; declare period int

javascript - How to concatenate/change the error message if the input is not a valid date in js? -

i tried 2 days still nothing. maybe can highly skilled in javascript loops. i asked question before , change code still no luck in showing expected data. , still struggling this. i have code: $(function(){ var len = $('#groupcontainer > div').length; var data = []; for(var i=0; < len; i++){ var number = $('#number_' + [i + 1]); var date = $('#date_' + [i + 1]); var count = + 1; var message =""; var = number.map(function(){ return this.value; }); var b = date.map(function(){ return this.value; }); var newobj = {number: a[0], date: b[0]} data.push(newobj); } var message = ""; for(var c = 0; c < data.length; c++) { haveerroringroup = false; for(var d in data[c]) { if(data[c].hasownproperty(d)) { if(data[c][d] == "") { if(!haveerroringroup){ haveerroringroup=

if statement - How can php not execute neither 'then' nor 'else' clauses of 'if'? -

following this tutorial (which adapted postgresql), have problem in register.inc.php : if (empty($error_msg)) { // create random salt $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true)); // create salted password $pwd = hash('sha512', $pwd.$random_salt); // insert new user database $q = "insert usr (username,email,pwd,salt) values ($1,$2,$3,$4);"; $res = pg_query_params($conn,$q,[$username,$email,$pwd,$random_salt]); if ($res === false) { header("location: ../html/coisas/error.php?err=registration failure: insert"); } else { header('location: ./register_success.php?msg=1'.$random_salt); } header('location: ./register_success.php?msg=2'.$random_salt); } the header sent 3rd 1 (?msg=2...). if comment out, there's no header sent. how can it won't enter in clause, nor in else clause? data not being stored in database, i'm getting "s

Jquery wait until all animation finish before starting new one -

i have menu slidedown/slideup animations attached hover event. if hover on next menu position, while previous still animated slidedown, want wait slidedown finish , launch slideup current position. i tried use promise object, not work @ all. $('.menu-2>ul>li').each(function(){ $(this).hover( function(){ var choice = $('ul', this); ('.menu-2>ul>li>ul').promise().done(function( ) { choice.slidedown(); }); }, function(){ $('ul', this).slideup(200); } ); }); you can add callback after slidedown finish. try example: choice.slidedown("fast",function(){your function}) this call animation finish update $('.menu-2>ul>li').each(function(){ $(this).hover( function(){ var choice = $('ul', this); ('.menu-2>ul>li>ul').promise().done(func

java - Add a Node to a class that extends Scene -

how can add custom pane custom scene in code? public class mainscene extends scene { public mainscene() { super(new flowpane(), 800, 600); } public void additem(string name) { item item = new item(name); // item extends pane. getroot().getchildren().add(item); // doesn't work. } } in example, not have reference root element. without asking user, cannot pass reference of root element because of use of super() . since getroot() returns parent, cannot use getchildren() on obvious reasons. what can type-cast getroot() flowpane . public void additem(string name) { pane item = new pane(); // item extends pane. ((flowpane)getroot()).getchildren().add(item); }

jpa - org.apache.jasper.JasperException: java.lang.IllegalArgumentException: Object: emp.Customer[ id=100 ] is not a known entity type -

error coming whwne project start "org.apache.jasper.jasperexception: java.lang.illegalargumentexception: object: emp.customer[ id=100 ] not known entity type." how solve error plz tell me 1)newjsp.jsp <%-- document : newjsp created on : oct 10, 2015, 1:10:21 pm author : niral --%>`enter code here` <%@page import="emp.*"%> <%@page import="javax.persistence.persistence"%> <%@page import="javax.persistence.entitymanager"%> <%@page import="javax.persistence.entitymanagerfactory"%> <%@page contenttype="text/html" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> </head> <body> <% entitymanagerfactory emf = persistence.createentitymanagerfactory(&qu

javascript - Jquery caching data-* attributes -

in html page , have following div: <div id="notification"></div> an ajax call add attribute div after receiving successful response.this ajax success does: $("form").on("submit", function (e) { e.preventdefault(); $.ajax({ datatype: 'json', type: "post", url: "/dummy/url", data: {redacted}, success: function (data) { $('#notification').attr({'data-status': data['status'], 'data-message': data['message']}); $('#notification').click(); $('#notification').removeattr("data-status data-message"); } }); }); the problem attributes of #notification not go away after using removeattr. mean removes attributes page, remains cached. thats why i getting same data-message on every click though server returns

c++ - "Don't Care" fields in multiset keys -

i have compound data type like: struct key { optional<int> a; optional<int> b; optional<int> c; }; i have multiset, multiset<key> . example, contains {1, 2, 3} {1, null, 3} {null, 2, 3} {null, null, 3} i want objects in multiset match {1, 2, 3} . there catch: null fields should match anything. example, {1, 2, 3} matches {1, null, 3} . i tried defined comparator ( < ) ignores null values. example {1, null, null} == {null, 2, 3} . not follow weak strict ordering , gives me wrong results. how can that? your problem here more serious not following weak strict ordering rules. equality not equivalence relation: { 1,null,3} matches {1, 2, 3} , {1, 4, 3}, {1, 2, 3} not match {1, 4, 3}. conclusion cannot rely on standard container meet matching requirement catch all values. if want store them, should try use unordered_set or unordered_multiset because allow store value without problems. have manually implement method sea

python 2.7 - How to better this regex? -

i have list of strings this: /soccer/poland/ekstraklasa-2008-2009/results/ /soccer/poland/orange-ekstraklasa-2007-2008/results/ /soccer/poland/orange-ekstraklasa-youth-2010-2011/results/ from each string want take middle part resulting in respectively: ekstraklasa orange ekstraklasa orange ekstraklasa youth my code here job feels can done in fewer steps , regex alone. name = re.search('/([-a-z\d]+)/results/', string).group(1) # take middle part name = re.search('[-a-z]+', name).group() # trim numbers if name.endswith('-'): name = name[:-1] # trim tailing `-` if needed name = name.replace('-', ' ') can see how make better? this regex should work: /(?:\/\w+){2}\/([\w\-]+)(?:-\d+){2}/ explanation: (?:\/\w+){2} - eat first 2 words delimited / \/ - eat next / ([\w\-]+) - match word characters of hyphens (this we're looking for) (?:-\d+){2} - eat hyphen

Lua: When is it possible to use colon syntax? -

while understand basic difference between . , : , haven't figured out when lua allows use colon syntax. instance, work: s = "test" -- type(s) string. -- can write colon function type function string:myfunc() return #self end -- , colon function calls possible s:myfunc() however same pattern not seem work other types. instance, when have table instead of string : t = {} -- type(t) table. -- can write colon function type function table:myfunc() return #self end -- surprisingly, colon function call not not possible! t:myfunc() -- error: attempt call method 'myfunc' (a nil value) -- verbose dot call works table.myfunc(t) moving on type: x = 1 -- type(x) number. -- expecting can write colon function -- type well. however, in case -- fails: function number:myfunc() return self end -- error: attempt index global 'number' (a nil value) i'm trying make sense of this. correct conclude certain types string allow both colon-fu

python - Pasrse API Response CSV to List without writing to file -

goal: directly read .csv api response python list i using census bureau's bulk geocoder lat/long of many addresses. documentation batch geocoding on page 5-6. i able read csv list without first saving file. my first attempt following: get response: import requests import csv url = 'http://geocoding.geo.census.gov/geocoder/locations/addressbatch' payload = {'benchmark':'public_ar_current', 'vintage':'current_current', 'returntype':'locations'} files = {'addressfile':('addresses.csv',open(tmp_file,'rb'),'text/csv')} response = requests.post(url,data=payload,files=files) handle response (without writing file): reader = csv.reader(response.content) tmp_list = list(reader) print(tmp_list) the output 1-d list: [[unique_id], [input_address], [match/no_match], [exact/non-exact], [output_address], [lat/long], [tiger_line_id], [tiger_lin

Segmentation fault on logical variable in Fortran -

i'm trying run subroutine 'condensation' found here ( http://mesonh.aero.obs-mip.fr/chaboureau/pub/ncl/ ), wrote 'main' program in order initialize arrays , call subroutine. i did 'print' statements in 'condensation' subroutine find wrong, , found problem (segmentation fault error) occurs on every mention of logical variable 'luseri'. but, don't know why. in main program, wrote: program main logical :: luseri ... luseri = .true. ... call condensation(...,luseri) end program main ('luseri' last argument in subroutine) everything seems ok: variable declaration , assignment in main program, declaration in subroutine 'condensation' , mention. here 'main' program (main_cst.f90) wrote: program main_cst implicit none integer, parameter :: klon = 8 ! horizontal dimension integer, parameter :: klev = 28 ! vertical dimension integer, parameter :: kidia = 1 ! value of first point in x; default=1 integer,

cakephp 2.3 - Apply model association info when using find('list') -

for user model have association: public $belongsto = array( 'country' => array( 'foreignkey' => 'country_id', 'conditions' => array( 'country.code_status' => 'assigned'), 'order' => array( 'short_name_en') ) ); for reason expecting using: $countries = $this->user->country->find('list'); i list of possible country codes populate dropdown in form , comply association definition. this not happening, , understandable since find() cannot (?) detect associated model coming from, can not apply conditions/order defined. added method appmodel like: public function getassociationfind( $model, $type='belongsto' ) { if (!isset($this->$type)) { throw new cakeexception(__('association type %s not found in model %s.', $type, $this->name)); } $typeassociations = $this->$type; if (!isset($typeassociations[$model]

java - Having problems with .getInputStream() -

i trying program tcp chat server, having difficulties .getinputstream() , .getoutputstream() methods, compiler says "cannot find symbol- method .getinputstream(). here code, have not progressed far yet: import java.net.*; import java.io.*; public class server { public static void server (string[] args) { serversocket ss1 = null; dataoutputstream dos1 = null; datainputstream dis1 = null; //setting values null try { ss1 = new serversocket(5000); //setting socket ss1 port 5000 , creating instance socket clientsocket = ss1.accept(); //accepting connection request dos1 = new dataoutputstream(ss1.getoutputstream()); dis1 = new datainputstream(ss1.getinputstream()); //creating output , input streams } catch (exception e){ system.err.println("error!"); } } } i using bluej on windows 7, if that's problem. also, can't seem find explanations how data streams or "old-school" sockets work, if knows can those, it'd apprecia

python - Explain the function -

lloyd = { "name": "lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } # add function below! def average(numbers): total = sum(numbers) total = float(total) total /= len(numbers) return total def get_average(student): homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) total = 0.1*homework + 0.3*quizzes + 0.6*tests return total def get_letter_grade(score): if score >= 90

php - Codeigniter JOIN multiple tables -

i'm having little trouble in retrieving data in multiple tables using codeigniter. this code i'm using retrieve data in model working well. function retrieve_experience($alumni_id) { $this->db->select('*'); $this->db->from('experience'); $this->db->where('alumni_id',$alumni_id); $query = $this->db->get(); return $query; } function retrieve_education($alumni_id) { $this->db->select('*'); $this->db->from('education'); $this->db->where('alumni_id',$alumni_id); $query = $this->db->get(); return $query; } now tried using simplified code fails display data. here code in model function retrieve_all_data($alumni_id) { $this->db->select('*'); $this->db->from('experience'); $this->db->join('education','education.alumni_id=experience.alumni_id'); $this->db->where('experience.alumni_id',$alumni_id); $query=$this->d

python - Summing groups of items in a list -

list1 = [1,3,5,7,9,11,13,15,17] list2 = [] i want add 3 first elements list2[0] , next 3 list2[1] , on. 1+3+5 list2[0] 7+9+11 list2[1] 13+15+17 list2[2] the result should be: list2 = [9,27,45] the documentation standard itertools module has recipe dividing list fixed-length groups: def grouper(iterable, n, fillvalue=none): "collect data fixed-length chunks or blocks" # grouper('abcdefg', 3, 'x') --> abc def gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) as beginner, might not understand how works, did confirm does: import itertools def grouper(iterable, n, fillvalue=none): "collect data fixed-length chunks or blocks" # grouper('abcdefg', 3, 'x') --> abc def gxx" args = [iter(iterable)] * n return it.zip_longest(*args, fillvalue=fillvalue) list1 = [1,3,5,7,9,11,13,15,17] print(list(grouper(list1, 3))) prints: [(1, 3, 5), (

python - Graceful error handling and logging in Jinja extension -

i'm developing jinja extension performs few potentially harmful operations, on failure raise exception holds information on went wrong. when occurs, of course exception prevent jinja completing render process , return none rather render result. problem mitigated using try/catch statement , returning empty string or whatever suitable. however, throws away exception , debugging info, rather pass on error log. system responsible setting jinja environment has it's own logging service, prefer keep decoupled extension. aware though, jinja has undefined class have used intercept access of undefined variables in project. is there way raise special type of exception ( undefinedexception did not work), or tell jinja environment log warning, when error occurs in extension, while still allowing continue execution? what have in mind along lines of example: def _render(*args, **kwrags): # ... try: self.potentially_harmful_operation() except exception e:

in memory database - WARN AEROSPIKE_ERR_CLIENT Socket write error: 111 -

im getting error $ aql 2015-10-10 15:48:10 warn aerospike_err_client socket write error: 111 error -1: failed seed cluster can me out of this.............! is aerospike running on same host did run aql? if is, listening on local 127.0.0.1 interface , on default port (3000)? (feel free share configuration). if not, make sure specify host , port when running aql using -h , -p options: aql -h <ip> -p <port>

sequelize.js - Sequelize error model is not associated -

i have 2 models: userauth , userfollow associate before sync. association userfollow has 2 foreign keys referencing user. did not use aliases when do: userauth.findone({ where:{ id: "someid" }, include: [{ model: userfollow }], logging: false }) it throws error says: [error: user_follow not associated user_auth!] i have class method "associate" in userfollow call before sync: classmethods: { associate: function(models) { // alter table user_follow // add foreign key (follower_id) // references user_auth(id) // on delete cascade // on update cascade userfollow.belongsto(models.user_auth, { ondelete: "cascade", onupdate: "cascade", foreignkey: 'follower_id', targetkey: '

python - Why does my string remove multiple characters? -

Image
i've noticed curious phenomenon here. i've instantiated global variable ( usrpin ), , i'm comparing local variable ( c ). when input value (in case, 4 zeros), value chopped off, creating string 1 character long. why? usrpin ... def login(): global usrpin ... c = str(input("enter pin")) print usrpin print str(c) if usrpin == c: mainmenu() else: print "incorrect pin" login() what on earth going on? in python 2.x input() automatic evaluation. means when do: input(0.2757) python evaluates float. similarly, in case 0000 evaluated integer , since 4 zeros same 1 zero, chops away. in python 2.x it's recommended use raw_input() safety. note: raw_input() in python 2.x returns string.

authentication - Get request with Python 2.7 -

i'm trying send request python 2.7. server i'm trying access has basic authentication , url i'm accessing displaying string want script print string. so code sending request server , saves string receives server, has basic auth. the problem prints out html page login page not string. username = 'username' password = 'password' server = "http://someserver/update" def get_auth(): request = urllib2.request(server) base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("authorization", "basic %s" % base64string) result = urllib2.urlopen(request) # print(result) def get_string(): f = urllib2.urlopen(server) print f.read() def main(): get_auth() get_string() if __name__ == '__main__': main() they way using get_string() never sends authentication header. rather fiddling urllib2 , might want

Multithreading example from Head First java book .Please explain -

Image
class bankaccount { private int balance = 100; public int getbalance() { return balance; } public void withdraw(int amount) { balance = balance - amount; } } public class ryanandmonicajob implements runnable{ private bankaccount account = new bankaccount(); public static void main(string[] args) { ryanandmonicajob thejob = new ryanandmonicajob(); thread 1 = new thread(thejob); thread 2 = new thread(thejob); one.setname("ryan"); two.setname("monica"); one.start(); two.start(); } public void run() { for(int x = 0;x < 10;x++) { makewithdrawl(10); if(account.getbalance() < 10) { system.out.println("overdrawn!"); } } } public void makewithdrawl(int amount) { if(account.getbalance() >= amount) { system.out.println(thread.currentthread().getname() + " withdraw"); try{ system.out.println(thread.currentthrea

sql server - What's the difference between com.microsoft.sqlserver.jdbc.SQLServerConnection and java.sql.Connection -

i'm having maven web application on tomcat 8 connecting sql server 2012 database. for logging purposes wanted use getclientconnectionid . due policies of microsoft it's quite pain make driver work maven (i know it's possible , did while, in case lead several problems after migrating/sharing project). unfortunately jtds-driver refuses work database server unknown reasons. so right i've put sqljdbc4-4.0.jar lib folder of tomcat , meta-inf/services of project , since fine. yet after doing more database i'm unsure if it's worth switch , tried information actual differences between com.microsoft.sqlserver.jdbc.sqlserverconnection , java.sql.connection , if make sense change. so far couldn't find useful information. pages refer how solve issues each type... is there difference in performance, behaviour or other possibilities justify switching back? java.sql.connection interface com.microsoft.sqlserver.jdbc.sqlserverconnection implemen