Posts

Showing posts from June, 2010

linux - How to print hexadecimal double in C? -

i have number in hexadecimal: ffffffffffff and need save it, used double double a=0xffffffffffff; but need print , don't know how to. each time use %f , %d , %x , doesn't print value of it; need print ffffffffffff . code: int main() { double a=0xffffffffffff; printf("%x\n",a); printf("%d\n",a); printf("%x\n",a); printf("%f\n",a); return 0; } the true value %f ; returns decimal value of hexadecimal — returns this: ffffffe0 -32 ffffffe0 281474976710655.000000 with need change hexadecimal string, compare it, because have ffffffffffff in string , need compare both. if can't printf it, neither sprintf work. that's integer, , long one. don't use double store such value, that's floating-point. just use: unsigned long long temp = 0xffffffffffffull; you have 12 hexadecimal digits, number needs @ least 12 * 4 = 48 bits. platforms should have unsigned long long

orchardcms - What are the definitions of each of the Lifecycle Events in Orchard's CMS? -

the documentation content handlers in orchard mentions lifecycle events ( http://docs.orchardproject.net/documentation/understanding-content-handlers ). most events self explanatory, wondering if can tell me differences between onactivated , oninitializing , , onloading ? in firing order: onactivated - content item object hierarchy has been created, not yet fetched db used preparing content part further usage. eg. setting getters , setters lazy loaded objects, setting delegates etc. think of of "constructor" given part. oninitializing - content item object hierarchy has been created, not yet fetched db. used setting initial/default property values given part. onloading - content item loaded db. used various things. fired if item exists in database , loaded. orchard core uses event set lazy loaders part records. onloaded - content item has been loaded db used various things. fired if item exists in database , record loaders have been set. can

python - Creating a PyCObject pointer in Cython -

a few scipy functions (like scipy.ndimage.interpolation.geometric_transform ) can take pointers c functions arguments avoid having call python callable on each point of input array. in nutshell : define function called my_function somewhere in c module return pycobject &my_function pointer , (optionally) void* pointer pass global data around the related api method pycobject_fromvoidptranddesc , , can read extending ndimage in c see in action. i interested in using cython keep code more manageable, i'm not sure how should create such object. any, well,... pointers? just in cython same thing in c, call pycobject_fromvoidptranddesc directly. here example link ported cython: ###### example.pyx ###### libc.stdlib cimport malloc, free cpython.cobject cimport pycobject_fromvoidptranddesc cdef int _shift_function(int *output_coordinates, double* input_coordinates, int output_rank, int input_rank, double *shift_data): cdef double shift =

oracle10g - How can I delete similar rows with very specific criteria among similar rows? -

in oracle 10g, have table no exact duplicates, many similar rows. ok, want delete rows 1 specific criteria in collection of similar rows. criteria multiple accounts associated 1 practice_name. delete records null acct value when there multiple accounts practice_name. however, if there 1 instance of practice_name, , acct null, want preserve record. sample data: acct practice_name state phone ======================================= null pract1 mi 111-1111 1523 pract1 mi 111-1111 6824 pract1 mi 111-1111 null pract2 mi 222-2222 8945 pract2 mi 222-2222 null pract3 mi 333-3333 1486 pract4 mi 444-4444 this result like: acct practice_name state phone ======================================= 1523 pract1 mi 111-1111 6824 pract1 mi 111-1111 8945 pract2 mi 222-2222 null pract3 mi 333-3333 1486

xamarin - MvvmCross assembly referenced from Cirrious.MvvmCross.dll could not be loaded: System -

i'm trying set mvvmcross application project , run unit tests against (namely view models in it). i'm using xamarin studio on os x (v. 4.0.4, latest @ time of writing). the mvvmcross app set portable class library. test assembly set plain mono/.net assembly (not pcl) referencing nunit framework. when trying execute tests, fail system.typeloadexception . i have run tests mono binding log on. here's output: mono: following assembly referenced /users/jr/dev/rowinginmotion-cross/rowinginmotion.mobile.boatapp.tests/bin/debug/cirrious.mvvmcross.dll not loaded: assembly: system (assemblyref_index=3) version: 2.0.5.0 public key: 7cec85d7bea7798e system error: invalid argument mono: failed load assembly cirrious.mvvmcross[0x559960] mono: not load file or assembly 'system, version=2.0.5.0, culture=neutral, publickeytoken=7cec85d7bea7798e, retargetable=yes' or 1 of dependencies. is test setup not supported=

php - Get facebook user email -

i have facebook app , i'm trying user's email, uncaught oauthexception: unknown path components: /email on using following code: $email= idx($facebook->api('me/email'),'data',array()); function idx(array $array, $key, $default = null) { return array_key_exists($key, $array) ? $array[$key] : $default; } what doing wrong? that's way use normally: $user_profile = $fb->api('/me'); $email=$user_profile['email']; so can it: $email=idx($facebook->api('/me'),'email',array());

java - Hibernate NonUniqueObjectException on merge() , update() -

i errror while updating objects using method update() org.springframework.orm.hibernate3.hibernatesystemexception: different object same identifier value associated session when use method merge() error org.hibernate.nonuniqueobjectexception: different object same identifier value associated session. please help. you need implement 'hashcode' , 'equals' methods right, see here . take care not use id unique property -> separating object id , business key.

c++ - Matrix vectorization using SIMD -

i'm trying vectorized following loop (only inner) : for (int =0; i<n; i++){ const int line = * width; (int j = 0; j < n; j++){ a[line + j] = 3; } } but i'm getting following error: not vectorized: not suitable gather d.38226_277 = *d.38225_276; i googled around , it's seems compiler not vectorize because, not know data contiguous. i'm sure data ([line + j]) contiguous. how can tell compiler trust me , vectorize loop ? i'm using gcc 4.7 edit : i able vetorize loop without change in code using intel compiler.

sql server - equals Test into sql -

i use equals select possible it? select example declare @name_surname varchar(200); select (case when (plp.name +' '+ plp.surname) != @name_surname (set @name_surname = (plp.name +' '+ plp.surname)) end) 'lp.', problem: (set @name_surname = (plp.name +' '+ plp.surname)) your sql doesn't quite makes sense. seem trying set variable , return value (as "lp.") @ same time. not allowed. here note in documentation : a select statement contains variable assignment cannot used perform typical result set retrieval operations. the correct syntax setting variable using select this: select @name_surname = (case when (plp.name +' '+ plp.surname) != @name_surname (plp.name +' '+ plp.surname) else @name_surname end) that is, set keyword not allowed within select statement.

C Slope finder returning weird numbers -

in c, attempting create program finds slope in effort learn more language. have created 6 variables hold needed information: //variables int one_x; int one_y; int two_x; int two_y; float top_number; float bottom_number; then, created way user enter information. printf("------------------\n"); printf("enter first x coordinate.\n"); printf(">>> \n"); scanf("%d", &one_x); printf("enter first y coordinate.\n"); printf(">>> \n"); scanf("%d", &one_y); printf("------------------\n"); printf("enter second x coordinate.\n"); printf(">>> \n"); scanf("%d", &two_x); printf("enter second y coordinate.\n"); printf(">>> \n"); scanf("%d", &two_y); lastly, program solves problem , displays answer. bottom_number = two_x-one_x; top_number = two_y - one_y; printf ("the slope %d/%d&q

vbscript - RunAs username from variable -

i writing script run ie different user. @ beginning script displays input, , use value input username. option explicit dim input, europe input = inputbox("please type mailbox name") europe = "europe\" & input dim oshell set oshell= wscript.createobject("wscript.shell") oshell.run "runas /profile /user:" & europe & "c:\program files\internet explorer\iexplore.exe" wscript.sleep 100 oshell.sendkeys input oshell.sendkeys "{enter}" wscript.quit as can see username on domain europe\ , password same username. so username should europe\ & input , , password & input i have trouble getting string variable , passing shell command. ok, managed that. if want put string variable username need put this: oshell.run "runas /profile /user:" & europe &" ""c:\program files\internet explorer\iexplore.exe

Why is my android activity being stopped? -

i have inherited code application need modify (yuck). activity in question implements surfaceholder.callback , sensoreventlistener. activity custom camera. the code works fine autofocus, , take picture. once picture taken, start activity result crop image. activity started, surfaceholder.callback surfacedestroyed called (as expected). @ point existing application releases camera (as expected). however, when new crop activity launched, original camera activity stopped (stack trace: instrumentation.callactivityonstop->activity.performstop). edit: complete stack trace when onstop of activity called: cameraactivity.onstop() line: 784 instrumentation.callactivityonstop(activity) line: 1219 cameraactivity(activity).performstop() line: 5186 activitythread.performstopactivityinner(activitythread$activityclientrecord, activitythread$stopinfo, boolean, boolean) line: 3003 activitythread.handlestopactivity(ibinder, boolean, int) line: 3052 activitythread

Neural Networks in Matlab. Adding large learning patterns -

i new matlab , can't find solution problem... what problem? i have create neural network using matlab have 25k inputs , 10 outputs. there 300 patterns learn. when reading info neural networks in matlab saw input/learing data in 1 matrix. it's ok xor or small. realized have create matrix contains 25 000 * 300 elements ( 7,5 mln of integers ). 1) there possibility can expand matrix adding new rows (learning patterns)? 2) or maybe got like: learnpatternmatrix1 = [1, 2, 3 , ..., 25 000]; perfectoutputmatrix1 = [1, 2, 3, ... , 10]; network.addpattern(learnpatternmatrix1, perfectoutputmatrix1); network.addpattern(learnpatternmatrix2, perfectoutputmatrix2); % ... network.addpattern(learnpatternmatrix300, perfectoutputmatrix300); network.learn()? thanks ;) i'm sorry don't have answer making matlab deal size of matrix. have comments may relevant problem, however. neural networks are, machine learning algorithms, unlikely perform when there large num

String.methods.include?(:upcase) => false but '.upcase' is listed in ruby-doc.org -

i have been playing around strings bit (in irb), , found myself in trouble understanding meaning of following code: string.methods => [:try_convert, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :included_modules, :include?, :name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :const_missing, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :private_constant, :module_exec, :class_exec, :module_eval, :class_eval, :method_defined?, :public_method_defined?, :private_method_defined?, :protected_method_defined?, :public_class_method, :private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method, :nil?, :=~, :!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone,

css - divs shrink when viewed in chromebook; font-size does not -

Image
i wondering why when view website (and websites) on chromebook 11.6in screen, entire website shrinks. specifically, have div 960px wide contains words 12px in size. looks fine in every regular sized computer have viewed on. however, when view on chromebook, 960px div appears smaller. in fact every div bit smaller. fine, however, text no longer fits smaller div , spills outside of containing div. and idea why happening? , how go fixing this? example: use viewport settings in meta. mozilla has great post using viewport https://developer.mozilla.org/en-us/docs/mobile/viewport_meta_tag

c# - Check if component is resolved in outermost LifetimeScope -

i reworking existing codebase make better use of autofac container. situation i'm having lot of things used resolve components straight container in classic servicelocator anti-pattern. i'm in process of introducing proper unit-of-work schemes using lifetimescope . the issue i'm facing component must resolved child lifetimescope implementing idisposable , must disposed. if they're resolved in root scope never happen. is there way prevent components being resolved in root scope? crashing runtime ok this, since i'm going through these cases 1 one , introducing scopes needed. way can think of create little dummy component gets resolved once root lifetime scope , resolving in .instanceperlifetimescope() , storing statically somewhere. when later component resolved i'll 1 of dummy components , see if it's same instance 1 lifes in root scope. it's bit clunky though, , there better way? you try using 'per matching lifetime scope' reg

javascript - BreezeJS Selecting ComplexType properties -

i running issue breeze , durandal leading me believe may bug breeze or don't know right syntax. here model (given address simple complextype class) public class person { public int id {get;set;} public string name {get;set;} public address myaddress {get;set;} } and on front-end breeze js, have following: entityquery.from('person').select('id,name').orderby('id'); the above line works perfect, if have: entityquery.from('person').select('id,name,myaddress').orderby('id'); i error message error retreiving data. deferred not defined it looks though, can't have complextype property in select statement. else running issue? in advance. edit : may 8, 2013 - fixed in v 1.3.3 i've confirmed bug - query syntax correct ( not need expand complex types). try corrected in next release , post here when gets in. , repro :)

vb.net - Use ASP.net 2010 B to Ping an IP Address -

i'm trying use simple ping technique ping ip address. have added imports system.net.networkinformation.ping web page , tried create button once clicked ping ip address. the problem have error message states 'system.net.networkinformation' namespace , cannot used expression. i'm new , have tried replace else, still cannot seem work. possible review , let me know i'm going wrong. im using vb , vs2010. code: imports system.text imports system.net.networkinformation.ping partial class ping inherits system.web.ui.page protected sub btnping_click(sender object, e system.eventargs) handles btnping.click using system.net.networkinformation ping(ping = new ping()) pingreply(pingreply = ping.send("xxx.xx.xxx.xx")) console.writeline("address: {0}", pingreply.address) console.writeline("status: {0}", pingreply.status) end using end sub end class you better off trying following:

scheme - Replace first occurrence of symbol in (possibly nested) list -

i replace first occurrence of symbol (say '- ) symbol (say '+ ) inside list may contain lists. say, '(((-))) turn '(((+))) '((-) - b) '((+) - b) here's another, different option: using mutable state find out when first replace has happened: (define (replace-first) (let ((found #f)) (define (replacer exp old new) (cond ((null? exp) '()) ((not (pair? exp)) (cond ((and (eq? exp old) (not found)) (set! found #t) new) (else exp))) (else (cons (replacer (car exp) old new) (replacer (cdr exp) old new))))) replacer)) ((replace-first) '(((-))) '- '+) => '(((+))) ((replace-first) '((-) - b) '- '+) => '((+) - b) ((replace-first) '(+ 1 2) '+ '-) => '(- 1 2) ((replace-first) '((+) 1 2) '+ '-) => '((-) 1 2) ((replace-first) '(1 2 ((+)) 3 4) &

graph - Exception importing data into neo4j using batch-import -

i running neo-4j 1.8.2 on remote unix box. using jar ( https://github.com/jexp/batch-import/downloads ). nodes.csv same given in example: name age works_on michael 37 neo4j selina 14 rana 6 selma 4 rels.csv this: start end type since counter:int 1 2 father_of 1998-07-10 1 1 3 father_of 2007-09-15 2 1 4 father_of 2008-05-03 3 3 4 sister_of 2008-05-03 5 2 3 sister_of 2007-09-15 7 but getting exception : using existing configuration file total import time: 0 seconds exception in thread "main" java.util.nosuchelementexception @ java.util.stringtokenizer.nexttoken(stringtokenizer.java:332) @ org.neo4j.batchimport.importer$data.split(importer.java:156) @ org.neo4j.batchimport.importer$data.update(importer.java:167) @ org.neo4j.batchimport.importer.importnodes(importer.java:226) @ org.neo4j.batchimport.importer.main(importer.java:83) i new neo4j, checking if importer c

jquery - nextAll getting objects from a List View not behaving as expected -

i copied this solution make enter key behave tab one , says in post should work properly. problem focus not changing between inputs (text boxes). the characteristics of solution following: 1. solution in added asp .net web forms application. 2. supported browser ie8 3. jquery version 1.3.1 4. there ajax update panels , script manager proxy involved. the page in question defined follows: <asp:scriptmanagerproxy runat="server" id="myscriptmanager"> <scripts> <asp:scriptreference path="~/scripts/myscripts.js"/> </scripts> </asp:scriptmanagerproxy> <div id="content"> <asp:updatepanel runat="server" id="myupdatepanel"> <contenttemplate> <script type="text/javascript">sys.application.add_load(ajavascriptclass.ajavascriptmethod)</script> <div id="maindiv"> <di

Possible to create random slope model with fixed intercept in SPSS? -

Image
i'm aware it's pretty unusual assume random slopes fixed intercepts, , not ideal me using spss task. however, i'm doing analysis in teaching context in have no other choice. i attempted make happen leaving include intercept unchecked didn't work - ended model intercepts different , slopes zero. in response jeremy's comment took @ syntax. mixed jobsat physen /criteria=cin(95) mxiter(100) mxstep(10) scoring(1) singular(0.000000000001) hconverge(0, absolute) lconverge(0, absolute) pconverge(0.000001, absolute) /fixed=physen | sstype(3) /method=reml /print=covb solution testcov /random=physen | subject(grpid) covtype(vc) /save=pred. there doesn't seem reference here intercept being fixed. amended fourth line of syntax read /fixed=intercept physen | sstype(3) but still produced model intercept not fixed.

.net - C# Displaying Image from Database -

i having issues displaying image sql server database in .net application using c#. i've got save part of image working , storing image series of byes in database, running issues trying display it. here have: using system; using system.configuration; using system.web; using system.io; using system.data; using system.data.sqlclient; public class showimage : ihttphandler { public void processrequest(httpcontext context) { int32 empno; if (context.request.querystring["id"] != null) empno = convert.toint32(context.request.querystring["id"]); else throw new argumentexception("no parameter specified"); context.response.contenttype = "image/jpeg"; stream strm = showempimage(empno); byte[] buffer = new byte[4096]; int byteseq = strm.read(buffer, 0, 4096); while (byteseq > 0) { context.response.outputstream.write(buffer, 0, by

c# - Rounding digits exception -

if passing large number significantdifference method steema.teechart.utils.significantdifference(2011100616556782.7, 2011100616556782.7) the following exception happened: rounding digits must between 0 , 15 inclusive parameter name digits. i got error after lot of zooming operations on large data. could in this? this because arguments given utils.significantdifference exceed precision range of double . could please explain how reproduce exact steps should follow reproduce issue?

ios - "No Action header was found" error message while using SOAP webservice -

getting following error while consuming soap webservice in ios app "no action header found namespace 'http://www.w3.org/2005/08/addressing' given message." the same webservice working fine in soap ui tool. following request format nsstring *data = @"<soap:envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\"> <soap:header></soap:header> <soap:body><tem:getevaluators></tem:getevaluators></soap:body> </soap:envelope>"; nsstring *url = @"webservice url"; nsdata *postdata = [data datausingencoding:nsutf8stringencoding allowlossyconversion:yes]; nsstring *postlength = [nsstring stringwithformat:@"%d", [postdata length]]; nsmutableurlrequest *request = [[nsmutableurlrequest alloc] init]; [request seturl:[nsurl urlwithstring:url]]; [request sethttpmethod:@"post"]; [request setvalue:postlength forhttpheaderfield:@

html - cursor infront of text is appearing larger than the text -

Image
i have textarea input text, if type words cursor in front of text appears larger. why showing larger? should equal words? want font size 38px; i testing on chrome browser please me solve issue. <textarea name="quotes" cols="40" rows="10" placeholder=" what`s quotes? " style="height:100px;width:99%;overflow:auto;border: 1px solid silver;font-size:38px" keynav:shortcut="10"></textarea> the answer question ('why blinking cursor appear larger text?') it's illusion. cursor height of full height of line. remember bottom of g, j, p, q, or y part of line. so, might appear blinking cursor taller line, isn't.

html - vertical centering a form in a div -

<div class="parent"> <div class="left-child"> <img src="logo.jpg" alt="logo"> </div> <div class="right-child"> <form action="#"> <input type="text" value="search"> </form> </div> </div> i vertical center right-child form when left-child logo height increases. can me? ps: logo uploaded user. have no idea logo height. i created new div fit form in vertical way. hope works. fixed image width, but, can delete this. http://jsfiddle.net/bfzfj/ your css: .parent { border: 1px dashed red; display: table; overflow: auto; } .left-child img { width: 50px; height: 50px; } .left-child { border: 1px dashed blue; } .right-child { border: 1px dashed green; display: table-cell; vertical-align: middle;

c++ - Vector vs Array Performance -

in thread started discussion vectors , arrays, in largely playing devil's advocate, push buttons. however, during course of this, stumbled onto test case has me little perplexed, , have real discussion it, on "abuse" i'm getting playing devil's advocate, starting real discussion on thread impossible. however, particular example has me intrigued, , cannot explain myself satisfactorily. the discussion general performance of vector vs arrays, ignoring dynamic elements. ex: continually using push_back() in vector going slow down. we're assuming vector , array pre-populated data. example presented, , subsequently modified individual in thread, following: #include <iostream> #include <vector> #include <type_traits> using namespace std; const int array_size = 500000000; // http://stackoverflow.com/a/15975738/500104 template <class t> class no_init_allocator { public: typedef t value_type; no_init_allocator() noexcept {}

Unit Testing in C# -

junior web developer , have been tasked creating unit test project. [testmethod] public void testgetuser()//shell complete, test code needs review { try { //set test user asamembershipprovider prov = this.getmembershipprovider(); //call user membershipuser user = prov.getuser("test.user", false); //ask username deliberate case differences membershipuser user2 = prov.getuser("test.user", false); //prove still user, assert.arenotequal(null, user); assert.arenotequal(null, user2); //test using “.tolower()” function on resulting string. //verify case doesn’t matter on username. assert.areequal(user.username.tolower(), user2.username.tolower()); assert.areequal(user.username.tolower(), "test.user"); } catch (exception ex) { logmessage(ex); assert.fail(ex.message); } }

sockets - C Handling multiple types of UDP packets -

i'm writing application listens incoming udp packets. there's possibility of receiving many different types of packets. instance, packets defined such, package a: | int | char b | int c | package b: | short int d | int e | char f | and forth. my question is, given i'm receiving multiple types of messages, what's method coordinating what's being sent i'm reading? as see it, "header" added beginning of each message, defining type or read message length , compare have listed, if know size of each packet. also, if later option, packet guaranteed expected length each time? edit: i can see using packet length problem there multiple messages types of same length. use header contains magic word , code defines type. way can assure intended application, , identifies correct parser use. a sequence number , timestamp useful detect lost packets , arriving out of sequence. these common issues encountered udp.

python - django-sphinx - settings has no attribute DATABASE_ENGINE - -

when running command: ./manage.py generate_sphinx_config cities >> sphinx.conf it returning error, settings has no attribute database_engine. checking in shell also, cant find database_engine in settings. during setup, had setup databases. database_engine used here: https://github.com/dcramer/django-sphinx/blob/master/djangosphinx/utils/config.py def _get_database_engine(): if settings.database_engine == 'mysql': return settings.database_engine elif settings.database_engine.startswith('postgresql'): return 'pgsql' raise valueerror, "only mysql , postgresql engines supported sphinx."

Creating a multidimensional dictionary in C# for Windows Phone 7.8 -

i need store daily statistics in isolated storage of windpws phone leads me believe multidimensional dictionary useful i'm having trouble wrapping head around logic needed work. the stats looks in pseudocode: dictionary dailystats { 1, [stats] => dictionary { [class] => 5, [entertainment] => 3, [personnel] => 2, [price] => 7, [quality] => 6 } } i started out this: var dailystats = new dictionary<int, dictionary<string, string>>(); but wanted assign values structure got lost quite fast. values collected app each day. i've thought of linq seems overkill i'm trying do. can point me in right direction? thanks! if have 1 dicionary statusclasses ??? var dailystats = new dictionary<int, statusclass>(); and: class statusclass { //substitute vars type var class; var entertainment; var personnel; var price; var quality; public statusclass(var classvalue, var entertainmentva

javascript - Java Script - Loading image into a property -

i using snowstorm.js javascript file webpage. current source allows change character 'snowflake' displayed as. however, able change property of snowflake image of snowflake have created. you able edit source , line sets character displayed. this.snowcharacter = '&bull;'; // &bull; = bullet, &middot; square on systems etc. is there way can change display image instead of character , if so, how done? have never worked javascript before or pointers greatful. it looks snowstorm.js might have functionality already. have seen information posted @ http://www.bozo.us/javascript/snowstorm/ ? page suggests: file structure the script looks snow images under ./image/snow/ default shown below. if desired, can changed in user-configurable section. this seems correspond update mentioned @ bottom of page linked, says: 1.2.20041121a script moved 1 file (snowstorm.js) simplicity addeventhandler , png support functions

Mapping multidimensional array in rails to an array -

i have list of beers user has in cellar through cellared_beers user has many beers through cellared_beers , vice versa. each cellared_beer has data year , size attached. i wanting display tallied results of cellared_beers user on page. right have following code counts: beer_groups = @user.cellared_beers.count(:group => [:beer_id,:year,:size]) => {[1, 2008, "12oz"]=>1, [1, 2009, "12oz"]=>3, [1, 2010, "12oz"]=>1} how map out can show beer attributes based on beer_id, year, size, , amount? something like: foo beer(beer.name), bar brewery(beer.brewery.name),2008,12oz,1 foo beer(beer.name), bar brewery(beer.brewery.name),2009,12oz,3 foo beer(beer.name), bar brewery(beer.brewery.name),2010,12oz,1 you mean in string, this? {[1, 2008, "12oz"]=>1, [1, 2009, "12oz"]=>3, [1, 2010, "12oz"]=>1}.each.map |values,count| beer = beer.find(values[0]) "#{beer.name}, #{beer.brewe

c# 4.0 - JavaScript to choose droplist value not working in ASP .NET MVC4 with HTMLHelper and "All" -

i'm using javascript selected value of drop list in mvc 4 have issue think caused htmlhelper. controller - populate droplist private string populatestandard(object selectedvalue = null) { var query = db.database .sqlquery<standardmodel>( "select * [dbo].[getstandards] ('" + user.identity.name + "', '" + datetime.utcnow + "')") .tolist(); viewbag.standard = new selectlist(query, "standard", "standard", selectedvalue); try { return query[0].standard; } catch { return ""; } } view the view has section drop list. please note inclusion of "all". think problem. puts first row atop drop list saying "all" null value. want that. far (so what) @html.displaynamefor(m => m.standard) @html.dropdownlist("standard", "all") javascript it's long story,

c# - Finding all combinations, pseudo -

i have 10 rows, each row can have 1-10 numbers value of 1-100 (the actual value doesn't matter). example, first 3 rows like: 1. (2 numbers) 1st 2nd 1st 2nd 2. (1 number) combinations ---> 1st 1st 1st 1st 3. (2 numbers) 1st 1st 2nd 2nd with real numbers: 1. 5, 7 5 7 5 7 2. 2 combinations ---> 2 2 2 2 3. 12, 24 12 12 24 24 results in total of 4 unique combinations. how can solved? i've tried for-loops , if statements, won't work should. eric lippert wrote fantastic article on how write method can take number of sequences, each of arbitrary size, , find cartesian product (that's technical term you're asking for) of of sequences in c# . this link article the code derives @ end of article follows, although highly suggest reading article see how ended there: static ienumerable<ienumerable<t>> ca

intuit partner platform - IPP Add Account - The Account Isn't Valid -

i trying add bank account quickbooks online using ipp. code fails , says account isn't valid. here code: account account = new account(); account.desc = "desc"; account.name = "checking2"; account.type = accounttypeenum.revenue; account.typespecified = true; account.subtype = accountsubtypeenum.bank.tostring(); dataservices.add(account); do need add fields? receive errors account same name exists, however, not see it. i don't see xml in log: oauthrequestvalidator oauthvalidator = new oauthrequestvalidator(accesstoken, accesstokensecret, configurationmanager.appsettings["consumerkey"].tostring(), configurationmanager.appsettings["consumersecret"].tostring()); servicecontext context = new servicecontext(oauthvalidator, accesstoken, companyid, intuitservicestype.qbo); context.enableservicerequestslogging = true;

html - Buttons for text area that change the font size however It only works of text selected by the user (like Microsoft office's font size selections) -

this code have font size buttons need work on selected text user , not change font size of letters in text area (like microsoft's font size selection in there word documents) <select onchange="textarea1.style.fontsize = this.value;" > <option value="12px" selected="selected">12</option> <option value="14px">14</option> <option value="16px">16</option> </select> put id="textarea1" select <select id="textarea1" onchange="textarea1.style.fontsize = this.value;" > <option value="12px" selected="selected">12</option> <option value="14px">14</option> <option value="16px">16</option> </select>

java - Can Flyway coeexist with unmanaged database objects? -

does flyway have manage objects in database schema? or permissible have objects dropped/recreated outside of flyway system, example tables containing lookups generated , populated separately? as long unmanaged db objects not connected managed ones, (technically) not problem. if connected each other, have problems in scenarios: setting new database flyway scratch won't work because flyway migration cannot intercepted other unmanaged scripts. if unmanaged objects not compatible @ time, break flyway migration @ point. in case, if start using unmanaged db scripts, won't have reproducible migration path database anymore, 1 of key features of flyway.

Plone 4.2 TinyMCE jQuery UI Dialog -

i writing replacement plone dialog infrastructure. personal use , fun, available on github collective.js.jqueryuidialog. currently i'm struggling manage initialization tinymce editor in dialogs. i tried missing scripts getscript, stuck. googled , found init hooks, 1 $(document).bind('loadinsideoverlay', function() { $('textarea.mce_editable').each(function() { var config = new tinymceconfig($(this).attr('id')); config.init(); }); }); but none worked. any ideas or recommendations read further? update i updated products.tinymce version 1.3.3 , proceeded through upgrade steps in zmi. other functionality still working (yeehaa). i realized, call seems have changed, since pages tinymce on it, issue get command view named tiny_mce_gzp.js seems deliver actual configured editor portal. actually digging source find call , copy it's behavior.

Entity Framework 4.1: code first - Foreign key restriction error -

i have base class, let me call, entity_a has property 'id' primarky key. public abstract class entity_a { [key(), required] [databasegenerated(databasegeneratedoption.identity)] public guid id { get; set; } } then have 2 other classes, entity_b , entity_c. entity_b , entity_c inhertis entity_a: scenario #1: [table("entity_b")] public class entity_b : entity_a { [required] public virtual string propertyb1 { get; set; } // below foreign key [required] [foreignkey("propertyb2")] public virtual guid propertyb2id { get; set; } public virtual entity_c propertyb2 { get; set; } } [table("entity_c")] public class entity_c : entity_a { [required] public virtual string propertyc1 { get; set; } [required] public virtual string propertyc2 { get; set; } } it works ok, creates tables. problem when remove entity_a , put 'id' property within each class entity_b , entity_c: scenario #2

r - Alter file.show() behaviour -

i'm running file.show() in rstudio on mac, this: filename <- "/users/me/reports/myfile.pdf" # replace file location/name file.show(file.path(filename), title="my file") this 2 things: opens file.pdf opens blank file in rstudio called "my file". options()$pdfviewer returns: "/usr/bin/open" how can stop (2) happening? if want open pdf file via rstudio on mac, simplest way (as far know) use system function: filename <- "/users/me/reports/myfile.pdf" pdf <- getoption("pdfviewer") # same options()$pdfviewer cmd <- paste(pdf,filename) system(cmd) for example used openpdf in biobase (see here ) i don't know way alter file.show behaviour in order prevent blank file being opened in rstudio. think has the r.app mac os x gui uses internal pager irrespective of setting of pager. can see on manual here . note: different on windows machine, use shell.exec(filename) directly.

javascript - Meteor - update var on select change -

i've got dropdown, when user select value, want code executed. question: how can check whether selected value of dropdown has changed? in html file: <template name="jaren"> <form id="yearfilter"> <select class="selectpicker span2" id="yearpicker" > {{#each jaren}} {{#if selectedyear}} <option selected value="{{_id}}">{{jaar}} {{description}}</option> {{else}} <option value="{{_id}}">{{jaar}} {{description}}</option> {{/if}} {{/each}} </select> </form> </template> in javascript file: template.jaren.jaren = function() { return years.find(); } template.jaren.selectedyear = function() { if (session.get('year_id') == this._id) { return true; } else { return false; } } template.jaren.events({ 'chan

haskell - Using a monad inside the IO monad -

is there opposite of liftio ? i'm using websockets, , want able listen messages server in separate thread. here's i'm doing: import network.websockets import qualified data.text t import control.monad.io.class import control.monad import control.concurrent import control.applicative printmessages :: websockets hybi00 () printmessages = forever $ resp <- receivedatamessage liftio $ print resp run :: websockets hybi00 () run = liftio . forkio $ printmessages forever $ line <- liftio getline sendtextdata . t.pack $ line main = connect "0.0.0.0" 8080 "/" run so printmessages listens messages server , keeps printing them out. problem is, forkio expects function returns io () . there way me run printmessages in io monad? if i'm understanding right, reason want receive messages in thread because main thread waiting user input send. from @ the documentation , seems you'll have easier time if rev

ruby - rspec require spec_helper in .rspec file -

i've noticed projects such bundler require spec_helper in each spec file i've noticed rspec takes option --require , allows require file when rspec bootstrapped. can add .rspec file, added whenever run rspec no arguments. are there disadvantages using above method might explain why projects such bundler choose require spec_helper in each spec file? i don't work on bundler can't speak directly practices. not projects check-in .rspec file. reason file, current convention, has personal configuration options general output / runner preferences. if required spec_helper there, others wouldn't load it, causing tests fail. another reason, not tests may need setup performed spec_helper . more there have been groups of rubyists trying move away loading many dependencies test. making explicit when spec_helper required in test people have idea may going on. also, running single test file or directory doesn't need setup faster. in reality, if of te

Web API returning JSON content type instead of XML -

i brand-spanking-new web api. working on proof of concept project team create ssrs 2012 reports based off of web-api xml data sources. however, web-api should not configured negotiate xml content type. in future phase, our web-applications should able retrieve json objects same controllers/actions. i began following this tutorial , worked, no problem. next configured routes can call actions directly, , added querystringmappings global.asax specify content type. public class routeconfig { public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { id = urlparameter.optional } ); } } public static class webapiconfig { public static void register(httpconfiguration config) { config.routes.maphttproute( name: "

unix - Trying to print words in a file with C child processes -

the goal create child process each word in file, , have child process print word. file has following 5 words, each 1 on separate line: aachen biscay capri dino ellis the problem when try print file, 1 of words printing twice. aachen ellis biscay capri ellis dino here code. seems pretty straight forward, can't figure out why getting word. int main (int argc, char *argv[]) { char word[50]; int i; pid_t p; while (fscanf(stdin, "%s", word) != eof) { = 0; while (i < sizeof(word)) { if (word[i] < 'a' || word[i] > 'z') { word[i] = '\0'; break; } i++; } p = fork(); if (p != 0) continue; break; } fprintf(stdout, "%s\n", word); return 0; } i run program follows: $ ./printwords < words2.txt > out.txt the father printing last word in end. try instead of printing after loop: if (p == 0) { fprintf(stdout, "%s\n&quo

php - Finding position of last digit in string -

i'm trying format number plates - need find last digit in string , add space after it, e.g. t4max = t4 max t53tes = t53 tes i'm assuming i'll have use preg_replace - i've tried below find position in string of last digit, returns empty array. preg_match('/(0-9])/', $plate, $matches, preg_offset_capture); any ideas? that's easy: $str = 't4max'; $str_with_space = preg_replace('~\d(?=\d*$)~', '$0 ', $str); online demo: http://ideone.com/mqqqsh regex explanation: ~\d(?=\d*$)~ expression means - digit \d followed not digit \d end of string.

ios - Why am I getting a "Unable to parse NSPredicate" error -

i built following predicate use magicalrecord against core data store. // format date correctly nsdateformatter *dateformat = [[nsdateformatter alloc]init]; [dateformat setdateformat:@"yyyy-mm-dd*"]; // hh:mm nsstring *formatteddate = [dateformat stringfromdate:currentlyselecteddate]; nsstring *stringpredicate = [nsmutablestring stringwithformat: @"aposx >= %f , aposx < %f , %f > aposy , %f <= (aposy + aposh) , astarttime %@", [staffindex floatvalue], [staffindex floatvalue] + 218, touchpoint.y, touchpoint.y, formatteddate]; nspredicate *predicate = ([nspredicate predicatewithformat: stringpredicate]); it crashes on last statement, error: * terminating app due uncaught exception 'nsinvalidargumentexception', reason: 'unable parse format string "aposx >= 218.000000 , aposx < 436.000000 , 15.000000 > aposy , 15.000000 <= (aposy + aposh) , astarttime 2

algorithm - How to get all 24 rotations of a 3-dimensional array? -

i have 3-dimensional array. think of brick. there 24 possible rotations of brick (that keep edges parallel coordinate axes). how generate corresponding 3-dimensional arrays? a die (half pair of dice) handy observing 24 different orientations, , can suggest operation sequences generate them. see of 6 faces can uppermost, , sides below can rotated 4 different cardinal directions. let denote 2 operations: “ turn ” , “ roll ”, turn rotates die z axis 1 cardinal next, , roll rotates die 90° away you, away-face becomes bottom face , near face top. these operations can expressed using rotation matrices mentioned in answer of felipe lopes, or can expressed simple functions when given (x,y,z) return (-y,x,z) or (x,z,-y), respectively. anyhow, if place die 1 on near face, 2 @ right, , 3 on top, find following sequence of steps generates twelve different orientations 1, 2, or 3 spots on top: rtttrtttrttt. sequence rtr exposes 6, 4, 5 1, 2, 3 were, , repeat of sequence rtttrt

mysql - mysqldump with create database line -

i'm in process of moving files onto computer, , 1 thing transfer data in mysql database. want dump databases .sql files, have create database db_name including in file, way have import file mysql without having manually create databases. there way that? by default mysqldump creates create database if not exists db_name; statement @ beginning of dump file. [ edit ] few things mysqldump file , it's options: --all-databases , -a dump tables in databases. same using --databases option , naming databases on command line. --add-drop-database add drop database statement before each create database statement. option typically used in conjunction --all-databases or --databases option because no create database statements written unless 1 of options specified. --databases , -b dump several databases. normally, mysqldump treats first name argument on command line database name , following names table names. option, treats name arguments database names.

c# - While loop not working as intended in Pong game -

i attempting create pong game in c# visual c# express 2010. part, have main idea of game finished, have issue ball moving. have create loop, this: public void ballset() { if (!values.ispaused) { while(true) { if (values.totaltime.elapsed.seconds > 1) { values.totaltime.restart(); ballmove(50, 50); } } } } public void ballmove(int factorx, int factory) { values.balllastx = ball.location.x; values.balllasty = ball.location.y; this.ball.location = new point(this.ball.location.x + factorx, this.ball.location.y + factory); } the "ballmove(50, 50);" testing purposes @ moment. issue when ballset() called, form seems close code of 0, meaning there no error. call ballset() on here. public pong() { initializecomponent(); ballset(); values.totaltime.start(); } i have checked , program work when remove while loop in ballset(), if statement chec

java - How to detect ActiveX controls in IE 8/9/10 without having to instantiate ActiveXObject -

is possible detect activex controls active in ie 8/9/10 using javascript (or other technology - possibly java?), in way more extensible , dynamic attempting instantiate specific activex object around try-catch block? far, appears way achieve solution, solution not extensible , require additional code maintenance when newer activex plugins released. it nice able detect plugins similar in way js navigator.plugins array, far can tell, there no comparable way activex controls. you create activex control had ability detect presence of other activex controls, ie not expose api you. catch-22.

unicode - Determine all ISO 15924 script codes in JavaScript string -

i'm looking efficient way take javascript string , return of scripts occur in string. full utf-16 including "astral" plane / non-bmp characters require surrogate pairs must correctly handled. possibly main problem since javascript not utf-16 aware. it has deal codepoints no fancy awareness of complex scripts or grapheme clusters necessary. (this obvious of anyway.) example: stringtoiso15924("παν語"); would return like: [ "grek", "hani" ] i'm using node.js , unicode libraries such xregexp , unorm don't mind adding other libraries might handle or ease such feature. i'm not aware of javascript library can character properties such script codes, second part of problem. the third part of problem avoid inefficiencies. i answered a similar question , @ least related. in this pastebin (looooong) function returns script name character. should easy modifiy accommodate string.