Posts

Showing posts from September, 2014

How to deal with serialization and deserialization of objects with dependencies -

suppose have 2 objects depend on each other or other objects(so use references these objects) , need save/restore "state" from/to disk. since storing pointers disk not produce correct results on restore, how keep dependencies correct on restore? e.g., class { b b; } class b { { a; } (or more complex chains may have n-cycles of dependencies) a = deserialize(adata) b b = deserialize(bdata) (and suppose need a.b = b , b.a = a) i'm thinking having unique hashes objects lazy evaluation solve problem maybe there better ways? (if have unique hash easy find object use , save , restore object(basically hash acts pointer valid(since unique , never changes))

zsh - Binding caps lock to escape in z-shell -

i want rebind caps lock escape in z-shell make better use of vi-mode in z-shell line editor. don't want rebind entire system. edit: i'm running on debian. use zsh , without x-server. is there solution independent of underlying linux-distribution? as sampriti panda , bk201 pointed out question doesn't belong here , reposted on superuser.com. question solved now, see solution follow link .

android - ADB: How to install apk on multiples devices simultaneously using adb commands -

how install apk on multiple devices simultaneously using adb command line instructions? want install apk on 2 or more devices single command, possible? i have tried using, below command. "adb -s install .apk path" --> install apk on either 1 of connected device not on both connected devices. please help.... there no "out of box" solution. have put time in there: you can query attached devices via 'adb devices' , have process output install apk on attached devices ( 'adb install' every connected device ) maybe there tool outside in web, haven't found one. see http://developer.android.com/tools/help/adb.html#devicestatus further information. regards

javascript - Mongo DB reorder objects on insert -

in node js app im using mongo db , , have issue when inserting in database. when add new record collection objects beign reordered . knows why happening ? im doing insert collection.insert(object, {safe:true}, function(err, result) { if (err) { res.send({'error':'an error has occurred'}); } else { // error } }); actually , operation on collection change order of objects , knows why happening ? mongodb documents have padding space used updates. if make small changes document adding/updating small field there chance size of updated document increase still fit allocated space because can use padding. if updated document not fit in space mongo move new place on disk. documents might move lot in beginning until mongo learns how padding need prevent such moves. can set higher padding avoid documents being moved in first place. in either case can't rely on insertion order sorted list of documents. if want guaranteed order nee...

c# - MoreLinq Acquire. What does it do? -

i inspecting jon skeet's morelinq , became curious acquire extension source code the implementation follows /// <summary> /// ensures source sequence of <see cref="idisposable"/> /// objects acquired successfully. if acquisition of /// 1 <see cref="idisposable"/> fails /// acquired till point disposed. /// </summary> /// <typeparam name="tsource">type of elements in <paramref name="source"/> sequence.</typeparam> /// <param name="source">source sequence of <see cref="idisposable"/> objects.</param> /// <returns> /// returns array of acquired <see cref="idisposable"/> /// object , in source order. /// </returns> /// <remarks> /// operator executes immediately. /// </remarks> public static...

ios - UIImage not clipped by clipping path -

i have uiview subclass contains uiimageview. want image appear circular, did this: - (void)drawrect:(cgrect)rect { cgcontextref ctx = uigraphicsgetcurrentcontext(); cgcontextsavegstate(ctx); cgpathref clippath = [uibezierpath bezierpathwithroundedrect:rect cornerradius:17].cgpath; cgcontextaddpath(ctx, clippath); cgcontextclip(ctx); [self.imageview.image drawinrect:rect]; cgcontextrestoregstate(ctx); } however, images not circular, regular rectangles. what's issue? ac couple options have either breate cornerradius on uiimageview appears circular or remove uiimageview uiview's subviews. in first case don't need have custom drawing since circle picture want drawn in uiimageview cornerradius (and clipstobounds enabled). in second don't need uiimageview @ all, uiimage. uiimageview way display uiimage on screen, , if that's taken care of in custom drawing of view don't need uiimageview. given these options believe u...

Saving variables to a text/html file in JavaScript serverside -

i'm making form on javascript , want save of users entered variables either .txt file or new webpage variables pre entered in inputs. understand javascript cant manipulate users machine can manipulate servers files(create new files) if can how 1 save variables onto new file in way imported website? input appreciated :) aaron~ javascript running in browser can make http requests server (generally using xmlhttprequest object). it can't write arbitrary files (if could, client could, , deface website) you need form of server side process running on server can interpret http request meaning "write file" (although, in cases, write database , generate file on request data there). you write server side process in javascript if have suitable server side environment (such node.js).

c++ - MPI send recv input arguments -

i have problems part of code (i semplified more clear). //p number of processor (we suppose 2) //vett vector contains elements send //disp vector elements index of first element send //elem vector elements number of elements send //local_v destination vector (of dimension elem[rank]) //local_n number of elements have arrive (=elem[rank]) in case cycle executed 1 time for(unsigned int = 1; < p; i++){ if(rank==0){ mpi_send(&vett[disp[i]], elem[i], mpi_int, i, 0, mpi_comm_world); }else{ mpi_recv(&local_v, local_n, mpi_int, 0, 0, mpi_comm_world, mpi_status_ignore); } } processor1 sends other(in case processor2). not sure if use correctly mpi_send, in particular i'm not sure first input argument correct... in mpi_recv missing [0] after receive buffer, entire line: mpi_recv(&local_v[0], local_n, mpi_int, 0, 0, mpi_comm_world, mpi_status_ignore);

java - Writing dates in csv files, some output as ###### -

i writing application let threads write csv files random numbers , random dates. however, of dates output ######, when click them in excell, show correct date (e.g.11/4/2014 shows ###### in excell, when click on cell, in fx field show 11/4/2014). here how write dates: random random = new random(); bufferedwriter bufferedwriter; gregoriancalendar cal = new gregoriancalendar(); dateformat df = new simpledateformat("dd/mm/yyyy"); writeline(random, bufferedwriter, cal, df); private void writeline(random random, bufferedwriter bufferedwriter, gregoriancalendar cal, dateformat df) throws ioexception { string randomdatestring; bufferedwriter.write(double.tostring(random.nextdouble() * 100)); bufferedwriter.write(","); randomdatestring = createrandomdate(random, cal, df); bufferedwriter.write(randomdatestring); bufferedwriter.newline(); } private string createrandomdate(random random, grego...

activerecord - has_many or join - what's the 'rails way' to use my table? -

i have database keeps track of accidents. each accident can have multiple causes. each cause has friendly name in 3rd table. what's 'rails way' create association? here's have: create_table "accidents", force: true |t| t.text "notes" t.datetime "created_at" t.datetime "updated_at" end create_table "causes", force: true |t| t.integer "accident_id" t.integer "cause_name_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cause_names", force: true |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end causename.create :name => "dui" causename.create :name => "speeding" accident: class accident activerecord::base has_many :causes end causes: class cause < activerecord::base belongs_to :accidents has_one :cause_name end cause names...

c# - Easy way to select more than one field using LINQ -

take of sample object, public class demo { public string displayname { get; set; } public int code1 { get; set; } public int code2 { get; set; } ... } and lets want put codes ( code1 , code2 ) in 1 list ( ienumerable )... 1 way one: var codes = demolist.select(item => item.code1).tolist(); codes.addrange(demolist.select(item => item.code2)); //var uniquecodes = codes.distinct(); // optional i know not nice neither optimal solution, curious know better approach / (best practice)? linq not silver bullet kill everything for intent i'd propose following var codes = new list<int>(demolist.count * 2); foreach(var demo in demolist) { codes.add(demo.code1); codes.add(demo.code2); } benchmark i did benchmark iterating list of 1 million , 1 thousand instances solution , ani's amount: 1 million mine : 2ms ani's: 20ms amount 1000 items mine : 1ms ani's: 12ms the sample code ...

c++ - Avoiding data race of boolean variables with pthreads -

in code have following structure: parent thread somedatatype thread1_continue, thread2_continue; // bool guarantee no data race? thread 1: while (thread1_continue) { // work } thread 2: while (thread2_continue) { // work } so wonder data type should thread1_continue or thread2_continue avoid data race. , if there data type or technique in pthread solve problem. there no built-in basic type guarantees thread safety, no matter how small. if working bool or unsigned char , neither reading nor writing guaranteed atomic. in other words: there chance if more threads independantly working same memory, 1 thread can overwrite memory partially while other reads trash value ~ in case behavior undefined . you use mutex wrap critical section lock , unlock calls ensure mutual exclusion - there 1 thread able execute code. more sophisticated synchronization there semaphores , condition variables or patterns / idioms describing how synchronization can handled usin...

windows - Coldfusion CFC creation timeouts -

after searching no end, countless hours of trial , error different settings, i've come empty on why server performing slowly. here basics. i've switched hosting local server (cf8 running on ubuntu) better equipped hosting company (cf10 running on windows server 2008). both servers ran xeon processors. old linux server ran on 8gb ram. windows running on 9gb. both running 64-bit. problem having on simple task: initial cfc creation. i have custom created cms, runs 2 sets of cfc (application , session scoped) general public, application scope cfc's created, , when user logs site, additional session scoped cfc's created (anywhere 8 - 16 depending on number of modules site contains). on linux box worked great, fast no issues. however, since switching windows server , cf10, creation process has become dreadful. when go log site, authentication done, , cfc's created. when first log site, process can take anywhere 15 - 50 seconds. when log out, session scope vari...

math - Using atan2 to find angle between two vectors -

i understand that: atan2(vector.y, vector.x) = angle between vector , x axis . but wanted know how angle between two vectors using atan2. came across solution: atan2(vector1.y - vector2.y, vector1.x - vector2.x) my question simple: will 2 following formulas produce same number? atan2(vector1.y - vector2.y, vector1.x - vector2.x) atan2(vector2.y - vector1.y, vector2.x - vector1.x) if not: how know vector comes first in subtractions? thanks atan2(vector1.y - vector2.y, vector1.x - vector2.x) is angle between difference vector (connecting vector2 , vector1) , x-axis, problably not meant. the (directed) angle vector1 vector2 can computed as angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x); and may want normalize range 0 .. 2 * pi : if (angle < 0) angle += 2 * m_pi;

angle - How to calculate wind direction from U and V wind components in R -

i have u , v wind component data , calculate wind direction these values in r. i end wind direction data on scale of 0-360 degrees, 0° or 360° indicating wind blowing north, 90° indicating wind blowing east, 180° indicating wind blowing south , 270° indicating wind blowing west. below example data: > dput(wind) structure(list(u_ms = c(-3.711, -2.2417, -1.8188, -1.6164, -1.3941, -1.0682, -0.57611, -1.5698, -1.4976, -1.3537, -1.0901, -0.60403, -0.70812, -0.49045, -0.39849, 0.17875, 0.48356, 1.5082, 1.4219, 2.5881), v_ms = c(-1.471, -1.6118, -1.6613, -1.7037, -1.7388, -1.8748, -1.8359, -1.6766, -1.6994, -1.7505, -1.4947, -0.96283, -1.1194, -0.6849, -0.7847, -0.80349, -0.19352, -0.97815, -1.0835, -0.81666), u_rad = c(-0.064769155, -0.039125038, -0.031744042, -0.028211496, -0.02433163, -0.018643603, -0.010055014, -0.027398173, -0.026138045, -0.023626517, -0.01902583, -0.01054231, -0.012359023, -0.008559966, -0.006954961, 0.003119775, 0.008439712, 0.02632305, 0.0248168...

php - Uppercase first letter and rest lower -

ive been looking around way in php have string converted, first letter becomes uppercase , rest lower case. at moment doing believe standard way: ucfirst(strtolower($string)); but have found programming languages (ie. tcl) can 1 cammand: totitle is there way in php? it's not problem such, i'm curios dude :d thanks function totitle($string){ return ucfirst(strtolower($string)); } and voila :)

Error when I use cordova platform add ios -

Image
i tried running command cordova platform add ios when command executed appears error in picture. how fix this? note: i use nodejs v0.10.25 prerequisites before running command-line tools, need install sdks each platform wish target. add support or rebuild project platform, need run command-line interface same machine supports platform's sdk. cli supports following combinations: ios (mac) android (mac, linux) blackberry (mac, windows) windows phone 7 (windows) windows phone 8 (windows) http://docs.phonegap.com/en/edge/guide_platforms_ios_index.md.html

php - Create an array within an array using a string from key -

i can't past making think 2d array in php. i'm using csv source input , want take 1 of columns , split array well. $csv = array_map("str_getcsv", file("data/data.csv", file_skip_empty_lines)); $keys = array_shift($csv); foreach ($csv $i => $row) { $csv[$i] = array_combine($keys, $row); $linkto = $csv[$i]['linkto']; // $linktoarray = explode(" ", $linkto); echo '<pre>'; // print_r($linktoarray); echo '</pre>'; $csv[$i] = array_combine($keys, $row); } $csv['timestamp'] = time(); echo '<pre>'; print_r($csv); echo '</pre>'; will output: array ( [0] => array ( [color] => 1 [shape] => 0 [label] => string [size] => 1 [linkto] => 1 2 3 )... using similar commented out, i'd love see like: array ( [0] => array ( ...

php - Active link with css color -

i have filter element filter data: http://dualda.com/index.php?option=com_findme&view=info&layout=ranking&interval=7 and here want actual "bold" text in red using css. ideas? e.g. this <a class="redlink" href="/index.php?option=com_findme&amp;view=info&amp;layout=ranking&amp;type=playerbyactivity&amp;lang=de">gespielte spiele</a> complement css redlink this: b .redlink, b .redlink:link, b .redlink:visited { color: #ee2b4e; } target links inside b tags , different states.

2D Array Memory Allocation Crash in C -

Image
i seem having problems memory allocation 2d array using calloc. when allocating 2nd dimension array calloc crashes when outside ide standalone executable, works when debugging. i've gone though can think of , stumped why happens; when working fine couple of days ago. seems spontaneous malfunction won't stop. the code in seperate function of called multiple times. o = (double**)calloc(3*cc,sizeof(double*)); (r = 0; r < 3*cc; r++){ printf("row: %d ",r); printf("1.addy: %p ",&o[r]); o[r] = (double*)calloc(4,sizeof(double)); printf("2.addy: %p\n",&o[r]); } i've tried using different forms of freeing memory: for (r = 0; r < 3*c; r++) free(o[r]); & free(o); but crash @ different points. when memory not freed. this screenshot of memory addresses allocates during each call , appear freed , reused appropriately, crash. if can tell me what's going on best.

apache - Building custom RPM but the package is empty? -

i trying build rpm compiled version of apache. want rpm build in /opt/apache.... able create rpm file when rpm -qpl on file shows empty. here spec file: name: custom-http version: 2.2.25 release: 1%{?dist} summary: custom build of apache license: na url: http://x.x.x.x:/repo2 source0: http://x.x.x.x:/repo2/httpd-2.2.25.tar.gz buildrequires: xfce4-dev-tools apr-util openssl-devel %description custom compiled version of apache version 2.2.25 %prep %setup -n httpd-2.2.25 %build ./configure --disable-rpaths --with-included-apr --enable-mods-shared=all --with-mpm=prefork --enable-ssl --prefix=/opt/apache --enable-so make %{?_smp_mflags} %install make install %clean %files %doc %changelog * thu jan 30 2014 name <email address> - first attempt ~ first, need install files buildroot when doing make install , since don't want files installe...

java - Remove inner vertical borders in a JTable -

Image
i want remove inner borders in jtable. i've researched question , found remove vertical borders jtable like: --------------------- +-------+-------+-------+ (0,0) (0,1) (0,2) | (0,0) | (0,1) | (0,2) | --------------------- +-------+-------+-------+ (1,0) (1,1) (1,2) instead of | (1,0) | (1,1) | (1,2) | --------------------- +-------+-------+-------+ (2,0) (2,1) (2,2) | (2,0) | (2,1) | (2,2) | --------------------- +-------+-------+-------+ however want this: +-----------------------+ | (0,0) (0,1) (0,2) | +-----------------------+ | (1,0) (1,1) (1,2) | +-----------------------+ | (2,0) (2,1) (2,2) | +-----------------------+ any appreciated! i couldn't think of neat way solve not involve overriding internal paint() call, messy. here less elegant solution: disable vertical lines , add line border of apropiate color. table.setshowverticallines(false); color linecolor ...

python - Character encoding in regular-expression substitution -

i trying substitute regular expression pattern. more want replace $$ some_latex $$ $latex some_latex$ . tried following. in [22]: re.sub(r'\$\$(?p<pat>.+?)\$\$', r'$latex \1 $', "$$ x = \frac{2}{3}$$", re.dotall | re.u) out[22]: '$latex x = \x0crac{2}{3} $' the word \frac converted \x0crac . how overcome this. tried following also. didn't help. re.sub(r'\$\$(?p<pat>.+?)\$\$', r'$latex \1 $', "$$ x = \frac{2{3}$$".encode("string_escape"), re.dotall | re.u) '$latex x = \\x0crac{2}{3} $' this has nothing regular expression; \f form-feed escape code: >>> '\f' '\x0c' >>> len('\f') 1 the character already present in input, before replacements take place: >>> "$$ x = \frac{2}{3}$$" '$$ x = \x0crac{2}{3}$$' double slash or use raw string literal: >>> '\\f' '\\f' >>>...

c# - Linq Query not returning value from database field -

i literally have no idea why isn't querying way expect query, new programming in head seems right. i using this.context.user.identity.name return logged in user returns email not username. here script in it's context. @html.actionlink("my account", "users", new { id = this.context.user.identity.name }, false) @: | @html.actionlink("logout", "logout", "users") from want url website/users/username hence wanting username instead of email. the query: project1.models.dbcontext db = new project1.models.dbcontext(); //save u.username in var user u.email == user_logged_in_email var user = u in db.users u.email == this.context.user.identity.name select u.username; i hoping linq query find row contained email address , pull username out , store in var user. equals system.data.entity.infrastructure.dbquery you need enumerate query user: var user = (from u in db.users u.em...

eruby - printing in erb without '<%= %>' or ruby on rails -

similar print in erb without <%=? however, answer there specific ruby on rails. there similar capability in vanilla erb? here's use case: <% [ 'host_perfdata_command', 'service_perfdata_command', ].each |var| value = instance_variable_get("@#{var}") if value %><%= "#{var}=#{value}" %><% end end -%> while works, it i%><%=s hard r%><%ead. basically, need write directly output string. here's minimal example: template = <<eof var 1 <% print_into_erb var1 %> var 2 <%= var2 %> eof var1 = "the first variable" var2 = "the second one" output = nil define_method(:print_into_erb) {|str| output << str } erb = erb.new(template, nil, nil, 'output') result = erb.result(binding) but because feel obligated point out, pretty unusual need this. other answers have observed, there number of ways rewrite template in question ...

python - How to label axes in Matplotlib using LaTeX brackets? -

how label axes in matplotlib using latex expression $\langle b_{\mathrm{e}} \rangle$ ? need label axis nice looking "<" , ">" latex brackets. try ax.set_ylabel(r'$\langle b_{\mathrm{e}} \rangle$') labeling y-axis or ax.set_title(r'$\langle b_{\mathrm{e}} \rangle$') title of axes.

c# - wsHttpBinding MessageSecurityException after runtime Web.config write update -

i using default wshttpbinding on iis hosted wcf service. <service behaviorconfiguration="wcfservice.mybehavior" name="wcfservice.myservice"> <endpoint address="" binding="wshttpbinding" contract="common.imyservice" name="wshttpbinding_mywcfservice"> </endpoint> <endpoint address="mex" binding="mexhttpbinding" contract="imetadataexchange"/> </service> i know bad practice wcf service must update web.config file. system.configuration.configuration config = system.web.configuration.webconfigurationmanager.openwebconfiguration("~"); system.configuration.connectionstringssection section = config.getsection("connectionstrings") system.configuration.connectionstringssection; section.connectionstrings["mainconnection"].connectionstring = newvalue; system.configuration.configurationmanager.appsettings["dataproviderusername"...

php - MySQLi fetch error -

i trying move mysql_query mysqli_query @ moment error: warning: mysqli_fetch_array() expects parameter 1 mysqli_result, object given in i searched google nothing helped me. maybe here able to! this code: connection: $objconnect = mysqli_connect("localhost","konstyle","root", "konstyle") or die(mysqli_error()); sql query: $objquery_category = mysqli_query($objconnect, $sql_category) or die ("error query [".$sql_category."]"); fetch array: while($objresult = mysqli_fetch_array($objconnect, $objquery_category)) why getting error/warning? you need lose $objconnect when fetching. should work: while($objresult = mysqli_fetch_array($objquery_category)) this straight manual : mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = mysqli_both ] ) two arguments: 1st mysqli_result , optional result type. the reason connection "saved" within $objquery_category...

xml - Scala – companion object & apply: non understandable error -

i can't create class representing xml parsed document, using companion object. here code of class: package models import javax.xml.bind.element import scala.xml.elem import javax.xml.validation.schemafactory import javax.xml.transform.stream.streamsource trait myxml { case class elémentxml(code_xml: scala.xml.elem) { def validate: boolean = { try ({ val schemalang = "http://www.w3.org/2001/xmlschema" val factory = schemafactory.newinstance(schemalang) val schema = factory.newschema(new streamsource("sites_types_libelles.xsd")) val validator = schema.newvalidator() validator.validate(new streamsource(code_xml.tostring)) true }) catch { case t:throwable => false } } } object elémentxml { def apply(fichier: string) { try{ val xml_chargé = xml.xml.loadfile(fichier) some(new elémentxml(xml_chargé)) }catch{ case e:throwable => none } } } } and here code app using class: val xml1:elémentxml = elémentxml("a...

mysql - MS Access Stratified Random Sampling -

i trying radomly select given number of rows person submitted request type. example lets there 2 people , people , 3 request types: summary name: number of requests: request type: mary 15 vaction mary 3 transfer john 4 transfer john 3 pay raise i have generated several other queries find number of records randomly sample. have table of detailed information, , table has summary similar 1 above has field "number sample" (e.g. mary vacation 5,m john pay raise 2). have field on main detailed table random numbers. how can sort name, request type, , random number. need pull number of records sorted list match "number sample" field, giving me random sample. did lot of searching cannot find answer. tried using select top not let me feed number of rows in field (even if not sure how able select different number within each subgroup). ideas...

java - How can I keep handlers for different buttons in different classes in JFrame? -

i have problem program using jframe. making "cash machine" program, asks user first name, last name, current account state , withdrawal amount. want have 2 classes implements 2 different tasks program does. class card should ask user data said before, , after clicking "accept" button should give message box information "hello [user], have withdrawed [amount], current account state [amount]." if user exceeds "zero state" means wants withdraw more has, program pops message box decline information. second class creditcard same, allows user make debt 1500. have 2 handlers : 1 card works fine after clicking "accept" button , second 1 creditcard doesn't work @ all. know problem proper inheritance, can't solve it. important me store creditcard handler in creditcard class (if it's possible of course). my code below: card class: public class card extends jframe { public jtextfield firstname; public jtextfield lastname; publi...

Wordpress Google Maps Plugin with markers and search engine -

i'm looking wordpress google maps plugin these functions: insert markers maps custom icon. i don't if possible, need insert link in each marker link antoher website page. the user should able search , filter markers admin pre-configured categories or tags. markers match user search, should appear in new map. i tried plugins maps marker pro (the best found lot of options think can't make marker user search form), wp google maps, mappress, comprehensive gm plugin. none of them seem gather features need. do know maps plugin functions? victor we have developed plugin should able cater requirements. http://heroplugins.com/plugin/maps/ regards, brett.

click event listener on styled map icons and labels -

is possible add listener click event on icons and/or labels appear styled maps? have form allows entry of points of interest. since poi styling shows icons and/or labels many potential candidates, , clicking on 1 opens infowindow address info, etc, capture address info fields on form if user clicks on one. there no api-based access poi's . but there possible workaround. when click on poi infowindow opens. it's possible modify infowindow-prototype able access content of infowindow without having reference infowindow-instance. //store original setcontent-function var fx = google.maps.infowindow.prototype.setcontent; //override built-in setcontent-method google.maps.infowindow.prototype.setcontent = function (content) { //when argument node if (content.queryselector) { //search address var addr = content.queryselector('.gm-basicinfo .gm-addr'); if (addr) { ...

unit testing - Should the CustomEventArgs method implement another Interface? -

hi using test driven development , seem in area not familiar. please check , let me know changes should make in code make "unit testable" ? code tested: public void purchaseitemlist() { //call methods checkavailablility if(!productavailable) { purchaseitemeventargs.issuccessfull = false; } else { purchaseitemeventargs.issuccessfull = true; // code update model. purchaseitemeventargs.itemspurchased = getitemspurchased() } } now issue face cannot mock purchaseitemeventargs class not implement interface. using moq testing. advise on code changes make unit testable helpfull. thanks since getitemspurchased() method of class, make protected virtual . define test class this: class testablemyclass : myclass{ private items _items; public testablemyclass(items items) : base() { _items = items; } protected items getitemspurchased(){ return _items; } } and then, in tests...

algorithm - List of random numbers -

i need generate list of numbers (about 120.) numbers range 1 x (max 10), both included. algorithm should use every number equal amount of times, or @ least try, if numbers used once less, that's ok. this first time have make kind of algorithm, i've created simple once, i'm stumped on how this. tried googling first, though don't know call kind of algorithms, couldn't find anything. thanks lot! it sounds want first fill list numbers want , shuffle list. 1 way add each of numbers list , repeat process until list has many items want. after that, randomly shuffle list. in pseudo-code, generating initial list might this: list = [] while length(list) < n in 1, 2, ..., x if length(list) >= n break end if list.append(i) end end while i leave shuffling part exercise reader. edit: pointed out in comments above put more smaller numbers larger numbers. if isn't what's desired, iterate on possib...

git - How do I turn off GIT_TRACE? -

i started receiving permission denied errors when trying fetch our git server. according this document , used git_trace_packet , git_trace commands. found problem , fixed it, every git command run getting traced. can tell me how turn function off? as said in comments, not commands. there command involved ( export ) it's shell ( bash in case, although there other shells) command, not git command. changes set of environment-variables shell provides other commands. so, need un-do thing did in bash, bash command. you can use sirbranedamuj's method : export git_trace_packet=0 git_trace=0 this keeps variables in environment changes value. or, can: unset git_trace_packet git_trace which removes 2 names set of environment variables entirely. effect on git same either way. (for other commands, , other variables, there's difference between "set 0 or empty-string" vs "not set @ all", it's worth remembering both methods.) ...

java - Getting output of 2 numbers after the decimal point -

new java, trying output of variables grosspayconv, taxesconv , netpayconv have output of xx.xx(having 2 places after decimal). believe casting wrong or something. keep getting numbers no values after decimal. thanks, sorry basic question, can't seem it. p.s = if curious variable names... conv - meaning conversion system.out.println("hours worked: "); double hours = input2.nextdouble(); system.out.println("hourly pay rate: "); double payhours = input3.nextdouble(); double grosspay = payhours*hours; double grosspayconv = (int)(grosspay*100)/100; double taxes = grosspay*tx; double taxesconv = (int)(taxes * 100) / 100; double netpay = grosspay-taxes; double netpayconv = (int)(netpay*100)/100; why casting output int.update below : double grosspayconv = (grosspay*100)/100;

import - Is it possible to dynamically export data from JIRA into Excel? -

i'd set data import source in excel through can dynamically pull data jira. know used possible using excel web query , xml link jira filter wanted use. i've been unable determine if still possible. if isn't, there way achieve this? whilst little old thought note here how did using jira 7.2.2 without need 3rd party plugin use issue navigator create filter/view of jiras want available excel save filter click on export drop-down right click on csv (all fields or current fields) or xml select copy link address (i using chrome other browsers have similar function) open excel (i'm using 2016 version) select data tab > new query > other sources > web paste in url click ok , follow various steps you're done :)

Java Insert String array into text file -

i trying create text file information string array , have accomplished far, getting array text file content. appreciated , have copied of code involved far. import java.io.bufferedwriter; import java.io.file; import java.io.filewriter; import java.io.ioexception; public class writetofileexample { public static void main(string[] args) { string newdir = "new_dir"; boolean success = (new file(newdir)).mkdir(); newdir = "/volumes/mav/names/"; success = (new file(newdir)).mkdirs(); file filename = new file("/volumes/mav/names/javaprogramming.txt"); if (success) { system.out.println("successfully created file @ directory " + filename); } else { system.out.println("an error occurred creating directory or file " + filename + ". please contact system administrator."); } try { strin...

ios - Adding UIBarButtonItem to UIActionSheet navigation bar (UIDatePicker) -

Image
i created uiactionsheet , added uipickerview on top of it. now, want add 2 button on right , left of uiactionsheet navigation bar title. how can that? this did far: - (ibaction)userdidclickedonselectdate:(id)sender { uiactionsheet *actionsheet = [[uiactionsheet alloc] initwithtitle:@"select birthday date:" delegate:self cancelbuttontitle:@"cancel" destructivebuttontitle:nil otherbuttontitles:@"select", nil]; [actionsheet showinview:self.view]; [actionsheet setframe:cgrectmake(0, 100, 570, 383)]; } i'm trying add uibutton in way, can't figure out why can't see on view. when check uiactionsheet subviews, there (maybe somewhere under). - (void)willpresentactionsheet:(uiactionsheet *)actionsheet { uidatepicker *pickerview = [[uidatepicker alloc] initwithframe:cgrectmake(10, 50, 50, 216)]; // configure picker... [pickerview setdatepickermode:uidatepickermodedate]; [pickerview settag:action_sheet_picker_tag];...

powershell - Parsing of "case" constants in Switch statements does not make sense -

can explain me behaviour of second switch statement in code: function weird() { $l_ret= [system.windows.forms.dialogresult]::abort "begin switch ok" switch( $l_ret ) { ([system.windows.forms.dialogresult]::abort) { 'abort' } ([system.windows.forms.dialogresult]::cancel) { 'cancel' } } "end switch ok" "begin switch bad" switch( $l_ret ) { [system.windows.forms.dialogresult]::abort { 'abort' } [system.windows.forms.dialogresult]::cancel { 'cancel' } } "end switch bad" } if invoke weird , get: begin switch ok abort end switch ok begin switch bad end switch bad but expect is: begin switch ok abort end switch ok begin switch bad abort end switch bad [edited clearer i'm asking] in other words, kind of parsing mode in when parsing case values not recognize typed enum constants??? thanks. edit: keith's second-to-last...

javascript - Wrapping multiple asynchronous calls into syncronous -

let's have function this getallepisodes = (show)-> dfrd = new deferred() eps = [] s of show.seasons api.getmeallepisodes(s.id).done (episodes)-> eps = eps.concat(episodes) return dfrd.promise() so when should resolve dfrd ? can't right after loop, right? makes difficult without knowing exact number of episodes beforehand (without making api calls)

LINQ way to count elements in each value of dictionary? -

i have dictionary<string, string[]> , i'm hoping linq way count strings in values. i'm using ol' fashioned for: int total = 0; (int = 0; < dict.count; i++) { total += dict.elementat(i).value.length; } i thinking of select() i'd have ienumerable<string[]> or 2d array of strings. there better way? sum 1 should work that int total = dict.sum(d => d.value.length); here full working demo can test in linqpad or console app if inclined dictionary<string, string[]> dict = new dictionary<string, string[]>(); for( int = 0; < 10; i++ ) { dict["s"+i] = enumerable.range(0,10).select(s => s.tostring()).toarray(); } int total = dict.sum(d => d.value.length); console.write(total);//100 1. msdn: enumerable.sum method

bash - getting a part of the output from a sed command -

i have command : cat -n file.log | grep "start new test" | tail -1 | cut -f 1 | xargs -i % sed -n %',$s/is not alive/&/p' file.log that gives output of whole line : jan 19 23:20:33 s_localhost@file platmgt.xbin[3260]: blade 10 not alive jan 19 23:20:33 s_localhost@file platmgt.xbin[3260]: blade 11 not alive how can modify last part : blade 11 not alive can modify in way display : error:blade 11 not alive ? thank response you can use cut delimit on colons , add error message: cat -n file.log | grep "start new test" | tail -1 | cut -f 1 | xargs -i % sed -n %',$s/is not alive/&/p' file.log | cut -d: -f 4 | xargs -i % echo error: %

mdpi - Scaling ratio in Android 3:4:6:8 -

i understand scaling ratio xxhdpi? ldpi = 3 mdpi = 4 hdpi = 6 xhdpi = 8 xxhdpi = ? mdpi normal, or default. scale factor 1.0. ldpi = 0.75 mdpi = 1.0 hdpi = 1.5 xhdpi = 2.0 xxhdpi = 3.0 xxxhdpi = 4.0 you can scale factor of current screen programmatically, so: final displaymetrics metrics = resources.getsystem().getdisplaymetrics(); scale = metrics.density;

html - Bootstrap 3 and Isotope jQuery Image Centering -

i know asked question cant seem find suitable answer particular case. i want following code show 2 centered images per row. <!doctype html> <html> <head> <title>james woods</title> <!-- sets viewport responsive design --> <meta name = "viewport" content="width=device-width, initial-scale=1.0"> <!-- core bootstrap css --> <link href = "../css/bootstrap-custom.css" rel ="stylesheet"> <!-- custom site css --> <link href = "../css/style.css" rel ="stylesheet"> <!-- custom creations css --> <link href = "create-style.css" rel ="stylesheet"> </head> <div class="container"> <div class = "panel panel-info"> <div class = "panel-heading"> <h3 style = "text-align: center;">creations...

php - Access a dynamically-set $_POST value -

i dynamically creating number of textfields , want insert values of fields database. each textfield associated youtube video pull api , carries name same url of youtube video. the code have is: if($youtube_video_database) { foreach ($youtube_video_database $key => $value) { foreach ($value $key => $value) { print "<div class='content row'> <div class='videos_and_comments col col-lg-12'> <div class='videos col-lg-6'> <iframe width='420' height='315' src='$value' frameborder='0' allowfullscreen></iframe> </div> <div class='videos col-lg-6'> <form method='post' action=''> <textarea class='form-control' name='$value' id='$value' rows='14'></textarea...

html - CSS different height div elements causing grid spacing -

Image
this picture describes problem better can put words. how can grid tight without gaps . need css solution if there one. rather not change html if @ possible. there demo set here if try out ideas. variable heights must allowed can't set elements same height. ideas? demo you can alternating floats. changed of box css, adding box-sizing , removing inline-block http://jsfiddle.net/x666e/ .box{background-color:white; border:1px solid black; margin: 0; width:50%; display:block; float:left; box-sizing: border-box; } .box:nth-child(2n + 0) { float: right; }

Linking to jquery and javascript is not working -

in coda 2, can link css when link lot of stuff doesn't work because nothing happens, jquery. wrong this? btw here far in jsbin if matters main.html <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="planets.css"> <script src="planets.js"></script> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <title>planets</title> </head> planets.js: $('#submit').click(function () { var checkedplanet = $("input[name='planets']:checked").val(); $("input:radio").attr("checked", false); var age = document.getelementbyid('age').value; var newage; if(checkedplanet==='mercury'){ newage = math.round(age/0.241); alert("you be"+" "+newage+" "+ "years old on mercury!"); } if(checkedplanet==='venus'){ ...

c - Data structure for the minimum value and its offset in a mutating array -

i have int array[4096] . want know minimum value , offset in array, without having ever search through it. obviously, on setting element new value, can compared minimum , replace if applicable. however, if setting offset that's minimum, , making no longer minimum, gets more difficult. how can done, efficiently possible? you can use priority queue supporting deletion , decrease-key support this. whenever value changes, if value decreased, call decrease-key on decrease value in priority queue. if value increased, delete value , reinsert priority queue. assuming priority queue backed structure efficiently supports these operations (typically, binary heaps appropriate bookkeeping can in o(log n) time each), can support faster doing linear scan on elements each time. if don't have binary heap lying around, can use tree-backed map (keys values, elements positions in array) this. hope helps!

c# - Telerik.Web.UI.WebResource.axd 500 (Internal Server Error) -

i trying deploy c# .net 4.5 application on iis7 uses telerik ui. reason getting following error when navigate login page get http://localhost/dev/3pt_upgrade/portal/automation_framework/telerik.web.ui.webresource.axd 500 (internal server error) i have tried on the telerik web resources troubleshooting guide in web.config have <system.webserver> <validation validateintegratedmodeconfiguration="false"/> <modules runallmanagedmodulesforallrequests="true"> ... </modules> <handlers> <add path="scriptresource.axd" verb="get,head" type="system.web.handlers.scriptresourcehandler, system.web.extensions, version=4.5.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" validate="false"/> <add name="telerik.web.ui.webresource" path="telerik.web.ui.webresource.axd" verb="*" type="telerik.web.ui.webresource, t...

php - Am able to access site via my IP, but not localhost anymore -

i'm working on wordpress website installed on box using wamp, i've typed in 'localhost' address bar in order access site. i've had apache rewrite module enabled had idea of allowing people on our lan access site via lan ip. edited line of apache's httpd.conf file (per instructions on page http://www.sourcecodester.com/tutorials/php/5155/how-access-wampserver-another-computer-lan.html ) : # controls can stuff server. # # require granted # onlineoffline tag - don't remove order deny,allow deny allow 127.0.0.1 allow ::1 allow localhost (i changed 'deny all' 'allow all') saved file, accessed box via ip on ipad mini, windows pc. come machine running wamp , i'm developing site on, click 1 of navigation links on page, then 500 internal server error so can see wamp menu , site typing own ip in. images aren't loaded, , error 500 when trying login typing ip '/wp-admin' after (meaning can't log in wordpress edit eithe...

Multiple Variable Calculator Flex/Bison -

i'm writing calculator in flex/bison allows variables. right have 1 variable (x) can use. want able use more x. (rather a-z). can help? here's have far: calculator.y %{ #include <stdio.h> #include <math.h> void yyerror(char *); int yylex(void); int symbol; %} %token integer variable %left '+' '-' '*' '/' '^' %% program: program statement '\n' | /* null */ ; statement: expression { printf("%d\n", $1); } | variable '=' expression { symbol = $3; } ; expression: integer | variable { $$ = symbol; } | '-' expression { $$ = -$2; } | expression '+' expression { $$ = $1 + $3; } | expression '-' expression { $$ = $1 - $3; } | expression '*' expression { $$ = $1 * $3; } | expression '/' expression { $$ = $1 / $3; } | expression '^' expression { $$ ...

ubuntu - Instructing Pip to Use Python 3 -

i'm using ubuntu, how instruct pip use python3 installation , not python2.6 ? 2.6 default installation on ubuntu. can't upgrade break ubuntu. any single pip installation (roughly) specific 1 python installation. can, however, have multiple parallel pip installations. package manager has package called pip-3.3 or similar. if not, can manually install (run get-pip.py script using python 3.3), though you'll have careful ends in right place in path . can use virtualenv .

javascript - repeat functions in jquery based on variable in php -

i have group of images in webpage each 1 has it's own id, of id's saved in php array. want write script take id php array , pass client side , repeat jquery function each image. here did: <script> <? php ($i = 0; $i < $counterpostid; $i++) { $str = "#post".$arrid[$i]; ?> var myvar = <? php echo json_encode($str); ?> ; var myvar2 = myvar + " " + "#textcaption"; //functions repeated each image jquery(myvar).mouseover(function() { jquery(myvar2).slidedown("slow"); }).mouseout(function() { jquery(myvar2).slideup("slow"); }); <? php } ?> </script> the code work fine last occurrence in loop, want jquery code repeated images. how can that? assuming $counterpostid array id's, can implode selector var selector = '<?php echo "#post" . implode(", #post", $counterposti...

ember.js - Adding headers after RESTAdapter initialization -

i trying add authorization header adapter's request after adapter has been initialized , used. can add headers in static way @ time create applicationadapter , can't seem use headers in subsequent rest calls. trying this: var auth= "basic " + hash; app.applicationadapter.reopen({ headers: { authorization: auth } }); i have debugged restadapter in ajax method, , test adapter.headers undefined . the accepted answer doesn't address fact recommended approach not working in ember-data. recommended since: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#l88 https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#l162 , other places in file. further, issue op brings of undefined happens here: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#l619 so, following not work: app.applicationadapter.reopen(...

date - str_to_date driving me nuts in mysql -

update `smart_userstest` set lastlogin = str_to_date(lastlogin,'%d/%m/%y %h:%i') lastlogin regexp('^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$') have query have used before... except getting errors. so have imported excel spreadsheets hitting db. lots of date fields. in new format trying fix. m/d/yyyy hour:min month, day, hour, , min can 1-2 numbers. rid of hour:min portion , set date proper mysql date. account hour:min portion being left blank because have both. example error: 1411 - incorrect datetime value: '1/24/2014' function str_to_date you can solve case : update `smart_userstest` set lastlogin = (case when lastlogin '%/%/% %:%' str_to_date(lastlogin,'%d/%m/%y %h:%i') when lastlogin '%/%/%' str_to_date(lastlogin,'%d/%m/%y') end) lastlogin regexp('^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$'); to me, strange setting character column date. a better approac...

avr - avrdude and attiny2313 and avrisp -

Image
i'm trying program attiny 2313 avrdude. command line , output (the first line command entered, others output): utnmac:firmware utn$ make flash avrdude -c avrispmkii -p attiny2313 -u flash:w:main.hex:i avrdude: stk500v2_recv_mk2: error in usb receive avrdude: avr device initialized , ready accept instructions reading | ################################################## | 100% 0.00s avrdude: device signature = 0xffffff (retrying) reading | ################################################## | 100% 0.00s avrdude: device signature = 0xffffff (retrying) reading | ################################################## | 100% 0.00s avrdude: device signature = 0xffffff avrdude: yikes! invalid device signature. double check connections , try again, or use -f override check. avrdude done. thank you. make: *** [flash] error 1 update: seems problem wiring can't find tutorial on wiring needs go. right i'm using this: is entirety of circuit? fr...

javascript - AngularJS Routing Issue with named groups -

i have basic application runing localy using apache/wamp etc. setup fine, , i've built quite few apps using , angularjs. previous apps used ui-router route/state build. app i'm building using normal ngroute , ng-view. issue: using $routeprovider setup 2 routes. app.js ( basic setup angular-route added scripts , "ngroute" added deps ) $locationprovider.html5mode(true); $routeprovider.when("/", {template: "<div>home</div> <a href='/single'>single</a> | <a href='/page/34'>page 34</a>"}); $routprovider.when("/single", {template: "<div>single</div>"}); $routprovider.when("/page/:pageid", {template: "<div>page</div>"}); $routeprovider.otherwise("/"); .htaccess rewriteengine on rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^ index.php [l] when run app "/" ok. using...