Posts

Showing posts from January, 2014

python - Error when trying to compress static files when using django-storages and django-compressor together -

i have setup aws s3 bucket in order transfer static files in remote cdn using application django-storages, worked fine until tried compress static files before uploading s3 using django_compressor. i have setup variables according django_compressor documentation django-storages ( https://django_compressor.readthedocs.org/en/latest/remote-storages/index.html ) i uploaded files in s3 using 'manage.py collectstatic' then: when 'manage.py compress' error: commanderror: error occured during rendering ../templates/base.html: 'https://my_bucket.s3.amazonaws.com/css/bootstrap.2.3.1.css' isn't accessible via compress_url ('https://my_bucket.s3-external-3.amazonaws.com/') , can't compressed what's wrong setup? here settings.py configuration django-storages , django_compressor: compress_url = 'https://mybucket_name.s3-external-3.amazonaws.com/' static_url = compress_url default_file_storage = 'my_project.boto_custom.cached

php - jQuery AJAX JSON data not sending -

i have below code running send data json object var jdata = json.stringify(grid.serialize()); $.ajax({ 'type': 'post', 'url': 'print.php', 'data': jdata, //assuming have json library linked. 'contenttype': "application/json", 'success': function (data) { alert(data); }, 'error': function (x, y, z) { alert(x.responsetext); // x.responsetext should have what's wrong } }); alert(json.stringify(grid.serialize())); currenty alert after ajax function prints [{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}] on receiving page using <?php print_r($_post) ?> see page being sent ,

java - How to apply JTatto themes on JFrame using Swing -

Image
i trying apply jtatto , feel in swing project. the theme being applied on forms on others controls aren't working properly. overlapping on top of each other. to apply theme using following code try { string lookandfeel="com.jtattoo.plaf.smart.smartlookandfeel"; uimanager.setlookandfeel(lookandfeel); } catch(exception ex) { ex.printstacktrace(); } works expecting l&f must be initialized before gui creations for changes on runtime, applied top-level containers calling swingutilities.updatecomponenttreeui(component c) , simpler component c == local variable top-level container , otherwise have iterating , apply each of jcomponents separatelly, in current components tree import java.awt.borderlayout; import java.awt.dimension; import java.awt.event.actionevent; import javax.swing.abstractaction; import javax.swing.icon; import javax.swing.jframe; import javax.swing.jmenu; import javax.swing.jmenubar; import javax.swing.jmenuitem; i

lua - Awesome WM: Move window from one screen to another -

how can program rc.lua file enable keyboard shortcut move window 1 tag on 1 screen tag on different screen? know modkey + shift + [tag number] shortcut, moves window different tag on same screen. for example: want move window first tag on screen 1 third tag on screen 2 (or @ least active tag on screen 2).

python - Accessing model from FileSystemStorage -

i have custom filesystemstorage. idea pass optional filename parameter. custome storge code: class salesmapfilestores(filesystemstorage): def __init__(self, location=none, base_url=none, filename=none): if filename: self.filename = filename super(salesmapfilestores, self).__init__(location=location, base_url=base_url) def get_available_name(self, name): return name def get_valid_name(self, name): if self.filename: return self.filename return name def _save(self, name, content): if self.exists(name): self.delete(name) return super(salesmapfilestores, self)._save(name, conten what whant pass filename parameter model. somethin this: class salesmapimage(models.model): name = models.charfield(max_length=254, verbose_name='filename') image = salesmapimagefield(upload_to='salesmap/test', storage=salesmapfilestores(filename=name), verbose_name='

php - How to improve rendering in FPDF? -

<?php $factuurnr = $_get['factuurnr']; require('fpdf/fpdf.php'); //connect database include("db_connect.php"); //create new pdf file $pdf=new fpdf(); //open file $pdf->open(); //disable automatic page break $pdf->setautopagebreak(false); //add first page $pdf->addpage(); //set initial y axis position per page $y_axis_initial = 25; //print column titles actual page $pdf->setfillcolor(232, 232, 232); $pdf->setfont('arial', 'b', 12); $pdf->sety($y_axis_initial); $pdf->setx(25); $pdf->cell(30, 6, 'klantnummer', 1, 0, 'l', 1); $pdf->cell(100, 6, 'factuurnummer', 1, 0, 'l', 1); $pdf->cell(30, 6, 'bedrag', 1, 0, 'r', 1); $y_axis = $y_axis + $row_height; //select products want show in pdf file $query="select * facturen factuurnummer = '$factuurnr'"; $result=mysql_query($query); //initialize counter $i = 0; //set maximum rows per p

javascript - AngularJS nested components and scope -

here's component displaying customer's address (please excuse jade ): address(style='{{addressstyle}}') strong {{clinic.businessname}} br span {{clinic.address.address1}} br span(ng-switch='{{clinic.address.address2 != null}}') span(ng-switch-when='true') | {{clinic.address.address2}} br span {{clinic.address.suburb}} {{clinic.address.state}} {{clinic.address.postcode}} br abbr(title='phone') p: | {{functions.formatphoneno(clinic.phone)}} app.directive('clinicaddress', function($interpolate) { return { restrict: 'e', templateurl: 'directives/clinicaddress', scope: { clinic: '=', functions: '=' }, link: function(scope, element, attrs) { scope.addressstyle = attrs.style ? scope.addressstyle = $interpolate(attrs.style)() : ''; } }; }); and one, based on it, displayi

php - How to maintain array structure and keys during calcultations -

i have database rows of data each column country. in example there 4 country (columns) , 3 rows although number of each change , need dynamic inputs. want normalize each row min value 0 , max 100 , @ same time keep 4 x 3 array structure of original database can extract rows or columns on request. the final output passed javascript presented in graph form. code have come normalizes data correctly output 1 long array 12 x 1 , column names have been dropped. i wondering if know how keep same structure $scorenorm output of $dataa , both presented below? <?php $conn=mysql_connect("relevant inputs"); if(! $conn ) { die('could not connect: ' . mysql_error()); } mysql_select_db("db-name"); $dataarray = "select * data2012" or die(mysql_error()); $data2012=mysql_query($dataarray, $conn); if(! $data2012 ) { die('could not data: ' . mysql_error()); } $scorenorm = array(); $dataa = array(); while($row = mysql_fe

java - eager fetch objects in collections -

i have cat objects mapped using hibernate similar 1 mentioned in manual: http://docs.jboss.org/hibernate/core/4.3/manual/en-us/html_single/ (example 4.1) . fields in cat class set lazily fetched, write hql query eagerly fetches cat object along kittens. tried using from cat c inner join fetch c.kitten , doesn't fetch fields of each of kittens. my question is: how can write single hql query eagerly fetches items in collection? aware of eager fetching collections in hibernate scrollableresults don't think there solution there (and if possible don't want change mapping files eager fetching).

graph - Legend in biograph plot in Matlab -

i have biograph object, , want "color-code" edges , vertices. is possible legends in biograph plot, similar ones in plot . my code this: sys = sparse(from_nodes, to_nodes,1,s,s); systri = tril(sys + sys'); h = view(biograph(systri,[],'showarrows','off','showweights','off')); %% 1 of parts i'm coloring: set(h.nodes(node_list1),'color',[1 0.4 0.4]) fowedges = getedgesbynodeid(h,get(h.nodes(node_list1),'id')); revedges = getedgesbynodeid(h,get(h.nodes(fliplr(node_list1)),'id')); edges = [fowedges;revedges]; set(edges,'linecolor',[1 0 0]) set(edges,'linewidth',1.5) now, this: legend(h,'node list 1', 'node list 2'); does know if possible? if want few times, manually. you can try print figure biograph window, , add labels there.

php - Syntax error:MySQL Insert Select -

i have query insert tbl_userprofile: $sql = "insert tbl_userprofile (userid, name, surname, gender, nationality, address, mobile, department, email, question, answer) select tbl_user.id , '$name', '$surname', '$gender', '$nationality', '$address','$mobile', '$department', '$email', '$question', '$answer' tbl_user username = '$uname'"; i'm getting syntax error saying: "you have error in sql syntax; check manual corresponds mysql server version right syntax use near 'pet-peeve', 'dirt' tbl_user username = 'alex'' @ line 2" note: pet-peeve , dirt question , answer. dont know how i'm getting syntax error. please syntax error? thanks there might plain text in 2 last field maybe there quote around, better use addslashes() $question , $answer variables '$email', '".addslashes($question)."', '&quo

c++ - Why expressions a() and (****&a)() call the same function? -

this question has answer here: why function pointer definitions work number of ampersands '&' or asterisks '*'? 2 answers function variable instead of pointer function 4 answers there code: void a() { } int main(){ a(); (****&a)(); return 0; } how happen statement (****&a)(); has same effect a(); ? it's because of function-to-pointer conversion (§4.3): an lvalue of function type t can converted prvalue of type “pointer t .” result pointer function. &a first gives pointer a . dereference * giving function itself. attempt dereference function, since can't, undergoes function-to-pointer conversion pointer again. dereference pointer * , , on. in end (****&a) denotes function a , call it, since can a

c# - What is the return type for an Event in .NET? -

i know what's default return type event: says event has not return type; others says event has return type. thanks. it depends on type of delegate declare event with. "typical" events declared delegate of type eventhandler or eventhandler<teventargs> returns void , nothing forbids declaring event different type of delegate... if not principle of least surprise (pols). "typical": public event eventhandler myvoidevent; "custom": public delegate bool mybooldelegate(object sender, eventargs e); public event mybooldelegate myboolevent; normally put "return values" in eventargs object, that's why events don't need return values... can if they're told to.

android - APK lost 30% of filesize -

i changed w8 - installed eclipse x64 , imported workspace. after running app saw .apk file lost ~30% of filesize. im little confused. checked project-files seems fine. can tell me how happend? maybe new java/eclipse version? auto cleanup task? thanks

regex - Automatically paraphrasing sentences in Java -

in java, i'm trying automatically paraphrase text using regular expressions. so i'll need find way replace first match of regular expression randomly generated match of regular expression, this: public static string paraphraseusingregularexpression(string texttoparaphrase, string regextouse){ //in texttoparaphrase, replace first match of regextouse randomly generated match of regextouse, , return modified string. } so how can replace first match of regular expression in string randomly generated match of regular expression? (perhaps library called xeger useful purpose.) for example, paraphraseusingregularexpression("i happy today", "(very|extremely) (happy|joyful) (today|at (moment|time|instant in time))"); replace first match of regular expression randomly generated match of regular expression, produce output "i extremely joyful @ moment in time" , or "i happy @ time" . you can steps bellow: first, split text

android - Parsing JSON to Array Map Produces "The local variable may not have been initialized" -

i'm following tutorial ( http://mobile.dzone.com/news/android-tutorial-how-parse ) how ever // add items doddataitemobj dataitem string - string publiceventtype = d.getstring(publiceventtype); saying local variable publiceventtype may not have been initialized. points line jsonobject d = dataitems.getjsonobject(i); believe defined. i've tried no luck public string d; produces error code have mentioned. i'd appreciate thoughts. import java.io.bufferedreader; import java.io.inputstream; import java.io.inputstreamreader; import java.util.arraylist; import java.util.hashmap; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.util.log; public class parsejson { { // hashmap listview

html - Three things I don't understand about this javascript calculator -

hey i'm new javascript , wondering bit of code never saw , wondering how worked practice javascript wanted make calculator , got code online wondering 3 things. how code know output number , answer text box. how line of code work? calc.input.value know calc form input input , value value of input 1 2 or 3 how in know input i'm choosing? what calc.input.value = eval(calc.input.value) , how work? thanks time , have nice day , sorry if didn't give enough info. <form name="calc"> <table border=4> <tr> <td> <input type="text" name="input" size="16"> <br> </td> </tr> <tr> <td> <input type="button" name="one" value=" 1 " onclick="calc.input.value += '1'"> <input type="button" name="two" value=" 2 " onclick="calc.input.value += '2'"> <input type=

emacs stop scrolling after screen full of text using -

i new emacs user , feel uncomfortable when scroll buffer using mouse in emacs. keep scrolling, emacs stops when last line of buffer hits top visible row. though minibuffer screams end of buffer, scrolling keeps going on, annoying. how can make emacs behave other editor/browser while scrolling using mouse? try adding .emacs ( ~/.emacs ). works me on osx. more info here ;; scroll 1 line @ time (less "jumpy" defaults) (setq mouse-wheel-scroll-amount '(1 ((shift) . 1))) ;; 1 line @ time (setq mouse-wheel-progressive-speed nil) ;; don't accelerate scrolling (setq mouse-wheel-follow-mouse 't) ;; scroll window under mouse (setq scroll-step 1) ;; keyboard scroll 1 line @ time

sql - SELECT from one table, JOIN on another table, ORDER BY a third table? -

i have 3 tables forum application creating: boards - represents collection of posts, is_deleted boolean posts - represents text collection of comments comments - represents text my goal display number of posts boards not marked deleted, ordered last comment made post (and when post created). current query have is: select posts.*, (select created_date comments comments.post_id = posts.id order comments.created_date desc limit 1) last_comment posts join boards on boards.id = posts.board_id boards.is_deleted = 0 order last_comment desc, posts.created_date desc limit 4 offset 0 which works well, don't need last_comment other when use order results, feels i'm running additional select little reason. there better way this? edit 2013-05-18: fooling around bit more, believe have query doesn't rely on nested select statements: select posts.* posts join boards on boards.id = posts.board_id left outer join comments on posts.id = com

Python keep whitespace in a string -

how can keep white space in string? i have string piece = "**\n *\n *" ** * * and want print in center, use function, doesn't keep white space print '\n'.join('{0:^20}'.format(x, 'centered') x in piece.split('\n')) ** * * i had output * * ** insert move w piece before centring * *** * *** insert move w piece before centring ** * * ** * * as can see second move right when print on center wrong in python 3 getting : >>> print ('\n'.join('{0:^20}'.format(x, 'centered') x in piece.split('\n')) ) ** * * >>>

php explode mysql row -

i have looked unable find answer need. i trying explode row in mysql containt multiple banner file names. <?php $str = 'one|two|three|four'; // positive limit print_r(explode('|', $str, 2)); // negative limit (since php 5.1) print_r(explode('|', $str, -1)); ?> i took code php tutorial website. possible use form of echo command print file names in there mysql row. eg doesnt work is <?php include '../connect/dbseries.php' ?> <?php include 'sbarray.php' ?> <a href="series.php">back</a> <?php $str = print' . $row[bannerfilenames] .'; // positive limit print_r(explode('|', $str, 2)); ?> thanks in advance aaron to print filenames in $row['bannerfilenames'] , either loop: $names = explode ("|", $row['bannerfilenames']); foreach ($names $name) echo "$name <br />"; or print them in line separated , instead of | implod

JavaScript -- trying to use a loop to delete certain items in an array, but it deletes all items -

i first tried foreach loop delete items array, later learned shouldn't this. tried make 1 normal loop. cycle through array containing bullets, , delete them when go outside game area. for (i = 0; < playerbullets.length; i++) { console.log(playerbullets[i].x); console.log(playerbullets[i]); if (playerbullets[i].x > 800 || playerbullets[i].x < 0 || playerbullets[i].y > 600 || playerbullets[i].y < 0 ) { playerbullets.splice(i); } } the console correctly shows [i] in full, , brings list of contents of array. however, [i].x console log displays 1 value, rather "x" value of each object in array. then first bullet goes out of bounds, bullets disappear. frustrating, , highly ineffective killing zombies. i have tried looping backwards through loop, seems recommended way tells me undefined. any ideas? feel i'm making simple error, because i'm using same structure code on tutorial sites, "should work". thank you! you sho

MySQL - Getting Top n records and ordering by a specific column with pagination -

i have got problem getting top n records database , ordering them specific column , paginating them. for example want first 100 movies movie table , order these first 100 records name , display 10 records per page. however doesn't work; select name movies order id desc, name desc, limit 0,10 i quite confused here. in order paginate have use limit in such ways; limit 0,10 = first page limit 10,20 = second page and on. in order first records, use order id desc when want list z a, order id desc, name desc doesn't trick. in words want first (latest) 100 records out of 10.000 , order 100 records name (asc or desc) , / or view (asc or desc). i hope clear enough explain problem. i glad if me out one. shift order of order by statements (updated) select name ( select * movies order id desc limit 100 ) order name desc limit 0,10 it uses first 1 first , if equal looks @ next one

Actionbar on Android 2.3.6 -

i have been asked @ getting existing app working on android phone running andrdoid 2.3.6 ( api 10? ). the app used ics actionbar, there way of doing api 10? dont think actionbar sherlock goes down api level. i dont think actionbar sherlock goes down api level. no, abs supports android 2.0 (api 5) upwards.

symfony - Why is Doctrine joining this entity onto itself? (Not unique table/alias) -

i have entity named 'tile', manytomany relationship entity named 'coins'. /** * @orm\manytomany(targetentity="coin") * @orm\jointable(name="coin", * joincolumns={@orm\joincolumn(name="tile_id", referencedcolumnname="tile_id")}, * inversejoincolumns={@orm\joincolumn(name="coin_id", referencedcolumnname="coin_id")} * ) **/ protected $coins; i have page lists tiles , of associated coins. there can lot of coins , tiles on page , using lazy loading can put 100-300 database queries on single page. trying avoid using leftjoin. public function getusertiles($id) { $qb = $this->createquerybuilder('b') ->select('b', 'z') ->leftjoin('b.coins', 'z') ->leftjoin('z.userinfo', 'u') ->add('where', "b.userid = ".$id." , b.status = 'completed'

javascript - jQuery dataTables with Codeigniter and sAjaxSource -

i using datatables codeigniter , have problem. getting message: array_push() expects parameter 1 array, null given and result {"aadata":null} i want this: { "aadata": [ ["test","test","test"] ] } code: $result = $this->lol_model->get(); //result = array ( [0] => stdclass object ( [test] => 12345 [test2] => 1842 07 03 [test3] => lol ) ) $aadata = array(); foreach($result $row) { array_push($json["aadata"],array( $row->test, $row->test2, $row->test3 )); } echo json_encode($json); you cannot define key '["aadata"]' when using array_push. however, can use: $json["aadata"]=array( $row->test, $row->test2, $row->test3 ); see post also: array_push() key value pair

android ndk - C: Passing floating point to function -

given following... void test(){ float = 0.7f; logd("width %.1f",0.7f); logd("width %.1f",a); fark(a); } void fark(float test){ logd("width %.1f",test); } this outputs.... 05-18 22:35:25.215: d/native(8241): width 0.7 05-18 22:35:25.215: d/native(8241): width 0.7 05-18 22:35:25.215: d/native(8241): width 36893488147419103232.0 what missing last one? you need declare fark before using it. specified in section 6.5.2.2, paragraph 6: if expression denotes called function has type not include prototype, integer promotions performed on each argument, and arguments have type float promoted double . these called default argument promotions . (bold emphasis added me). note defining fark type incompatible implicitly assumed type constraint violation , requires compiler emit diagnostic message if call , definition in same translation unit. gcc warns then, clang rejects code [ error: conflicting types 'fa

Python For loop range by step with step increments -

i wasn't sure how word this, , it's basic feel idiot. i'm new programming , trying figure out how create text file has header task shows range of loop step , followed multiple tasks have sequential range of header per task. how fit range of loop each sub task doesn't incrementally go up. help. here's bad code: #!/usr/bin/python list = [] i, x in enumerate(range(1,15,4)): test = range(x,max(0,min((x+4),16))) list.append(test) foo = """ task -title{%(start)s:%(end)s} %(child)s """ foo2 = """ task -title{%(frame)s} -stuff """ addtask = "" addtask2 = "" in list: first = i[0] last = i[len(i)-1] x in i: frm = foo2 % {"frame":x} addtask2+=(frm) new = foo % {"start":first,"end":last,"child":addtask2} addtask+=(new) f = open("/tmp/test.txt","w") f.write(addt

javascript - Python HTML getElementsByClassName alike manipulate on file content -

i have saved source code of page file using sikuli. need "roundup" on batch of matrix style placed elements. don't want calculate dimensions between them. want urls type in location bar. wrote scratch of mzdn javascript implementation of such "simple" operation. don't want use lxml. want real native libraries - mean need "portable" script. i've googled while , decided ask question @ stack overflow. don't want use split('<a href=') magic. in python(in pythonic way): var array = document.getelementsbyclassname('another') var j = array.length (i=0;i<j;i++) { element = array[i]; url = element.getelementsbytagname('a')[0].href; console.log(url); } var array = document.getelementsbyclassname('else') var j = array.length (i=0;i<j;i++) { element = array[i]; url = element.getelementsbytagname('a')[0].href; console.log(url); } managed split . python kids.

iis - ASP.NET Cookies BUG - multiple cookies duplicated randomly? -

it seems there annoying bug in asp.net cookie handling during writing of response-stream wire. set-cookie headers multiplied randomly. my example setup is: asp.net mvc4 on iis8 express server, same issue happens on iis7 integrated mode , , found posts same issue iis6 in 2009. seem issue exists while. for example, in global.asax.cs subscribe beginrequest event , write httpresponse.cookie collection in event handler: public class mvcapplication : system.web.httpapplication { public override void init() { base.init(); beginrequest += onbeginrequest; } void onbeginrequest(object sender, eventargs e) { response.cookies.set(new httpcookie("onbeginrequest", "0")); } } this will, already, output "onbeginrequest" set-cookie header twice. but, if similar done httpapplication events (authenticaterequest, acquirerequeststate, etc... total ~20 events), header of http response sent browser have lot of dupl

objective c - Some C functions in iOS duplicated as #define -

c functions memcpy , memset available c functions #define in ios: for example #define memcpy, under hood, is: #define memcpy(dest, src, len) \ ((__darwin_obsz0 (dest) != (size_t) -1) \ ? __builtin___memcpy_chk (dest, src, len, __darwin_obsz0 (dest)) \ : __inline_memcpy_chk (dest, src, len)) i gather there memory checking here can shed additional details on why better memcpy alone (where value added)? more importantly, when use which? unless #undef macro, or call (memcpy)(args...) , use macro variant. i use maco - it's intended fast , efficient, , work expect.

AngularJS - controller and factory - where am I going wrong? -

i'm new angular , cannot pinpoint going wrong. i'm trying inject factory controller, reference said controller within html , use ng-repeat present data. can't work solely using handlebars , excluding ng-repeat. i'm here see if there glaringly wrong code i'm missing. i've been going through 2 separate tutorials hang on , sure had it. guess not though. html: <html data-ng-app='theapp'> <div class='siderow' data-ng-controller='maintagcontroller'> <div class='siderowlabel'>tags</div> <div class='siderowdata'> <a href='page.html' class='bluelink' data-ng-repeat='maintag in maintags'>{{ maintag }}</a> </div> </div> js: /// <reference path="../../vendor/angular.min.js" /> var theapp = angular.module('theapp', []); theapp.factory('maintagfactory', function() { var maintags = [ { mainta

Objective-C atomic operations/locking access to myLocation property in Google Maps iOS SDK -

this partly question regarding google maps sdk in ios, though perhaps question atomic operations in objective-c. in app, wish draw gmspolyline on map between user's current location , selected destination. can retrieve user's current location using mylocation property on gmsmapview . according documentation mylocation : if location enabled, reveals user location dot being drawn. if disabled, or enabled no location data available, nil. property observable using kvo. i have code draw polyline takes form: if (mymapview.mylocation) { // draw polyline between mymapview.mylocation , selected destination } my concern that, remote possibility, between check if (mymapview.mylocation) , drawing polyline // draw polyline between mymapview.mylocation , selected destination , mymapview.mylocation might become nil if location lost @ inopportune moment. so question is, in objective-c, there way me wrap both check mymapview.mylocation not nil , drawing

Can't update the database after click on the submit button in servlet jsp -

i can't update database after clicking on submit button in servlet jsp. index.jsp <%@page import="java.sql.*"%> <%@page import="java.sql.drivermanager"%> <%@page import="java.sql.connection"%> <%@page contenttype="text/html" pageencoding="utf-8"%> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> </head> <body> <% try{ class.forname("com.mysql.jdbc.driver"); connection con = drivermanager.getconnection("jdbc:mysql://localhost:3306/xigmapro","root",""); statement st=con.createstatement(); resultset rs1=st.executequery("select * user_information"); %> <table border="1"> <tr> <td width="120">user name<

ruby on rails - Does a before_filter in the application controller slow down the app? -

i have few before_filter in application controller check 1) if current_user banned, 2) if current_user has received new message , 3) if current_user has pending friend requests. this means before every request app check these things. cause server issues in future, possible server overload? i wouldn't create server overload on it's own, server overload need many concurrent requests , rails have connection pool database out of box, slow down process have 3 queries before each request @ controller intended do. facebook solved @ 2009 using called bigpipe, not new technology rather leveraging browsers , ability send few requests fragmented parts of page , compose using javascript. you can have read here http://www.facebook.com/note.php?note_id=389414033919 . as check if user banned, yes you'd have check either way, perhaps can have in cache using memcached or redis won't hit database directly every time.

networking - Detect TCP connection/disconnection in Delphi -

my application has server form includes stringgrid. server allows 4 clients connected @ once. add tcp connections client-side while list not full. when new client requests tcp connection server , list full, server should check clients in list see if still connected. if clients still connected , list full, reject new client. if 1 or more clients no longer connected, accept new client, add list , update list. how know clients still connect or not? you should not checking dead clients @ time when new client wants connect. should set server's maxconnections property 4 prevent new connections while list full regardless of state of already-connected clients, , check dead clients periodically while connected using protocol-level heartbeats or tcp-level keepalives. if heartbeat/keepalive errors or times out, disconnect client , remove list, allowing new client connect.

java - Could Not convert socket to TLS -

i trying send email using java servlets in eclipse ide. code. final string username = "******@gmail.com"; final string password = "******"; properties props = new properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.ssl.trust", "smtpserver"); session session1 = session.getinstance(props, new javax.mail.authenticator() { protected passwordauthentication getpasswordauthentication() { return new passwordauthentication(username, password); } }); try { if(result) { message message = new mimemessage(session1); message.setfrom(new internetaddress("******60@gmail.com")); message.s

c# - Unable to set NiceEditor content in Web Browser COntrol -

i using niceedtor on web browser control. on jquery ready() function trying set content of , in result following error: object doesn't support property or method 'setcontent' below given code: $(function () { var nice = new niceditors.findeditor('__edit'); nice.setcontent("<b>hi</b>"); }); text area defined following: <textarea name="question" rows="15" cols="130" id="__edit"></textarea> you need instantiate textarea niceeditor control using niceditors.alltextareas(); or new niceditor().panelinstance('__edit'); . $(function () { //niceditors.alltextareas(); // set globally textareas. new niceditor().panelinstance('__edit'); // redister textarea niceeditor ///... code var nice = new niceditors.findeditor('__edit'); nice.setcontent("<b>hi</b>"); }); demo documentation

How do I use Ruby's new lambda syntax? -

ruby has lambda syntax, can use -> symbol: a = 0 new -> { < 5 } puts += 1 end this works well, when try this: match "/", to: -> { |e| [404, {}, ["hello! micro rack app"]] }, via: [:get] match( "/", to: -> { |e| [404, {}, ["hello! micro rack app"]] }, via: [:get] ) match( "/", { to: -> { |e| [404, {}, ["hello! micro rack app"]] }, via: [:get] }) all of return same syntax error: $ ruby -c -e 'match( "/", to: -> { |e| [404, {}, ["hello! micro rack app"]] }, via: [:get] )' -e:1: syntax error, unexpected '|' match( "/", to: -> { |e| [404, {}, ["hello! mi... am missing something? i think new syntax should be match "/", to: ->(e) { [404, {}, ["hello! micro rack app"]] }, via: [:get]

jQuery datatables wrong get column in drag and drop -

in datatables want find first column when dragging row , find first column in dropping row. below code wrong result in drag , drop rows, please me change thst var startposition; var endposition; var old; var newc ; $("#example tbody").sortable({ cursor: "move", start:function(event, ui){ var ntds = $('td', this); old = $(ntds[0]).text() ; }, update: function(event, ui) { endposition = ui.item.prevall().length + 1; var newc = ui.item.context.children[0].innerhtml; alert('old: ' + old + ' newc: ' + newc); } }); get td of first column var ntds = $('tr td:first', this);

android - EditText always showing null -

my xml <textview android:id="@+id/newplacelatlable" android:text="place latitude" android:layout_width="150dp" android:layout_height="40dp" android:layout_below="@id/newplacelable"/> <edittext android:id="@+id/newplacelat" android:layout_width="150dp" android:layout_height="40dp" android:layout_torightof="@id/newplacelatlable" android:layout_below="@id/newplacelable" android:inputtype="numberdecimal" /> <textview android:id="@+id/newplacelonlable" android:text="place longitude" android:layout_width="150dp" android:layout_height="40dp" android:layout_below="@id/newplacelatlable"/> <edittext android:id="@+id/newplacelon" android:l

r - Printing plot depending on variable conditions on 2 pdf pages -

i'am trying print plot, depending on variable 12 terms. plot result of cluster classification on sequences, using om distance. i print plot on 1 pdf page : pdf("yyy.pdf", height=11,width=20) seqiplot(xxx.seq, group=xxx$variable, cex.legend = 2, cex.plot = 1.5, border = na, sortv =xxx.om) dev.off() but printing small ... try print on 2 pages, : pdf("yyy.pdf", height=11,width=20) seqiplot(xxx.seq, group=xxx$variable, variable="1":"6", cex.legend = 2, cex.plot = 1.5, border = na, sortv =xxx.om) seqiplot(xxx.seq, group=xxx$variable, variable="7":"12", cex.legend = 2, cex.plot = 1.5, border = na, sortv = xxx.om) dev.off() but doesn't work ... know how can ask r separate terms' variables 2 groups, print 6 graphics per pdf page ? the solution plot separately subset of groups want on each page. here example using biofam data provided traminer . group variable p02r04 religious participation takes 1

Simple mercurial webdev repo setup: features vs. fixes -

i have inherited mercurial system basic web site, i’m new mercurial , temporary site babysitter until find lot more competent me. in meanwhile, use pointers on how can keep our feature development separate quick bug fixes. currently, have 3 basic environments: individual developer environments, staging, , production. each environment has own local mercurial repo. single bitbucket repo acts master repo every environment pushes , pulls from. the problem when working on code unfinished needs submit quick bug fix needs deployed quickly. if developer has committed changes unfinished code , commits quick bug fix , push, code goes bitbucket repo. judging i’ve researched far, can development bitbucket repo (for slower development) , “stable” bitbucket repo (for fixes need happen now) in situation, on our dev machines, we’d of our slower dev code in our local dev repo cloned local stable repo. when wanted share unfinished code, we’d push/pull bitbucket dev. other developers push/pul

java - Using EhCache as the main Datatasource instead of Database -

is reliable use ehcache datasource instead of database ? my business functionality periodically collect information running application , store in ehcache cache , retrieve , display statistics collected information querying cache ehcache search api. cache nee keep last 30-45 days of data. what think approah? ehcache acceptable solution - assuming tti, ttl , other params set according business needs. there shouldn't reliability issue per se. sql database affords options transactional commits, complex queries , relational support aren't provided of course of ehcache itself.

javascript - GruntJS, Multiple Tasks and grunt.option -

i starting use gruntjs 1 of projects. have accomplished write simple build script using simple aliases. however script contains many tasks same, difference parameters source folder , destination folder. for example: sass: { options:{ trace: true, debuginfo: true, style: 'compressed' }, html: { files: { 'build/html/css/main.css': 'sass/html.sass' } }, html2: { files: { 'build/html2/css/main.css': 'sass/html2.sass' } }, html3: { files: { 'build/html3/css/main.css': 'sass/html3.sass' } } } what achieve have 1 task , pass parameters (dest,src) task. i tried implement using multitasks: grunt.registertask('sass2', 'run sass compilation tasks.', function() { var projects = ['

postgresql - How to "not include" some piece in regex pattern -

given string 12,.34.56 i need split string point ( . ), these points, previous character not comma ( , ) that is, string above, must retrieve result 12,.34 56 i trying this: select regexp_split_to_table('12,.34.56', e'[^,]\\\.') this returns: 12,.3 56 as see, symbol 4 removed, reason understood: [^,] means "some symbol" except comma, , in case, "some symbol" turned 4 question: how prevent this? how not include piece: [^,] in pattern? since not supported postgres regular expressions, workaround replace ,. (unique) combination of characters , later convert back: select replace(unnest(string_to_array( replace('12,.34.56.78,.34', ',.','~^~'), '.')), '~^~', ',.') i using unnest(sting_to_array()) instead of regexp_split_to_table() because has shown scale better.

javascript - How to transfer contents of one table to another in struts 2? -

i have 2 tables displaying 2 lists. jsp <%@page contenttype="text/html;charset=utf-8"language="java"pageencoding="utf-8"%> <%@taglib prefix="s"uri="/struts-tags"%> <!doctype html public"-//w3c//dtd xhtml 1.0 transitional//en""http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>insert title here</title> </head> <body> <s:form name="tableform"method="post"> <th> <s:submit action="verify" key="add"></s:submit> </th> <table id="one"> <thead> <tr> <th ></th> <th> id</th> <th>name</th> <th>status</th> <th>type</th> <th>rollup type<