Posts

Showing posts from April, 2011

c++ - Can I have a const member function that returns *this and works with non-constant objects? -

if understand correctly, member function not supposed modify object should declared const let users know guarantee. now, happens when member function returns reference *this ? example: class c{ public: c &f() const {return *this;} }; inside c::f() , this has type const c* , so, following not compile: int main() { c c; // non-constant object! c.f(); return 0; } of course, provide non-const version of c::f() work on non-constant objects: class c{ public: const c &f() const; c &f(); }; however, not believe want. note non-constant version not change object, promise users not expressed... missing something? edit: let me summarize question clarity: f() not modify object on called, declaring c &f(); without making const member misleading. on other hand, want able call f() on non-const objects. how resolve situation? edit: comes out discussion took place in comments question based on incorrect understanding of const ness of f

sh - How could I remove one older folder with bash? -

i have following folders: 1435773881 jul 1 21:04 1435774663 jul 2 21:17 1435774856 jul 3 21:20 1435775432 jul 4 21:56 i need remove older folder folder ( 1435773881 in case above) bash script. what command should use? you can do ls -lt | tail -1 | awk '{print $nf}' | xargs rm -rf ls -lt | tail -1 shows last line after sorting directories date awk '{print $nf}' "prints" last column (which directory name) xargs rm -rf deletes directory

java - Hibernate does not save Object even not getting any error in log -

i have single table in db . created pojo class map class instance table. class structure @entity @table(name = "example") class example { @id @generatedvalue(strategy = generationtype.auto) @column(name = "id") int id; @column(name = "slot_id") int slot_id; @column(name = "slot_date") string slot_date; @column(name = "hotel_id") string hotel_id; @column(name = "room_type_id") string room_type_id; @column(name = "create_date") string create_date; @column(name = "update_date") string update_date; @column(name = "slot_price") double slot_price; @column(name = "available_rooms") integer available_roooms; //rest have getter , setter method } hibernet commit part public void save(example example) { session

android - How Messages are Received on WhatsApp or any other messaging service? -

can please tell me how whatsapp messages received on mobile? like, phone requests whatsapp serve every second or server send phone ping when message me received @ server end. don't want know exact procedure, overview job. well guess, not easy answer in scope here how might work. for may need understanding of technology on mobile side , server side.so let me try explain in simple manner may implementation. 1) no, mobile not ping server everytime. polling adds lots of overhead on network, multiple calls can stacked if there delay in responding leading huge traffic on server side. instead , other way round. whenever server recieves msg pings instead recieved msg. 2) hope point 1 makes clear other way around. know push notification. push notification whichserver can notify mobile of new msgs or information or update.here's link can give more detail on push notification android https://parse.com/tutorials/android-push-notifications 3)how server processes request

How to work as a team with Microsoft Visual C# and SQL server centralized database and single Project -

here scenario. wants project using microsoft visual c# 2013 , sql server database. project group project. want work every member on same project same centralized database. technologies have use , how configurations. i think better use tfs . , create database project using visual studio . maintain local database. , tfs version controlling , source sharing among group members.

angularjs - How to select a week with date picker -

i'm using angular bootstrap datepicker . have 1 datepicker , need select week(sunday saturday) not day of week for ex, select week period popup calender . select week period 19 july, 2015 25 july, 2015 here comes output 07/19/2015 07/25/2015 in jquery, know how it, jquery weekpicker . curious how select week using angularjs i grateful assistance. thanks. calculate week date picker, can try one $('#date').datepicker({onselect: function() { var mon = $(this).datepicker('getdate'); mon.setdate(mon.getdate() + 1 - (mon.getday() || 7)); var sun = new date(mon.gettime()); sun.setdate(sun.getdate() + 6); alert(mon + ' ' + sun); }}); see link - https://forum.jquery.com/topic/datepicker-select-week

android - How do I pull a image by gridview position -

everything working picture not shown baseadapter: public bitmap getitem(int position) { return bitmaps.get(position); } activity: intent = new intent(getapplicationcontext(), spcifiesimage.class); // passing array index i.putextra("id", position);`enter code here` startactivity(i); this activity want image there : intent intent = new intent(getapplicationcontext(), spcifiesimage.class); intent = getintent(); // selected image id int position = i.getextras().getint("id"); customgrid imageadapter = new customgrid(mcontext); imageview imageview = (imageview) findviewbyid(r.id.imageview3); imageview.setimagebitmap(imageadapter.bitmaps.get(position)); // passing array index intent.putextra("mas", massage); startactivity(intent); customgrid: context mcontext; private bitmap btimaprecieve; list<parseobject> parseobjects; arr

sql - How to avoid multiple column in correlated sub query assignment in MySQL update -

i'm attempting assign closest location community based on community postcode , using haversine formula sql described here . need return single scalar value can't seem avoid having second calculated distance value needed determine closest location. help. update community c join postcode p on p.id = c.postcode_id join ( select 100.0 radius, 111.045 distance_unit ) set c.location_id = ( select l.id, a.distance_unit * degrees(acos(cos(radians(p.latitude)) * cos(radians(l.latitude)) * cos(radians(p.longitude - l.longitude)) + sin(radians(p.latitude)) * sin(radians(l.latitude)))) distance location l l.latitude between p.latitude - (a.radius / a.distance_unit) , p.latitude + (a.radius / a.distance_unit) , l.longitude between p.longitude - (a.radius / (a.distance_unit * cos(radians(p.latitude)))) , p.longitude + (a.radius / (a.distance

javascript - jQuery Image Slices -

i've image slider, in want slice image create kind of 3d-effekt. created slider, i'm struggling responsive behavior of slider. in px values, working finde, want slider responsive. @ code , give me solution solve problem? here code: the scss: /*variables & helper*/ *{ box-sizing: border-box; } %clearfix { &:after { content: ""; display: table; clear: both; } } body, html{ margin: 0; padding: 0; background: url('../img/bg.png'); } img{ max-width: 100%; height: auto; } .article{ width: 80%; margin: 2rem auto; background: #fff; @extend %clearfix; padding: .8rem; } .img__container { float: left; width: 100%; margin: 0; } .slice{ float: left; } and here javascript: $(function(){ $( window ).on('resize',function() { calcdimensions(); bgposition(); }); /*variables*/ var $imgcontainer = $('.img__container'), $img

javascript - Loading jQuery script and getting TypeError: $.fn.appear.run is not a function -

i've loaded animation script css markup, i'm getting following error: typeerror: $.fn.appear.run not function anyone have ideas why , how can sort that? /* * css3 animate * copyright (c) 2014 jack mccourt * https://github.com/kriegar/css3-animate-it * version: 0.1.0 * * utilise jquery.appear plugin within javascript file here link * https://github.com/morr/jquery.appear * * utilise jquery.dotimeout plugin data-sequence functionality here link them. * http://benalman.com/projects/jquery-dotimeout-plugin/ */ (function($) { var selectors = []; var check_binded = false; var check_lock = false; var defaults = { interval: 250, force_process: false } var $window = $(window); var $prior_appeared; function process() { check_lock = false; (var index = 0; index < selectors.length; index++) { var $appeared = $(selectors[index]).filter(function() { return $(this).is(':appeared'); }); $appeared

In a MongoDB index, what do the options "safe" and "force" mean? -

i'm looking @ our mongo (2.4.10) indexes, using collection.getindexes(). see options aren't discussed in doc can find. specifically, see options "safe" , "force". example below: { "v" : 1, "name" : "status_1", "key" : { "status" : numberlong(1) }, "ns" : "db.mycoll", "force" : true, "background" : true }, what "force" , "safe" mean? the options mention ("force" , "safe") not valid index options mongodb 2.4. they resulted developer accidentally ensuring index including these index options (perhaps having intended fields part of index criteria?). you can reproduce outcome in mongo shell: > db.foo.ensureindex({foo: true}, {force: true, safe: true}) { "createdcollectionautomatically" : true, "numindexesbefore" : 1, "numindexesafter"

r - Work With a Value in a Data Frame by Character -

i have data frame column of text formatted nba season such: year 2014-15 2013-14 2012-13 ... 1999-00 i need reformat second year. small data set, , don't mind manually fixing 1999-00 value, can't figure out how to: paste(data$year[1:2],data$year[6:7]) to get: year 2015 2014 2013 ... 2000 i think simplest extract first year , add one: as.numeric(substr(data$year, 1, 4)) + 1 # [1] 2003 2002 2001 2000 1999 data: (data <- data.frame(year=c("2002-03", "2001-02", "2000-01", "1999-00", "1998-99"))) # year # 1 2002-03 # 2 2001-02 # 3 2000-01 # 4 1999-00 # 5 1998-99

python - finding highest number, no arrays, only if statements -

i taking course in python programming , have been given assignment complete of finding highest number given prompting user. easy complete array unable use them assignment. having issue if input series of numbers such "55, 100, 99" program telling 99 highest number. not sure going wrong. largest = none smallest = none temp = none while temp != "done": num = raw_input("enter number: ") if num == "done" : break try: int(num) except: print ('that not integer. try again') break print(largest) if largest none: largest = num if largest != none , num > largest: largest = num print ('invalid input') print "maximum is", largest print "minimum is", smallest change: int(num) to: num = int(num) otherwise, num still string because you're not saving result of conversion anywhere.

ios - Swift class extension with protocol vs conforming to protocol -

in this tutorial, author uses extension flickrphotosviewcontroller: uitextfielddelegate , implements protocol method. have tested , author have done class flickrphotosviewcontroller: uicollectionviewcontroller, uitextfielddelegate , implemented methods in class. difference can see makes easier read , understand. design style or something? is design style or something very so. normal style separate class multiple extensions, each expressing class's adoption of 1 or more related protocols. separation has no functional meaning; class could have been expressed without separation.

ios - How to save Pin Annotation once app is closed (Swift) -

currently, app pins location , location stores so: func locationmanager(manager: cllocationmanager!, didupdatelocations locations: [anyobject]!) { // find location of user var userlocation:cllocation = locations[0] as! cllocation var latitude = userlocation.coordinate.latitude var longitude = userlocation.coordinate.longitude var latdelta:cllocationdegrees = 0.01 var longdelta: cllocationdegrees = 0.01 var span: mkcoordinatespan = mkcoordinatespanmake(latdelta, longdelta) var location:mkuserlocation = currentlocation; var region: mkcoordinateregion = mkcoordinateregionmake(location.coordinate, span) var coordinate:cllocationcoordinate2d = cllocationcoordinate2dmake(latitude, longitude); carinitiallocation = userlocation; locationsdefaults.append(carinitiallocation); carinitialcoordinate = coordinate; self.map.setregion(region, animated: true); } where locationsdefaults array store location of pin. i use nsuserdefaults,

javascript - Jquery script in html page do not work -

i have php page in wp site, , trying add jquery script directly in php. , structure...** <?php /* template name: gallery page */ ?> <?php get_header(); ?> <?php //here have working php code ?> //here html <script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> alert("hi"); </script> <?php endwhile; else : // no rows found endif; ?> <div class="spacing"></div> <?php get_footer(); ?> anyone knows why javascript code dont work if set set in script,. while works if type <script> alert("hi"); </script> also: if link jquery in footer, , call external script in site code above, works. alert starts. kno

php - How to store chat history in web chat app -

i working on company intranet has embedded chat client users can talk each on intranet. i'm using guide http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket work on basis of chat client , have working users can talk each other privately. want able though maintain chat history if refresh page or if switch between pages. not sure best way store is, whether in database, store socket information in chat server or store in session or cookie array. thanks can provide storing chat history in redis ideal. there several redis clients available php: http://redis.io/clients#php . depending on amount of traffic get, archive old chats mysql or other database @ later time. you'd want use redis while conversation active can write , read extremely (great chatting on sockets). here's example of using php & redis chat service step-by-step examples: http://www.9lessons.info/2014/01/getting-started-with-redis-chatting.html

Why Android APK much larger when installed? -

i installing apk weighs 2mb. once application installed weighs 9mb. there logical explanation this? the apk file-format compressed format. as install app android decompresses app because performs optimizations. reason unfavourable decompress before every start performance , battery-life reasons. some apks bring native libraries them (for example many games or apps build delphi) stored uncompressed. escpecially kind of apps suffer being enormous large when installed compared java-only apps.

java - Android Database SQLite Average -

i making app android sqlite database have 1 table , 2 columns: 1 names , other marks. also, can see information of database in listview , can add more elements it. how can make average of marks in database? , how can delete row? i paste database helper public class persondatabasehelper { private static final string tag = persondatabasehelper.class.getsimplename(); // database configuration // if want onupgrade run change database_version private static final int database_version = 1; private static final string database_name = "mydatabase.db"; // table configuration private static final string table_name = "person_table"; // table name private static final string person_table_column_id = "_id"; // column named "_id" required cursor private static final string person_table_column_name = "person_name"; private static final string person_table_column_pin = "person_pin"; private databaseopenhelper openhelp

c++ - countNonZero function gives an assertion error in openCV -

i tried horizontal projection using countnonzero() function below. mat src = imread(input_file, cv_load_image_color); mat binaryimage = src.clone(); cvtcolor(src, src, cv_bgr2gray); mat horizontal = mat::zeros(1,binaryimage.cols, cv_8uc1); (int = 0; i<binaryimage.cols; i++) { mat roi = binaryimage(rect(0, 0, 1, binaryimage.rows)); horizontal.at<int>(0,i) = countnonzero(roi); cout << "col no:" << << " >>" << horizontal.at<int>(0, i); } but error occured in line of calling countonzero() function. error follows. opencv error: assertion failed (src.channels() == 1 && func != 0) in cv::countno nzero, file c:\builds\2_4_packslave-win32-vc12-shared\opencv\modules\core\src\st at.cpp, line 549 can please point out mistake? assertion src.channels() == 1 means image should have 1 channel, i.e. has gray, not colored. calling countnonzero on roi , subimage of binaryimage , clon

android - Continuous Image capture using Camera2 api -

how capture continuous images using camera 2 api's. wrote simple application , thread in capture continuous images not working it nice if provided code see what's wrong. in general terms, you'll want create cameradevice object , call cameradevice.createcapturesession(list <surface>, cameracapturesession.statecallback, handler) method specifying surfaces might output (maybe 1). once cameracapturesession.statecallback (that specified in createcapturesession method) calls onconfigured(cameracapturesession) method, call cameradevice.createcapturerequest(int) method, returns capturerequest.builder object. this, can use capturerequest.builder.addtarget(surface) method specify of pre-specified surface(s) want output (probably of them). once you're done adding targets, call capturerequest.builder.build() method, returns capturerequest object. can use cameracapturesession object provided onconfigured(cameracapturesession) method pass capturereque

php - How to get the closest row to the current date in my table? -

i pull out table database current day lands when user visits page. table sample: ---+----------+----------- id | | ---+----------+----------- 1 |2015-07-01|2015-07-14 ---+----------+----------- 2 |2015-07-15|2015-07-31 ---+----------+----------- 3 |2015-08-01|2015-08-20 output: if date 2015-07-10 output should id 1 if date 2015-08-02 output should id 3 if understand question right, want select row today's date between "from" , "to"? if that's case should this: select id your_table_name curdate() >= `from` , curdate() <= `to` or if like: select id your_table_name curdate() between `from` , `to` both queries return 1 or many rows today's date in between "from" , "to".

moving average and errors - Matlab -

i have series of data x,y , trying find moving average. x data numbers integers 1 100 while y data numbers 0.01 1 , have standard deviation y_dev (which derive because experiment repeated several times). trying find moving average using 20 closest neighbors (using matlab): num_data=length(x) mov_average=y i=11,num_data-10 % leave data in edges same ind1(i)=i-10 ind2(i)=i+10 mov_average(i)=mean(y(ind1(i):ind2(i))); end the above way derives moving average not know how use standard deviation have each y data point because data points have larger standard deviations others means not reliable others (so weigh less). how can include standard deviation each data point in above calculation? thank you. say have vector a . way of writing mean(a) weighted average a*wts' , wts = ones(1,numel(a))/numel(a) . in case, have a = y(ind1(i):ind2(i)) . it sounds you're wanting use weighted moving average, weights wts no longer identical, chosen using standard deviati

arrays - Populating a 2 dimensional Range in excel using sum ifs function in VBA -

data in sheet profit based on store , location. looking have matrix location in 1 column , stores in row. each location , store return 1 value sum of profit stores (there maybe multiple stores in particular location) in location. this excel function: =sumifs(sheet2!$c$2:$c$6,sheet2!$a$2:$a$6,sheet1!$a5,sheet2!$b$2:$b$6,sheet1!b$4) try like, with sheets("sheet1") .range("b5:z99") .formula = "=sumifs(sheet2!$c$2:$c$6, sheet2!$a$2:$a$6, sheet1!$a5, sheet2!$b$2:$b$6, sheet1!b$4)" .value = .value end end essentially, write formula block of cells revert formulas' results values. edit dynamic last row: dim lr long lr = sheets("sheet2").cells(rows.count, 3).end(xlup).row then formula assignment be: .formula = "=sumifs(sheet2!$c$2:$c$" & lr & ", sheet2!$a$2:$a$" & lr & ", sheet1!$a5, sheet2!$b$2:$b$" & lr & ", sheet1!b$4)" edit: name

python - Need more elegant solution to even string length -

here's task got: given string of length, return first half. string "woohoo" yields "woo". first_half('woohoo') → 'woo' first_half('hellothere') → 'hello' first_half('abcdef') → 'abc' here's solution: def first_half(str): if len(str) % 2 == 0: b = len(str) // 2 return str[:b] my question is: can show me simpler solution in python of course doesn't require me use variable half of string length (b)? in python: str = "woohoo" str = str[:-len(str)/2]

r - Combine multiple data frames and calculate average -

i have 3 data frames below. wish combine them 1 data frame according lon & lat, , average 3 values each 'cell'. have read ( calculate average on multiple data frames ) , attempted utilise aggregate no avail....any pointers appreciated. > head(csr.grace[,c(1:14)],10) lon lat january february march april may june july august september october november december 1 28.5 -4.5 17.710425 13.855327 12.385712 13.558101 12.789865 6.913783 1.03770075 -5.3901741 -6.6351015 -7.661375 -3.09337944 6.0659410 2 29.5 -4.5 14.010154 10.257435 9.009641 10.275778 9.598241 5.166972 0.73570247 -4.2733162 -5.0861417 -5.850192 -2.93521806 4.1240150 3 30.5 -4.5 16.288443 10.467614 9.275714 10.904162 10.228808 5.364853 0.50089883 -4.7478741 -5.4320069 -6.316568 -3.80160315 3.8494745 4 31.5 -4.5 18.560677 9.932461 9.239592 11.037748 10.551886 5.281853 0.01181973 -4.9034324 -5.3504391 -6.438050 -4.41695714 3.3432301 5 32.5 -4.5 10.171202

Okta "On - Premises" SCIM Provisioning to Cloud Service from OAN App-to-Be -

i developing integration between our cloud service , okta's idp. become official oan app end-users can install via okta interface. during development phase of project, using okta developer preview account. our app accepts provisioning traffic via scim rest apis exposes. okta tells don't support sending scim directly production application integration-partner scim servers, , tells way connect scim traffic our application use downloadable on-premises provisioning java connector. have installed connector on centos machine , connected our preview account, working , sending scim messages expected. so, here's problem: when setting on-premises provisioning connector, had associate connector our specific okta preview account via configuration file, , accepting , associating via okta admin ui. plan put out application okta application network, each end-user provided unique key parameterized in application configuration , used component of scim base url each installation of our

java - Unreported exception IOException reading file from URL -

i've looked on , have yet find solution this. long , short of i'm trying take text file provided url , read string can other things it. the specific compile error is: /tmp/java_kwweo5/main.java:49: error: unreported exception ioexception; must caught or declared thrown string text = readurltextcontent("http://textfiles.com/stories/antcrick.txt"); ^ 1 error the code causing error, in main : import java.util.*; import java.net.url; import java.net.malformedurlexception; import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.ioexception; public class main { private static string readurltextcontent(string url) throws ioexception, malformedurlexception { url source = new url(url); bufferedreader reader = new bufferedreader(new inputstreamreader(source.openstream())); try { stringbuilder builder = new stringbuilder(); string line = re

ios - Adding Google Analytics to my podfile breaks the build (library not found) -

Image
i have google analytics in project works fine. once move pod file breaks. in pod: pod 'google/analytics', '~> 1.0.0' pod 'google-mobile-ads-sdk' the pod update log: installing google (1.0.7) using google-mobile-ads-sdk (7.3.1) installing googleanalytics (3.12.0) installing googlenetworkingutilities (1.0.0) installing googlesymbolutilities (1.0.0) installing googleutilities (1.0.1) i error: ld: library not found -liphone-lib clang: error: linker command failed exit code 1 (use -v see invocation) i've noticed breaks , spams "library search paths" in build settings. i have google ads sdk in pod file , has been working fine. anyone know wrong here? if it's bug fault be? edit: updated cocoapods 0.38.2, no change. in pod xcconfig file, var "library_search_paths" gets edited when include google analytics , removes "$(inherited)": example: library_search_paths = "$(pods_root)/googl

android - Pending Intent Fires Immediately -

i trying make app allows user enter 2 times using 2 timepickers , phone set silent between these times. using pendingintent , alarmmanager trigger broadcastreceiver @ times user chooses. @ moment, setting phone on , off silent when user clicks save button. "alarm scheduled" toast appears , "broadcast received" appears twice doesn't after that. here main activity code: public class mainactivity extends appcompatactivity { alarmmanager alarm; timepicker timepickerstart; timepicker timepickerend; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); timepickerstart = (timepicker)findviewbyid(r.id.timepickerstart); timepickerstart.setis24hourview(true); timepickerend = (timepicker)findviewbyid(r.id.timepickerend); timepickerend.setis24hourview(true); } //method called when save button clicked public void setalarm(view view) { calendar calen

arrays - java.util.ConcurrentModificationException with iterator (character movement) -

i'm coding game when hold d character moves right , when hold s character moves left. program works should, 1 exception. i'm moving character (and character moves fine), java keeps throwing error "java.util.concurrentmodificationexception". did research , learned cannot adding arraylist "keys" , iterating @ same time. said, how edit code still have character move seamlessly now? way know of make sure character moves @ same steady pace second hold key down, not take quick movement, pause, , continue motion. package leveleditor; import java.awt.canvas; import java.awt.dimension; import java.awt.graphics; import java.awt.toolkit; import java.awt.event.keyevent; import java.awt.event.keylistener; import java.awt.event.mouseevent; import java.awt.event.mouselistener; import java.awt.event.mousemotionlistener; import java.awt.image.bufferstrategy; import java.util.arraylist; import java.util.iterator; public class leveleditor extends canvas implements key

asp.net - Serve Tag not well formed when using EVAL() in OnClientClick event -

i'm trying create onclick event so onclientclick="document.queryselector('[kpi="31"]').value = '';return false;" the kpi= value has data bound, use code so onclientclick="<%# document.queryselector('[kpi=eval("kpi_id")]').value = '';return false; %>" but error saying server code not defined. please.. if datasource collection of objects , requesting property called kpi_id can avoid using eval , use item or container.dataitem. easiest way me show container.dataitem, since don't know kind of control using bind to. container.dataitem should object, need cast datatype onclientclick="document.queryselector('[kpi=<%# ((yourdatatype)container.dataitem).kpi_id %>)]').value = '';return false;" if use repeater in .net 4.5 can set itemtype repeater datatype can replace ((yourdatatype)container.dataitem) item: onclientclick="document.queryselector(&

javascript - ImageJ API WaitForUserDialog -

i'm trying write plugin imagej prompt user select rectangular roi in region in image using rectangular selection tool button built menu bar. here code: import ij.*; import ij.process.*; import ij.gui.*; import java.awt.*; import ij.plugin.*; public class computedop implements plugin { public void run(string arg) { ij.showmessage("dop plugin status","load image"); imageplus imp = ij.openimage(); imp.show(); ij.showmessage("dop plugin status","phantom loaded, select rectangle roi"); //image roi waitforuserdialog wait = new waitforuserdialog("select rectangular roi", "please press ok when done."); wait.show(); roi userroi = impphantom.getroi(); //create profile plot profileplot pplotphantom = new profileplot(impphantom, true); double[] phanprofile = pplotphantom.getprofile(); } my problem focus shifts prompt dialog appears due waitforuserdialog. won't

oauth - Require authentication or certificate to view Heroku app -

i have api deployed heroku. open see. want known android phones able modify , access api. i don't want user have login every time use app. can add sort of certificate phone verify credible? is oauth best approach this? is there better way user doesn't have login every time? this broad question (and hence there several approaches). without knowing language/framework using it's hard give specific advice, but: your server can issue cookie or token client can store locally duration. these tokens should include timestamp , authenticated (use library hmac authentication) prevent clients modifying tokens. clients should present token or cookie on each request server via http header or standard cookie header. you need login system support initial issue of token/cookie. clients oauth against server (complex) or against external service (github/facebook/google/twitter), still need way track state on client (hence token/cookie). cookie support should

javascript - How to provide an Api for your angular directive? -

until i've been developing widgets in javascript without angularjs. approach same: widget provide api allow clients change him part of application. approach has not change need use angularjs. have though in next solution , know options: angular.module("app", ["mycustomwidget"]) .controller("mainctrl", ["$scope", "mycustomwidgetservice", function($scope, mycustomwidgetservice) { $scope.mycustomwidgetservice = mycustomwidgetservice; $scope.changemycustomwidget = function() { $scope.mycustomwidgetservice.message = "this message written mainctrl"; } }]); /** widget */ angular.module("mycustomwidget", []) .factory("mycustomwidgetservice", function() { var mycustomwidgetservice = {}; mycustomwidgetservice.message = "this default message inside service"; return mycustomwidgetservice; }) .directive("mycustomwidgetdirective", [function() { return { bindtocontr

Production quality of applications made with Node.JS, GO and ASP.NET -

tj holowaychuk in blog starts pain using node.js apps in production. in blog , same pain detailed, , using set of libraries overcome that. is there statistics on 1 of these node.js, go, asp.net apps developed in c# more stable in production environment? i remember reading book long time ago entitled "code complete". it's 1 of few i've read include copious amounts of statistics related quality. couldn't tell whether or not latest revision includes of "new new" things node, example. i'm long-time coder , have worked on big (expensive) microsoft-related programming projects. on last year i've converted on node. it's difficult quantify quality-versus-code, honest. i'm left sense of faster development project span. acknowledge fair amount of i'm bundling isn't code case before. in past, though, microsoft author of "unknown" code. , now, it's collection of authors , dependency tree odd me--a proje

python 3.x - deference between df.describe and df.describe() -

import pandas pd import numpy np dates =pd.date_range('20150501',periods=5) df =pd.dataframe(np.random.randn(5,4),index=dates,columns="i know example".split()) df.describe() giving different results compared df.describe . please explain me difference between these modules. df.describe method (you can think of 'pointer method' in other languages). df.describe() calls method, , returns result. p = df.describe p() df.describe() in example above, p() , p.describe() execute same action

utf 8 - PHP - preg_replace and UTF8 -

i'm retrieving data database. receive array contains 'title' index utf8 encoded value. i'd use value name of file in saved, i'm doing this: file_put_contents($filename, $content); where $filename is '-' . $category['root'] . '-articles-' . $category['id'] . '-' . $this->urlize($category['category']) here code of "urlize" : private function urlize($value) { if ($value != null && trim($value) != '') { $value = preg_replace('/([\[\(].*[\]\)])/i', '', $value); $value = preg_replace('/[\s]/i', '-', $value); $value = preg_replace('/[,!?.;:\"\'&+\/]/i', '-', $value); $value = preg_replace('/[-]+/i', '-', $value); $value = preg_replace('/(^-)/i', '', $value); $value = preg_replace('/-$/i', '', $value); $value = pre

Regarding Python's socket module, how do you have client always receive data -

i server , client socket connection in python, client: import socket import sys sys import stdin serv = 'ip goes here' port = 8888 sock = socket.socket(socket.af_inet, socket.sock_stream) sock.connect((serv, port)) def prompt(): sys.stdout.write('<you> ') sys.stdout.flush() def send(x): sock.sendall(x) rec = 0 ex = len(x) while rec < ex: data = sock.recv(16) rec += len(data) while 1: if sock: data = sock.recv(16) if len(data) == 0: pass print '<server> %s' % data prompt() msg = stdin.readline() sock.sendall(msg) the way have now, if on 1 client, send "alphabet" both clients other clients not receive until send new message waiting stdin.readline() occur. wondering how make clients receive data server, , see without having have stdin.readline() happen first. thanks achieved wanted using threads suggested crazy