Posts

Showing posts from April, 2012

Ruby on Rails gem to make passwords more secure? -

i built ruby on rails authentication system scratch , works great. (i aware of existence of devise , yet wanted write own system better grasp of ruby on rails in general.) the thing worries me users pick words dictionaries, sequential numbers (e.g. "12345679"), own user names, or all-time classic "password" own password . is there gem validates against of those? or have work regular expressions here? thanks help. stong_password gem cool. though may not contain looking for, still pretty gem

hibernate - OptimisticLock Trying update the same object again -

i'm getting below exception: org.hibernate.staleobjectstateexception: row updated or deleted transaction (or unsaved-value mapping incorrect): [ it happens when try update object using form again. in first time works when try update same object again got exception. could flush in session ? here entity @persistencecontext(unitname = "jpaservice", type = persistencecontexttype.extended) private entitymanager nasc; here service: @stateless @transactionattribute(transactionattributetype.required) @transactionmanagement(transactionmanagementtype.container) thank you! optimistic locking works following way: have version field in entity (annotated @version ). load entity, , (for example), version field has value 33. save entity. hibernate checks version value in entity (33) matches 1 in table. if not, throws exception. if match, increments versions, in entity , in database. so, if save entity once again, still gets values

php - Wordpress Custom Fields and Images that don't exist -

i have page ( http://schroeder.s482.sureserver.com/york-family-farm/ ) photo gallery generated uploaded photos using advanced custom fields plugin. there 1 photo in particular page, other pages have 21 photos. there way have show images there? here code i'm using display it: <a href="<?php the_field('featuredimage'); ?>" target="_blank"> <img src="<?php the_field('featuredimage'); ?>" width="290px" height="217px" id="ffs-pic"> </a> thanks much! love learning guys! i'm guessing 'featuredimage' field created using advanced custom fields plugin. assuming that's case, have few choices. still using free version, can create 20 more image fields , name them 'image2', 'image3', 'image4', etc... insert them template same way displaying 'featuredimage'. has obvious downside have manually create everyth

java - Get raw HTML in servlet to churn out a PDF file -

i have jsp rendered after forwarded servlet. have html jsp want post page in order generate pdf. as per understanding submit button submits form. but, need submit raw html use flyingsaucer or similiar pdf creator library. what way use html , save pdf file? please chime in correct if wrong , think approach. advice appreciated. edit: sorry have posted no code @ moment have hit wall in servlet in quest around this. you've 2 options: let js set current html dom tree (hidden) request parameter on submit. <form method="post" action="pdfservlet"> <input type="hidden" name="source" /> <input type="submit" value="generate" onclick="this.form.source.value = document.documentelement.outerhtml;" /> </form> it's in pdfservlet available request.getparameter("source") . let pdfservlet request desired page programmatically using url / urlconnection .

MySQL INSERT fails in Python but works fine in MySQL Workbench -

here query have runs fine in mysql workbench included sample values , works fine if manually plug in values in code, fails when use values parameters. ideas? python code: print player cur.execute(""" insert scoredata (gameid, playerid, starter, pos, min, fgm, fga, tpm, tpa, ftm, fta, oreb, reb, ast, stl, blk, tos, pf, pts) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s); """), (player[0], int(player[20]), int(player[19]), player[3], int(player[4]), int(player[5]), int(player[6]), int(player[7]),

Cannot set option value in select programmatically using AngularJs -

the select : select(ng-model="elid", ng-change="load(elid)", ng-options="e._id e.name e in options") option(value="") - select mashup - controller : the following works, select gets populated. using broadcasts because comes socket.. don't mind that. //receive list $scope.$on('list:refresh', function(ev, data) { $scope.options = data }) the following works if did not manually select option before. data.id valid entry in list. //refresh list of mashups when new 1 has been created $scope.$on('list:select', function (ev, data) { $scope.elid = data.id }) if manually select option, , list:select fires, $scope.elid udated <select> not highlight option. what going on? solved: the select : select(ng-model="data.elid", ng-change="load()", ng-options="e._id e.name e in options") option(value="") - select mashup - controller

java - How can I convert List<List<String>> into String[][]? -

in project have list contains list s of string s ( list<list<string>> ) , have convert list array of string arrays ( string[][] ). if had single list<string> (for example mylist ) convert string[] : string[] myarray = new string[mylist.size()]; myarray = mylist.toarray(myarray); but in case have lots of list of string inside list (of list of string s). how can this? i've spent lots of time didn't find solution.. i wrote generic utility method few days own usage, converts list<list<t>> t[][] . here's method. can use purpose: public static <t> t[][] multilisttoarray(final list<list<t>> listoflist, final class<t> classz) { final t[][] array = (t[][]) array.newinstance(classz, listoflist.size(), 0); (int = 0; < listoflist.size(); i++) { array[i] = listoflist.get(i).toarray((t[]) array.newinstance(classz, listoflist.get(i).size()));

javascript - MVC 4 button onClick that is calling razor function -

i have mvc 4 application. here case: 1. model hashkey - containing 1 string key 2. model modelobjecta - object transport. 3. class - generate unique key on request , put in tempdata along given modelobjecta , returns unique key. 4. controller controllermodelobjecta - serve as pure controller. 5. view showallmodelobjecta - view page display collection controller. how works. have request navigate showallmodelobjecta. controller call class object transfer , sends unique key showallmodelobjecta. view calls method (not httpget) object coresponding received key controller. collection of object received , in @foreach loop disassembles objects , put them in table. along object in table putted 3 buttons represents different functions (view details, edit, delete) corresponding object. the problem : on each object`s button have use @functions call classa , send object itself, on click not on loop. here code (i have change names :) ) @functions{ public string buttonclicked(

javascript - Regex to detect urls without www and http -

could update regex match next requirements must match urls without www , http if query contains - match too url ends when space or comma(,) or string end meet match topleveldomains list var srg = new regexp(/(^|[\s])([\w\.]+\.(com|cc|net))/ig); for sample, must match: jsfiddle.net jmitty.cc:8080/test3s.html www.ru,sample.com,google.com/?l=en very.secure.dotster.com/i?ewe as result need <a>jsfiddle.net</a> <a>jmitty.cc:8080/test3s.html</a> <a>www.ru</a>,<a>sample.com</a>,<a>google.com/?l=en</a> <a>very.secure.dotster.com/i?ewe</a> fiddle http://jsfiddle.net/tynu7/ well, guess can change little things in regex: ([\w\.]+\.(?:com|cc|net|ru)[^,\s]*) replace by: <a href="$1" target="_blank">$1</a> i'm not sure why having (^|[\s]) @ beginning , didn't seem useful me, removed it. if had reasons, can put back. i added ru extensions match www

performance - Does chaining LINQ statements result in multiple iterations? -

does chaining linq statements result in multiple iterations? for example, let's want filter data clause, , on matches sum: int total = data.where(item => item.alpha == 1 && item.beta == 2) .sum(item => item.qty); does result in single interation of data, such equivalent this? int total = 0; foreach (var item in data) if (item.alpha == 1 && item.beta == 2) total += 1; or, iterate on data once, , results of where second time sum? the statements in linq streamed, where not run until sum enumerates through values. means items data enumerated single time. basically, where method creates new ienumerable<t> , doesn't enumerate through data . sum foreach on ienumerable<t> where , in turn pulls items through where sequence 1 @ time.

javascript - node.js export module function -

i have problem node.js. creating blog , have 2 archives: sessions.js users.js in sessions.js : function sessionsdao(db) { this.startsession = function(username, callback) {....} } module.exports.sessionsdao = sessionsdao; in users.js var session = require('./sessions'); var s = new session(); s.startsession(username); but shows me error: object not function typeerror: object not function require returns exports object, so: var sessionsdao = require('./sessions').sessionsdao; var s = new sessionsdao(); s.startsession(username);

How to call Jekyll commands from Ruby -

i have rails app creates/builds jekyll sites on same server. right now, i'm calling jekyll commands backticks this: def build_jekyll result = `jekyll build -s /some/source/path -d /some/dest/path` end this works fine feels little un-ruby like. if jekyll gem in rails gemfile, is there way can build jekyll site using ruby? (from docs, looks call jekyll::commands::build.build i'm not sure how initialize site parameter). tl;dr require 'jekyll' conf = jekyll.configuration({ 'source' => 'path/to/source', 'destination' => 'path/to/destination' }) jekyll::site.new(conf).process but how did find out? i figured out looking @ the source code . when run jekyll build , enter source file bin/jekyll . interesting part here is command :build |c| # ommitted c.action |args, options| options = normalize_options(options.__hash__) options = jekyll.configuration(options) jekyll::commands::build.

What is the voltage used to power the stm32 in the Sony smartwatch -

the stm32 datasheet says number of wait states reading flash memory have configured based on voltage used power microcontroller, , frequency. when running @ 120mhz, assuming voltage higher 2.7v configured 3 wait states microcontroller crashes under high cpu load. i see (based on https://github.com/underverk/smartwatch_toolchain/blob/master/src/driver_power.c ) there's power management unit powers microcontroller, although sony's site doesn't acknowledge existence. voltage used power microcontroller? the micro controller fed 1.8v. when in dfu-mode, changed 3.3v.

pymongo - MongoDB: Removing a field from ALL subdocuments in an array field -

i have thousands of documents in format: { "_id" : objectid("51e98d196b01c2085c72d731"), "messages" : [ { "_id" : objectid("520167056b01c20bb9eee987"), "id" : objectid("520167056b01c20bb9eee987"), }, { "_id" : objectid("520167056b01c20bb9eee988"), "id" : objectid("520167056b01c20bb9eee988"), }, { "_id" : objectid("520167056b01c20bb9eee989"), "id" : objectid("520167056b01c20bb9eee989"), } ], } i need remove duplicate "id" field. have tried: db.forum_threads.update({}, {$unset: {"messages.$.id": 1}}, {multi: true}); this error getting: cannot apply positional operator without corresponding query field containing array. the reason you're getting error because don't have predicate in filter clause. can this: mongos&g

sql - Get Time difference between group of records -

i have table following structure id activitytime status 19 2013-08-23 14:52 1 19 2013-08-23 14:50 1 19 2013-08-23 14:45 2 19 2013-08-23 14:35 2 19 2013-08-23 14:32 1 19 2013-08-23 14:30 1 19 2013-08-23 14:25 2 19 2013-08-23 14:22 2 53 2013-08-23 14:59 1 53 2013-08-23 14:56 1 53 2013-08-23 14:57 1 53 2013-08-23 14:52 2 53 2013-08-23 14:50 2 53 2013-08-23 14:49 2 53 2013-08-23 14:18 2 53 2013-08-23 14:30 1 i want calculate total time difference each id against status 2. example id 19 stayed on status 2 14:35 14:50 (15 minutes), 14:22 14:30 (8 minutes). total id 19 stayed on status 2 23 minutes. (in both cases considered minimum time status 2 status 1) the problem is how inc

Analyzing how noisy a data set using Excel -

i have set of data has on 15,000 records in excel measurement tool finds trends on large areas. i'm not interested in looking trends within data whole rather on data closest each other sense of how noisy (variation neighboring records). want know average standard deviation of looking @ 15,000 or records @ 20 records @ time. hope data values trend gradually rather sudden changes record record , looks noisy. if add chart , use "moving average" trendline kind of visually shows how noisy data looks across 15,000 + records. however, hoping numeric value rate how noisy data vs. other datasets. ideas on here formula's built-in excel or adding add-in? let me know if need explain better. could calculate moving average 20 sample window, use difference between each point , expected value calculate variance? hard tables here, here sample of mean actual measured expected variance 5 5.44 4.49 0.91 6 4.34 5.84 2.26 7

iphone - How to animate UITableViewCell XIB-subclass contents when in editing mode? -

i have uitableviewcell created in xib , hooked .h , .m. cell being displayed in uitableview needs ability go editing mode. when goes editing mode, however, cell contents don't move or resize. also, if , when delete button appears, contents not shift. realize similar questions have been asked here, haven't found had correct answer or answer specific situation.

java - Eclipse WTP installation fails "Cannot complete the install because one or more required items could not be found" -

i followed answer's instructions here issue persists. have juno , trying download wtp sdk 3.1.2 (not sure if that's i'm supposed download. tried other things none worked) here , , error message cannot complete install because 1 or more required items not found. software being installed: jst enterprise plug-in developer resources 3.1.1.v200908101600-771184eahsuujtw3ue6zhbiyv8tu (org.eclipse.jst.enterprise_sdk.feature.feature.group 3.1.1.v200908101600-771184eahsuujtw3ue6zhbiyv8tu) missing requirement: j2ee core component 1.1.301.v200908181930 (org.eclipse.jst.j2ee.core 1.1.301.v200908181930) requires 'bundle com.ibm.icu [3.4.4,4.1.0)' not found missing requirement: j2ee core component 1.1.301.v200911302230 (org.eclipse.jst.j2ee.core 1.1.301.v200911302230) requires 'bundle com.ibm.icu [3.4.4,4.1.0)' not found cannot satisfy dependency: from: wtp ejb ui plug-in 1.1.301.v200908131325 (org.eclipse.jst.ejb.ui 1.1.301.v200908131325) to: bundle

Writing on the same line in FORTRAN -

in fortran, each time 1 uses write new line produced. in order control working of program being executed, write on screen current value of variable, on same line (erasing previous value , starting @ beginning of line). is, like 1 continue "update value of a" write(*,*) backspace "screen" goto 1 something write(*,*,advance='no') (incorrect anyway) not quite need: write values of a 1 after on long line. a trick shown want follows do l=1,lmax ...update a... write(*,'(1a1,<type>,$)') char(13), enddo where <type> format specifier a (i.e., i0 integer). the key char(13) , carriage return, , $ in format descriptor. don't know if there name $ , know works displaying on screen--for output file a on each line.

ios - Last Cell in UICollectionView is clipped -

i have uicollectionview displays vertical list of cells. it's tableview i'm using collection view more controller of how each cell placed in view. reason, last cell in collection view clipped. can drag see bottom half, let go collection view bounces place, obscuring bottom half of last cell. have xib contains collectionview, , register collection view cells xib. whole view placed in navigation controller programmatically. thoughts has issue autolayout. since i'm adding view controller containing collection view navigation controller programmatically, no constraints set between collection view , navigation bar. if hide instantiated navigation bar , drag 1 out in ib, collection view cell not clipped. don't want way. i've tried programmatically adding constraints, doesn't work either. have suggestions? here's how i'm creating navigation controller , placing view controller containing collection view it. also, code i've tried use add constraints incl

c# - Spring.Net / NHibernate - Multi Threading -

i'm using spring .net , fluent nhibernate in window application, , i'm working multiple threads. read in blogs , questions there can 1 session per thread, , i'm using hibernatedaosupport , currentsession it: public class daobase<t> : hibernatedaosupport, idaobase<t> { protected isession currentsession { { return sessionfactoryutils.getsession(hibernatetemplate.sessionfactory, true); } } } however, testing feature , must show sessions of each thread different sessions. how can it? obs: after research found objects obtained through nhibernate session, can not changed in session, example, can not find object in "session 1" , give update on same object in "session 2". but, in tests i'm getting object first thread , updating same in second thread, working. whats wrong? you've got backwards - thread can have how many nhibernate sessions likes. important thing session not design

ruby - Understanding CanCan initialize method -

i'm having hard time understanding how cancan works. have following model class ability include cancan::ability def initialize(user) if user && user.email == "jason@gmail.com" can :access, :rails_admin # allow admin users access rails admin can :dashboard # allow access dashboard end end end when comes rails_admin file in initializers folder railsadmin.config |config| config.authorize_with :cancan config.main_app_name = ['pr', 'admin'] config.current_user_method { } # auto-generated end i want have 1 user access admins dashboard email "jason@gmail.com", how cancan know signed in @ time? rely on helper method i'm missing? cancan uses current_ability method supply ability, and in uses current_user . know @ least devise has method, other auth frameworks must commonly supply too, not sure.

postgresql - Trigger vs. check constraint -

i want add field-level validation on table. there field named "account_number" , field should pass "luhn" check. i've found function called "luhn_verify" seems work (google if interested). returns boolean. question is: are there major performance advantages in postgresql using trigger validation vs. check constraint. additional information: postgresql 9.1 table not have insert trigger, have update. disclaimers: i feel has been answered, can't seem find distinct answer. if so, please mark duplicate , reference original question/answer. might better questions dba board. the rule of thumb use check constraint before resort triggers. a check constraint faster, simpler, more portable, needs less code , less error prone. triggers can circumvented other triggers, instance. triggers more complicated . use them when have to , more complex requirements. if check constraint restrictive case or causes trouble reloadin

bash - Output using awk in a pattern of svn log -

how modified , added files revision,author , comments svn log verbose in pattern: cat test: r7351 | user01 | 2013-07-02 17:53:28 -0400 (tue, 02 jul 2013) | 2 lines changed paths: d /trunk/demo/proj1/.project jira-125723 removing unwanted files ------------------------------------------------------------------------ ------------------------------------------------------------------------ r7352 | user02 | 2013-07-02 17:54:24 -0400 (tue, 02 jul 2013) | 2 lines changed paths: d /trunk/demo/proj2/320-test.ert jira-125723 removing unwanted files ------------------------------------------------------------------------ ------------------------------------------------------------------------ r7504 | user04 | 2013-07-08 14:26:36 -0400 (mon, 08 jul 2013) | 4 lines changed paths: m /trunk/demo/maven/sum.jsp m /trunk/demo/code/results.jsp jira-121639 wp-iqisu- lot of changes fix issue ------------------------------------------------------------------------ ------------

java - Jboss CLI: Expected [INT] but was STRING -

i making cli script add 2 attributes(max-post-size, max-save-post-size) http connector should looks like: <connector name="http" protocol="http/1.1" scheme="http" max-post-size="5120000000" max-save-post-size="1024000000" socket-binding="http"/> my command is: /subsystem=web/connector=https:add(socket-binding=http,scheme=http,protocol="http/1.1",max-post-size=5120000000, max-save-post-size=1024000000) but gives me "failure-description" => "jbas014688: wrong type max-post-size. expected [int] string", so confused how declare integer in cli, try max-post-size=[5120000000] , max-save-post-size=[1024000000] doesn't work given [standalone@localhost:9999 connector=http] cd /subsystem=web/connector=http the type of attribute int : [standalone@localhost:9999 connector=http] ls -l attribute value type [...] max-post-size 2120

Web API: JSON binds, XML doesn't on POST -

i have web api service (to surprise) needs able accept xml json. first, here models: [datacontract] public class serializedcustomerevent { [datamember] public string typeid { get; set; } [datamember] public contextpair[] context { get; set; } } public class contextpair { public string key { get; set; } public string value { get; set; } } here api controller method: public void post(serializedcustomerevent value) { _queuebroker.queue(value); } now here's part i'm overlooking something. json post fiddler works fine: content-type: application/json; charset=utf-8 { "typeid":"abc", "context": [ {"key":"field1","value":"123"}, {"key":"field2","value":"jeff"} ] } the xml version, however, doesn't work. context property null. content-type: application/xml; charset=utf-8 <?xml version="1

asp.net mvc 4 - How to pass data from Razor View Kendo UI DropDownList to Controller Variable? -

Image
vs'12 , kendoui, asp.net c# mvc4 internet application ef code first would see how 1 pass values form kendoui dropdownlist mvc controller razor view controller [httppost] //[acceptverbs(httpverbs.post)] public actionresult index(viewmodelcctrst model) //, formcollection values) { if (modelstate.isvalid) { string clt = model.clients; string cnt = model.countys; string twn = model.townships; ... ... //string xx = values["clients"]; // xx = values["countys"]; // xx = values["townships"]; ... ... *clt,cnt,twn , other variables null... wherein lies question why these null** razor view: @ @(html.kendo().dropdownlistfor(m=>m.ranges) //.name("ranges") .htmlattributes(new { style = &qu

java - What are some techniques for deploying a single page application that depends on a rest api? -

i'm building single page application (using angularjs) renders data rest api call makes legacy system. legacy system large, written in java , takes minutes deploy decided more productive develop single page application separate legacy system. the problems occurred once tried communicate legacy system's rest api. although both apps deployed locally same host, deployed on different app servers needed use different ports when communicating. because spa communicating rest api on different port, browsers prevented requests protect against cross site scripting attacks. we found build tool name lineman (that leverages grunt) made easy proxy http requests. got around cross site scripting limitation suitable in development mode. now we've got proof of concept working, want know how we're supposed deploy these apps without proxying. it's hard me find advice on how because angular doesn't assume have backend in first place , people use angular on front e

Javascript Recursion JSON into HTML -

Image
can please me creating following json following html? i bad @ recursion it's not funny. can't find on assist me how need, you'll see jsfiddle how off am! i'm trying turn this: var data = [ { "node_id":1, "children":[] }, { "node_id":2, "children":[] }, { "node_id":3, "children":[ { "node_id":4, "children":[] }, { "node_id":5, "children":[ { "node_id":6, "children":[] }, { "node_id":7, "children":[] } ] } ] } ]; into this: <ul> <li>

c - How does malloc distinguish between different types that both take up the same space? -

suppose following program run on x86_64 system: int main() { //sizeof(int) == 4 //sizeof(int*) == 8 //sizeof(long) == 8 // 2 distinct memory locations hold these 2 integers int* mem1 = (int*)malloc(2 * sizeof(int)); mem1[0] = 1; mem1[1] = 2; //i 1 distinct memory location hold 1 long long* mem2 = (long*)malloc(1 * sizeof(long)); mem2[0] = 3; free(mem1); free(mem2); return 0; } since malloc receives number of bytes allocate, both calls malloc same. how malloc know allocate 16 bytes store 2 integer array , allocate 8 bytes 1 long? edit clarity: based on following assumptions, storing these 2 different arrays require different amount of space each. however, malloc appears reserve same amount of space each time in program. yet, arrays sizes correctly determined arrays of datatypes of different lengths long s. can me identify flaw in understanding of memory, or point malloc / libc doing in background? here assumptions i'

struts2 - Getting json return type and html return in the same action -

i'll try specific possible. i have action 2 methods, 1 called via ajax , other 1 via regular submit. the point can't request regular submit, i'm getting action properties. public class clientaction{ @smdmethod public map<string, object> findclient(string myparam){ ... } public string saveclient(){ map<string, string[]> parametermap = this.getrequest().getparametermap(); } } getrequest saveclient method returns null!!! but, why??? didn't declare @smdmethod and here struts.xml <action name="client" class="mycompany.clientaction"> <interceptor-ref name="customjson"><param name="enablesmd">true</param></interceptor-ref> <result type="json"><param name="enablesmd">true</param></result> </action> i did others declarations. used have 2 separete classes, 1 each method,

c# - Windows Forms text editor search function -

i have 2 forms, 1 text editor, , second search form. in form1 have defined getrichtextbox() function. works there, how retrieve form2 (and other stuff)? my form1: using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.windows.forms; namespace texteditor { public partial class form1 : form { public form1() { initializecomponent(); } private richtextbox getrichtextbox() { richtextbox rtb = null; tabpage tp = tabcontrol1.selectedtab; if (tp != null) { rtb = tp.controls[0] richtextbox; } return rtb; } private void newtoolstripmenuitem_click(object sender, eventargs e) { tabpage tp = new tabpage("doc"); richtextbox rtb = new richte

c# - Forward/Backward loop performance analysis -

Image
i've been investigating performance issues event viewer application have on our development site when noticed interesting issue in algorithm. created simplified test project test 2 different algorithms. program retrieves windows event logs using eventlog class, , translates logs queryable eventlogitem entities. this operation performed , timed using 2 different loops. first (backward) loop starts @ index of last item in list, translates item , decreases index. method defined this: private static void translatelogsusingbackwardloop() { stopwatch stopwatch = new stopwatch(); stopwatch.start(); var originallogs = eventlog.geteventlogs(); var translatedlogs = new list<eventlogitem>(); parallel.foreach<eventlog>(originallogs, currentlog => { (int index = currentlog.entries.count - 1; index >= 0; index--) { var currententry = currentlog.entries[index]; eventlogitem translatedentry = new eventlo

c++ - Unexpected results when casting dword to byte [4] (endianity swap?) -

im trying cast dword array of 4 bytes. when this, bytes seem flip around (change endianness) as understand dword equaling 0x11223344 on little endian systems this: 0000_1011___0001_0110___0010_0001____0010_1100 but when this: typedef unsigned long dword; typedef unsigned char byte; int main(void) { dword = 0x11223344; byte b[4]; memcpy(b, &a, 4); printf("%x %x %x %x\n", b[0], b[1], b[2], b[3]); } i 44 33 22 11 . expected 11 22 33 44 . same thing happens when use reinterpret_cast or union { dword a; byte b[4]; } foo; im guessing im wrong , not compiler/processor, missing here? how on big endian system? edit: guess understanding of little endian systems wrong. question: faster while still being portable: using shifts individual byte values or using memcpy/reinterpret_cast , htonl()/ntohl()? no, understanding of little-endian incorrect. little endian means least significant byte @ lowest memory address. also: as understand

html - CSS: Percentage centering input with padding -

html (part of form): <div class="container"> <a id="p1_icon"></a> <input id="p1" class="input" name="p1" type="password" placeholder="password"> </div> css: .container { width:80%; margin-left:10%; margin-right:10%; // unnecessary position:relative; // allow icon positioned in input } .input { width:100%; padding: 10px 15px 10px 30px; // icon sits in 30px padding-left. ... other styling } #p1_icon { @include sprite_index(20px, 20px, -1063px, -246px); // sass icon sprite position:absolute; top:9px; left:7px; } the problem, of course, padding on .input gets added 100% width, ends being wider container (and therefore not centered). how can input fill container entirely? can javascript fine, i'd mobile-friendly css solution if 1 exists. (note: need containe

c++ - CUDA kernel and printf strange behaviour. -

i wrote simple kernel code, trying manipulate 1 dimensional array elements: #include "stdio.h" __global__ void loop(double *x, int cellsnum, int varnum,const double constant1) { int idx = threadidx.x+blockdim.x*blockidx.x; int = (idx+1)*varnum ; double exp1,exp2,exp3,exp4 ; if(idx<cellsnum-2) { exp1=double(0.5)*(x[i+6+varnum]+x[i+6])+x[i+10] ; exp2=double(0.5)*(x[i+8+varnum]+x[i+8]) ; if(i==0) { printf("%e %e",exp1,exp2) ; } exp3=x[i+11]-constant1*(exp1*exp2)/x[i+5] ; exp4=constant1*(x[i+9]*exp1-x[i+9-varnum]*exp2)/x[i+5] ; x[i+12]=exp3+exp4; } } extern "c" void cudacalc_(double *a, int* n1, int* n2, double* n3) { int cells_num = *n1; int var_num = *n2; double constant1 = *n3; loop<<<1,cells_num>>>(a,cells_num,var_num,constant1); } but doesn't work if comment piece of code: if(i==0) { printf("%e %e",exp1,exp2) ; } even when variable greater zero. comment lines code produces nan in x array. i&

After tuning Postgresql, PgBench results are worse -

i testing postgresql on 8gb ram/4 cpus/ 80gb ssd cloud server digital ocean. ran pgbench default settings in postgresql.conf, , altered common settings--shared_buffers, work_mem, maintenance_work_mem, effective_cache_size--to reflect 8gb of ram. after running 2nd set of tests, noticed of results worse. suggestions on why might be? rather new pgbench , tuning postgresql in general. settings: shared_buffers = 2048mb work_mem = 68mb maintenance_work_mem = 1024mb effective_cache_size = 4096mb tests: pgbench -i -s 100 pgbench -c 16 -j 2 -t 60 -u postgres postgres pgbench -s -c 16 -j 2 -t 60 -u postgres postgres pgbench -c 16 -j 4 -t 60 -u postgres postgres pgbench -s -c 16 -j 4 -t 60 -u postgres postgres pgbench -c 16 -j 8 -t 60 -u postgres postgres pgbench -s -c 16 -j 8 -t 60 -u postgres postgres how effective these tests? effective way employ pgbench? how should customize tests reflect data , server instance? what mean "worse"? how long time r

Java: 2D array of arraylists? -

i working on sudoku solving program , need arraylist holds numbers 1 thru 9 each of squares on 9x9 board. each of these arraylists correspond possible numbers go in square, if number can not go in square, removed list. i want able pull arraylist of current square working on, example if wanted remove number 7 arraylist corresponding square (3,5) arrayoflists[3][5].remove(integer.valueof(7)); however can't figure out how this. when try create array getting error on line declare array of arraylists cannot create generic array of arraylist here code: //create arraylist arraylist<integer> nums = new arraylist<integer>(); //fill arraylist numbers 1-9 (int = 1; < 10; i++) { nums.add(i); } //create 9x9 array of arraylists arraylist<integer>[][] array = new arraylist<integer>[9][9]; //fill each element of array arraylist of numbers 1-9 for(int = 0; i<9; i++){ for(int j = 0; j<9; j++){

Python Programming approach - data manipulation in excel -

i'm using python packages xlrd , xlwt read , write excel spreadsheets using python. can't figure out how write code solve problem though. so data consists of column of state abbreviations , column of numbers, 1 through 7. there 200-300 entries per state, , want figure out how many ones, twos, threes, , on exist each state. i'm struggling method i'd use figure out. normally post code have don't know begin. prepare dictionary store results. get numbers of line data have using xlrd, iterate on each of them. for each state code, if it's not in dict, create dict. then check if entry read on second column exists within state key on results dict. 4.1 if not, you'll create dict, , add number found on second column key dict, value of one. 4.2 if does, increment value key (+1). once has finished looping, result dict have count each individual entry on each individual state.

$watch a service variable or $broadcast an event with AngularJS -

i'm using service share data between controllers. application has update dom when variable modified. i've found 2 ways that, can see code here: http://jsfiddle.net/sosegon/9x4n3/7/ myapp.controller( "ctrl1", [ "$scope", "myservice", function( $scope, myservice ){ $scope.init = function(){ $scope.myvariable = myservice.myvariable; }; }]); myapp.controller( "ctrl2", [ "$scope", "myservice", function( $scope, myservice ){ $scope.increaseval = function(){ var = myservice.myvariable.value; myservice.myvariable.value = + 1; }; }]); http://jsfiddle.net/sosegon/y93wn/3/ myapp.controller( "ctrl1", [ "$scope", "myservice", function( $scope, myservice ){ $scope.init = function(){ $scope.increasedcounter = 1; $scope.myvariable = myservice.myvariable; }; $scope.$on( "increased", function(){ $scope.incr

How can I reuse an AlertDialog for Yes/No on Android? -

i'm trying find way reuse dialog shows customized titles, send yes/no click function has launched dialog. i have 2 buttoms, save , dismiss, , both call yes/no dialog, 1 showing "do want save" , other "dismiss changes?". i think procedure "dirty" guess can work, problem "view view" variable, don't know how pass activity dialog, can use recall function launched dialog. thanks in advance, hernihdez .java of activity (fragment of it) public void open_hh_fragment_yesno(view view, string aux_title, string aux_function) { bundle bundle=new bundle(); bundle.putstring("setmessage", aux_title); bundle.putstring("callingfunction", aux_function); dialogfragment newfragment = new hh_fragment_yesno(); newfragment.setarguments(bundle); newfragment.show(getsupportfragmentmanager(), "hh_fragment_yesno"); } public void savechanges(view view, string aux_yesno) { if (aux_yesno == "