Posts

Showing posts from May, 2011

r - How to draw a ggplot2 with facet_wrap, showing percentages from each group, not overall percentages? -

Image
i'd draw ggplot facet_wrap, doesn't show actual table percent, percent of given answer in each group. have this, because want show, answer selected , important each group. groups don't have same size. example data: group <- c(rep(c("group1"), times = 10),rep(c("group2"), times = 6),rep(c("group3"), times = 4)) choice <- c(rep(c("a","b","c"),length.out = 10), "a","a","a","a","b","c","b","b","b","c") df <- data.frame(cbind(group,choice)) it nice, if not use overall prop.t , prop.c show in plot, because important show, example 66.67% of group 2 prefers choice a. library(gmodels) crosstable(choice, group, prop.chisq=false, prop.t = true, prop.c = true, prop.r = false, format = "spss") this plot: library(ggplot2) g <- ggplot(df, aes_string(x="group", fill="group")...

Camera not working after android 5.0.2 update -

i working on android app using camera ( cwac ) , worked ok before updating android 5.0.2, after update if take picture camera.takepicture called in cameraview: postdelayed(new runnable() { @override public void run() { try { camera.takepicture(xact, new picturetransactioncallback(xact), new picturetransactioncallback(xact)); } catch (exception e) { android.util.log.e(getclass().getsimplename(), "exception taking picture", e); // todo out library clients } } }, xact.host.getdeviceprofile().getpicturedelay()); this picturetransactioncallback: private class picturetransactioncallback implements camera.picturecallback { picturet...

linux - list the uniq lines based on ":" delimiter -

this question has answer here: is there way 'uniq' column? 8 answers i trying write script find unique lines(first occurance) based on columns/delimiters. in case understanding delimiter ":". for example: may 14 00:00:01 server1 ntp[1006]: ntpd[info]: 1430748797.780852: ndtpq.c(20544): log may 14 00:00:01 server1 ntp[1006]: ntpd[info]: 1430748797.780853: ndtpq.c(20544): log may 14 00:00:02 server1 ntp[1006]: ntpd[info]: 1430748798.780852: ndtpq.c(20544): log may 14 00:00:03 server1 ntp[1006]: ntpd[info]: 1430748799.780852: ndtpq.c(20544): log may 14 00:00:04 server1 ntp[1006]: ntpd[info]: 1430748800.780852: ndtpq.c(20544): log may 14 00:00:04 server1 ntp[1006]: ntpd[info]: 1430748800.790852: ndtpq.c(20544): log may 14 00:00:05 server1 ntp[1006]: ntpd[info]: 1430748801.790852: ndtpq.c(20544): thisis different log de...

Drupal - Filter Nodes Retrieve by views module according to an array of categories -

i have array of taxonomies ids. created page using views module. want use contextual filtering retrieve nodes taxonomy references s id in array. example: term_taxonomy_ids = array ( 135, 195, 253, 469, 987, 6975 ); i want retrieve nodes taxonomy references ids in array. you need create relationship node taxonomy through taxonomy reference field have on node. then create contextual filter of type "term id" , using relationship created. in section "when filter value not available" select "provide default value" can past values in there or use php retrieve them. the last thing do, under more @ bottom of page, select "allow multiple values"

php - post product data if quantity more than zero -

Image
how send data (product_id, quantity) of products quantity marked more 0? i want category page this <?php if ( isset( $_post['product'] ) ) { foreach ( $_post['product'] $product ) { if ($product['q']>0) { add_to_cart( $product['id'], $product['q'] ) } } } ?> <form method="post" action=""> <input type="number" name="product[0][q]" value="0"/><input type="hidden" name="product[0][id]" value="11"/><br/> <input type="number" name="product[1][q]" value="0"/><input type="hidden" name="product[1][id]" value="12"/><br/> <input type="number" name="product[2][q]" value="0"/><input type="hidden" name="product[2][id]" value="13"/>...

ios - How to unzip a big zip file containing one file and get the progress in bytes with swift? -

i try unzip big zip file containing 1 item (more 100mb) , show progress during unzipping. i found solutions progress can determined based on amount of files unzipped in case have 1 big file inside. guess must determined amount of bytes unzipped? actually using ssziparchive following code works fine: var myzipfile:nsstring="/users/user/library/developer/coresimulator/devices/mydevice/ziptest/testzip.zip"; var destpath:nsstring="/users/user/library/developer/coresimulator/devices/mydevice/ziptest/"; let unzipped = ssziparchive.unzipfileatpath(myzipfile as! string, todestination: destpath as! string); i found no solutions this. does have hint, sample or link sample ? update: following code looks work intended, handler called once (at end of unzipping) when 1 file unzipped: func unzipfile(szipfile: string, todest: string){ ssziparchive.unzipfileatpath(szipfile, todestination: todest, progresshandler: { (entry, zipinf...

c# - Request.Files - get the first File without foreach cycle -

i'm new in web. action : [httppost] public virtual actionresult savefile(ienumerable<vacationschedule.models.vacationtypeviewmodel> vacationtypes) { foreach (string filename in request.files) { httppostedfilebase file = request.files[filename]; string type = file.contenttype; string nameandlocation = "~/documents/" + system.io.path.getfilenamewithoutextension(file.filename); file.saveas(server.mappath(nameandlocation)); } return view(mvc.admin.actionnames.documents); } question: know in request.files can 1 file. exist way file without foreach cycle? you can use firstordefault extension method: string filename = request.files.firstordefault(); if (!string.isnullorempty(filename)) { } or ternary operator index accessor: string filename = request.files.count > 0 ? request.files[0] : null;

c - Failed to add a node to linked list -

i make changes can't add more 2 nodes freez if 1 or 2 node work reason??? gave_up can nothing code till time #include <stdio.h> #include <stdlib.h> #include <ctype.h> struct info{ int num; char name[15]; struct info *next; }; struct info *first,*current,*new_s; int struct_num; void add_struct(void); int main(){ first=null; add_struct(); puts("done"); add_struct(); puts("done"); add_struct(); puts("done"); return(0); } //struct add function void add_struct(void){ new_s= malloc (sizeof(struct info)); if(!new_s){ puts("error"); exit (1); } if(first==null){ first = current= new_s; first->next = null; }else{ current=first; while(current->next!=null){ current=current->next; } current->next=new_s; current=new_s; } struct_num++; } the problem in code is if( first==null){ first->next=new_s; if first nu...

left outer join in sql need values from two tables values not coming -

i need values 2 tables using left outer join. code select rr.rrid, rr.propertyid, rr.roomtypeid, rr.occid, rr.rate, rt.accountid, rr.createdby, rr.createddate, rr.updatedby, rr.updateddate, (ot.occid) txoccid, (ot.occupancy) textoccupancy, (rt.roomtypeid) txroomtyprid, (rt.typename) textroomtype app_roomrate rr right outer join tx_myroomtype rt on rt.roomtypeid = rr.roomtypeid right outer join tx_myoccupancytype ot on ot.occid=rr.occid rt.accountid=2 in getting last table tx_occpancy values, need tx_roomtype values 2 left outer join, advance thanks i see no left joins in query, right joins. try replacing them left joins , see happens.

php - session_id() is not entering in to DB? -

i able echo session_id() , that. can't seem enter session_id() table. here function: public function login($email, $password) { $row = db::getinstance()->get('users', array('email', '=', $email)); $password = $row->first()->user_salt . $password; $password = $this->hashdata($password); $is_active = (boolean) $row->first()->is_active; $is_verified = (boolean) $row->first()->is_verified; if ($email == $row->first()->email && $password == $row->first()->password) { $match = true; } else { $match = false; } if ($match == true) { if ($is_active == true) { if ($is_verified == true) { $random = $this->randomstring(); $token = $_server['http_user_agent'] . $random; $token = $this->hashdata($token); $_session['token'] = $token; $_session[...

.net - Having trouble enabling the NuGet version of XUnit.NET on Team Build 2013 -

Image
i use xunit test framework. i've created test project, added 2 nuget packages (xunit , xunit.runner.visualstudio) , works great. visual studio discover tests. but how can configure tfs 2013 build discover tests? what's proper way that? found lot of tips think related old test runner downloaded visual studio extensions instead of current nuget package. with introduction of nuget based test runners solution enabling these test runners on team build has changed. no longer need extract .vsix or .nuget files , check them source control (after configuring build controller know download these files). install latest versions what need ensure these items have been installed on build server: visual studio has been updated update 4 nuget has been updated @ least 2.7 uninstall old test runner make sure uninstall old .vsix based test runner visual studio instance on build server , remove files source control folder if stored there. if have older version of x...

Pattern matching the fields of a map in erlang -

i'm reading book << programming erlang, 2nd edition >>. when looked through pattern matching of map's field, code snippet in book complains error on erlang prompt. %% book's version 1> henry8 = #{ class => king, born => 1491, died => 1547 }. #{ born => 1491, class=> king, died => 1547 }. 2> #{ born => b } = henry8. #{ born => 1491, class=> king, died => 1547 }. 3> b. 1491 %% eshell v6.2 65> henry8 = #{ class => king, born => 1491, died => 1547 }. #{born => 1491,class => king,died => 1547} 66> #{ born => b } = henry8. * 1: illegal pattern is there i'm missing? in advance. use := instead of => #{ born := b } = henry8. source: http://erlang.org/doc/reference_manual/expressions.html#id79796

android - Popbackstack Finishes Activity in OnBackPressed -

i have activity 2 fragments (list & details), in oncreate(), start list fragment if savedinstance null so public static final int client_list_fragment = 1; public static final int client_details_fragment = 2; private int currentfragment = 0; if (savedinstancestate == null) { //on first run, start list fragment if (currentfragment == 0) { clientlistfragment listfrag = new clientlistfragment(); getsupportfragmentmanager().begintransaction() .add(r.id.container_client, listfrag, constants.client_list_fragment_tag) .commit(); currentfragment = client_list_fragment; } else { switch (currentfragment) { case client_list_fragment: addlistfragment(); break; case client_details_fragment: adddetailsfragment(0); ...

rewrite - How to convert query string to url names -

my url ..../blogs?id=1&title=news now need covert to ..../blogs/1/news in .htaccess. please how convert this. me. use these lines: rewriteengine on rewriterule ^blogs/(.+)/(.+)$ /blogs.php?id=$1&title=$2 [r,l,qsa]

How to insert JSON OBJECT data into SQLite -

i have following code insert json object sqlite database. used loop insert each json object data database. last json object inserted database. db.transaction(function(tx) { tx.executesql('create table news_posts (id integer primary key, title text, content text,thumbnail text,url text,date datetime)'); }); (var = 0; < json.posts.length; i++) { db = window.opendatabase("news", "1.0", "posts database", 200000); db.transaction(function(tx) { tx.executesql("insert news_posts (title,content,thumbnail,url,date) values (?,?,?,?,?)", [json.posts[i].title,json.posts[i].content,json.posts[i].thumbnail,json.posts[i].url,json.posts[i].date], function(tx, res) { console.log("success"); }); }); }

javascript - .on not working on dynamic html -

i creating drag , drop thing. when drop happens create new runtime html , want bind event, have used following .on .on ( "event", "selector", function() { but not working. here snippet : $( "#wrap .dragimages" ).on( "click", "button.edit-new-modal", function() { var photoid = $(this).attr('data-username'); alert(photoid); }); .on works before drag , drop. afterwords nothing happens on clicking "button.edit-new-modal"!! what's wrong? solution? try : $(document.body).on( "click", "button.edit-new-modal", function() { var photoid = $(this).attr('data-username'); alert(photoid); });

nosql - Save data to Redis database -

public class book { public long id { get; set; } public string isbn { get; set; } public string title { get; set; } public bookpublishers publishers{ get; set; } } public class bookpublishers { public icollection<publisher> publisher = new list<publisher>(); public icollection<publisher> publisher() { return this.publisher; } } public class publisher { public string name { get; set; } public string phone { get; set; } public string address { get; set; } } i saved book redis. when read it, publishers property have no value. (count = 0), other have. i chage property publisher : public icollection<publisher> publishers { get; set; } worked. can me. read question.

datareader - Generic Relational to Composite C# Object Mapper -

i have following code that's capable of mapping reader simple objects. trouble in case object composite fails map. not able perform recursion checking property if class itself prop.propertytype.isclass type required call datareadermapper() . idea on how may achieved or other approach? also, not wishing use orm. public static class mapperhelper { /// <summary> /// extension method reader :maps reader type defined /// </summary> /// <typeparam name="t">generic type:model class type</typeparam> /// <param name="datareader">this :current reader</param> /// <returns>list of objects</returns> public static ienumerable<t> datareadermapper<t>(this idatareader datareader)where t : class, new() { t obj = default(t); //optimized taken out of both foreach , while loop propertyinfo[] propertyinfo; var temp = typeof(t); propertyinf...

html - p tag not containing ul tag -

i working on creating simple address container , had in html following simple markup: <p class="address"> <ul> <li>hello</li> <li>hello</li> <li>hello</li> </ul> </p> and following css: .address { -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.5); box-shadow: 1px 1px 1px rgba(0,0,0,.5); } now somehow <p> element not contain ul , neither box-shadow applied p tag , when replace p tag div tag, works find. div contains ul (as can seen in inspect elements) , div has box-shadow. have checked in both ff , chrome , have no idea of why glitch occurring. please see answer similar question: list of html5 elements can nested inside p element? only phrasing content can in between <p> tag , described follows: phrasing content text of document, elements mark text @ intra-paragraph level. runs of phrasing content form paragraphs.

Laravel 5 - Pass More Perminssion in controller -

i installed laravel 5 alexpechkarev package. created permission,role , users. gave permission allowed method $permissions = ['role'=>['admin', 'staff'] ]; admin have access can't access page staff user.. how can in advance this controller code.. public function __construct() { $permissions = ['role'=>['admin', 'staff'] ]; if( is_object(request::route()) ) { request::route()->setparameter('larbac', $permissions); $this->middleware('larbac'); } } here admin can access things view, edit, delete staff can't view, edit, delete page

php - MySQL Query - Records between 15 days ago End_date to till End_date -

i want return records database 15 days old end _date till end_date ! searching query last 3 days! however. want query. simple i'm not sure how it. wrote query : select * bid_post ending_date between date_sub( date(`ending_date`) , interval 15 day ) , ending_date >= curdate() but not working ! data column varchar type. storing date yyyy-mm-dd format does how can accomplish this? thanks. please try query select * bid_post ending_date between date_sub( curdate() , interval 15 day ) , curdate()

sql server - Appending charactes to a string when duplicate found -

say have table of ids, names , field flag update follows: +----+-------+---------+ | id | name | update? | +----+-------+---------+ | 1 | | y | | 2 | b | y | | 3 | xxb | | | 4 | c | | | 5 | d | y | | 6 | xxd | | | 7 | xxxd | | | 8 | e | | +----+-------+---------+ the 'update' append 'xx' name, there cannot duplicate names in table i'd append additional 'x' duplicates found. 1 table update this: +----+-------+---------+ | id | name | update? | +----+-------+---------+ | 1 | xxa | | | 2 | xxb | | | 3 | xxxb | | | 4 | c | | | 5 | xxd | | | 6 | xxxd | | | 7 | xxxxd | | | 8 | e | | +----+-------+---------+ any ideas on best way this? updating of duplicates occur initial update i'm stuck on, , i'm not sure how easy have check on , update levels of duplication, eg no ...

android-activity start from where it closed when I exit the app -

in mainactivity , have code closing application : @override public void onbackpressed() { if (exit){ intent intent = new intent(intent.action_main); intent.addcategory(intent.category_home); intent.setflags(intent.flag_activity_new_task); startactivity(intent); finish(); super.onbackpressed(); }else { exit = true; new handler().postdelayed(new runnable() { @override public void run() { exit = false; } }, 3 * 1000); } i should press 2 button when want close application . the problem ,when close application, starts activity , last activity i've been . how can start activity mainactivity not other activities ? use these lines of code.. @override public void onbackpressed() { super.onbackpressed(); if (exit){ intent intent = new intent(intent.action_main); intent.addcategory(intent.category_home); ...

Change children's opacity without setOpacityCascade in cocos2d-x 3 -

Image
i know setopacitycascade cascade alpha children, in way, children alpha. therefore, if children overlaps, overlapped part looks weird. eg. the red , blue block have same parent what want when set parent opacity what got when set parent opacity any appreciated.

profiling - How to debug a java heap OutOfMemory error in a production environment? -

our web app running in tomcat7 , we're using java 1.7.0_55....in past when we've had problems we've been able debug in our development environments using eclipse , profiler (the name escapes me @ moment). now we're getting outofmemory exception in our production environment. i'm quite leery of running profiler in production environment question is...is there way debug problem in production environment without using profiler or there light-weight enough run in production? just take heap dump of production server & analyse eclipse memory analysis tool. can copy heapdump local. eclipse memory analyzer best tool job. however, trying ui run remotely painful. launching eclipse , updating ui load on jvm busy analyzing 30g heap dump. fortunately, there script comes mat parse the heap dump , generate html reports without ever having launch eclipse! check out .

php - Duplicate MYSQL Record with child records -

i using code below duplicate event record in database, problem trying duplicate child records (i.e. event services). need copy "event services" eventservices table update eventid during copy newly copied id record. appreciated. thanks. note: eventservices table has eventid field matches id of event. $table = 'events'; $id_field = 'id'; $id = $_get['eventid']; duplicatemysqlrecord($table, $id_field, $id); function duplicatemysqlrecord($table, $id_field, $id) { include_once 'db_connect.php'; // load original record array $result = mysql_query("select * {$table} {$id_field}={$id}"); $original_record = mysql_fetch_assoc($result); // insert new record , new auto_increment id mysql_query("insert {$table} (`{$id_field}`) values (null)"); $newid = mysql_insert_id(); // generate query update new record previous values $query = "update {$table} set "; ...

c# - Asp.net GridView search with Entity Framework -

i error: data source invalid type. must either ilistsource, ienumerable, or idatasource. my code: protected void button1_click(object sender, eventargs e) { jobshopentities job = new jobshopentities(); gridview1.datasource = (from x in job.jobdescriptions (x.titlu == textbox1.text) select x).first(); gridview1.databind(); } i searched lot solution.. here got solution. rest of code on end in case have error. protected void gridview1_rowediting(object sender, gridviewediteventargs e) { gridviewrow row = gridview1.rows[e.neweditindex]; int rowid = convert.toint32(row.cells[1].text); response.redirect("~/administrator/management/managejobs.aspx?id=" + rowid); } you bind grid object first give object instead of collection whereas datasource expect collection. if not need bind gridview single record can remove call of first method , call tolist() list of records. if need first record can use enu...

java - android testing - EditText returning empty even when it has characters -

i'm trying perform functional test on edittext, sending text first gaining focus on field using following snippet: instrumentation.runonmainsync(new runnable() { @override public void run() { edittext.requestfocus(); } } and sending string via: instrumentation.waitforidlesync(); instrumentation.sendstringsync("some text"); instrumentation.waitforidlesync(); if run test , watch it, text being input edittext, when try use in assertion, edittext returns empty text: assertfalse(edittext.gettext().tostring().isempty()); i've tried logging text, returns empty string, if there no text in edittext. have tried running assertion on separate runnable or after delay no avail. temporary solution: meantime, i'm passing test manually adding edittext.settext("some text"); before assertion, though think there better or correct way. another work-around i've found using android espresso. after sending string edittext...

In OSX with oh-my-zsh installed, how to highlight the output of `ls` in oh-my-zsh with Solarized theme installed -

i configured terminal according this blog . after followed step step, ok colour of ls 's outputs grey. i googled problem , found this . says adding export lscolors=gxfxbeaebxxehehbadacad .bash_profile resolve problem. but, use zsh oh-my-zsh instead of bash . there no bash_profile @ ~ . tried add environments variable .zshrc , didn't work unfortunately. another way resolve problem install coreutils packets , use gnu ls instead. however, reluctantly install big packets ls command. how can fix problem..... i surrendered install gnu-ls instead...

breeze: how to filter collection in count condition -

i have class named a, has property b collection of class c, , want filter records of a.b.count > 0, below tried queries: breeze.predicate.create("b().length", ">", 0); breeze.predicate.create("b()[0]", "!=", null); breeze.predicate.create("b()","all","length", ">", 0); i got error:typeerror: this._fnnode1 null i want know right way filter records. i don't believe breeze supports aggregates yet, can't use count() in query. remember breeze predicate being sent server evaluation , won't know javascript properties .length. it looks there way want described in documentation: http://www.getbreezenow.com/documentation/querying-depth take @ getting count section. hope helps.

freepascal - How to compare string to integer with while do loop in pascal? -

how compare string integer using while loop in pascal? this: var destination:string; while (destination>'11') begin writeln('error'); write('destination number'); readln(destination); end; you have convert destination integer: program project1; uses sysutils; var converted: integer; destination: string; begin converted := 12; destination := ''; while (converted > 11) begin writeln('error'); writeln('destination number'); readln(destination); converted := strtointdef(destination, 12); end; end. convertion routines avalaible in sysutils: http://www.freepascal.org/docs-html/rtl/sysutils/index-5.html

stata - How to find maximum distance apart of values within a variable -

i create working example dataset: input /// group value 1 3 1 2 1 3 2 4 2 6 2 7 3 4 3 4 3 4 3 4 4 17 4 2 5 3 5 5 5 12 end my goal figure out maximum distance between incremental value s within group . group 2 , 2 , because next highest value after 4 6 . note value relevant 4 6 , not 7 , because 7 not next highest value after 4 . result group 3 0 because there 1 value in group 3 . there 1 result per group . what want get: input /// group value result 1 3 1 1 2 1 1 3 1 2 4 2 2 6 2 2 7 2 3 4 0 3 4 0 3 4 0 3 4 0 4 17 15 4 2 15 5 3 7 5 5 7 5 12 7 end the order not important, order above can change no problem. any tips? i may have figured out: bys group (value): gen d = value[_n+1] - value[_n] bys group: egen result = max(d) drop d

Use Twitter API to get tweets and output to csv file using Python -

i have code scrape tweets using twitter api , output csv file. problem that: i cannot add header of columns csv file each row seperated new line, don't know why don't want it. sorry cannot post image... my output looks like: first row: thu may 14 00:24:55 +0000 2015 tweets 0 ... second row: third row: thu may 14 00:24:59 +0000 2015 tweets 0 ... here code: # aim of program scrape tweets tweeter based on keywords` # out put txt file contains tweets tweepy import stream tweepy import oauthhandler tweepy.streaming import streamlistener import time htmlparser import htmlparser import json import csv ckey = xxxxxxxxxx csecret = xxxxxxxxx atoken = xxxxxxxxxxxxxxxxx asecret = xxxxxxxxxxxxxxx class listener(streamlistener): def on_data(self, data): try: data_json = json.loads(htmlparser().unescape(data)) tweet_time = data_json["created_at"] tweet_text = data_json["text"] retweet_count...

c# - SqlCommand state closed when SqlConnection state is open -

i having intermittent issue sqldatarreader class have opened sqlconnection , state open , when create sqlcommand sqlconnection , sqlconnection 's state closed . occurs approximately 1 in 10 attempts, , might timing issue. note rather putting connection in using block, open/close connection independently execute multiple commands @ once, issue occurs on first time command executed on connection has been opened. the connection code is: private sqlconnection sql; public result connect(string database) { string connection = config.environments[config.environment][database]; try { // create , open connection sql = new sqlconnection(connection); sql.open(); if (sql == null || sql.state != system.data.connectionstate.open) return new result(false, "connect database", "could not connect database [" + connection + "]"); return new resul...

How to Call a Go Program from Common Lisp -

i have go program cannot rewritten in common lisp efficiency reasons. how can run via common lisp? options far: 1. cffi using foreign function interface seems me "correct" way this. however, research did lead directly dead end. if winner, resources there learn how interface go? 2. sockets leaving go program running time while listening on port work. if best way, i'll continue trying make work. 3. execute system command this seems kinds of wrong. 4. unknown or there awesome way haven't thought of yet? it depends on want do, 1-3 viable options 1. cffi to work need use ffi on both go , lisp side. need extern appropriate function go c functions, , call them using cffi lisp. see https://golang.org/cmd/cgo/#hdr-c_references_to_go on how extern function in go. in case create dynamically linkable library (dll or file) rather executable file. 2. sockets (ipc) the second option run go program daemon , use form of ipc (such sockets) commu...

javascript - Race conditions on directives -

i have directive calculates height , distance top of window of element passed in id attribute. issue i'm running have several of these directives running (on elements attached same directive), , i'm running race condition of directives lower down in dom running before ones higher whatever reason. is there way can make bottom ones wait ones higher via promise or something? if so, how implement that? there better way of handling this? if want code executed directive in descending order (higer in dom comes first), should either put code in directive's controller , or prelink methods. the default link method shortcut postlink executed in ascending order. that being said, don't know code making guess, sounds service more appropriate directive, unless calcul you're doing done directly in directive element, in case using $element should enough. should not pass id or selector directive.

mongodb - Mongo username and email unique fields validation -

hi want tell user 1 taken if username or email way im validating in save function if finds duplicate give error 11000 cant specify 1 taken. want error give index or can put in if statement explaining 1 duplicate key can more specific error. there way can accomplish this? why im getting index: 0? shouldn't different each field? let me know if have questions. schema var user = db.schema({ name: { type: string, required: true}, username: { type: string, required: true, index: { unique: true }}, email: { type: string, required: true, index: { unique: true }}, password: { type: string, required: true, select: false}, admin: { type: boolean, required: true}, verify: { type: boolean, required: true}, created_at: { type: string, required: true, default: date.now }, updated_at: { type: string, required: true, default: date.now }, campaigns_donated: [] }) post action router.post('/register', function(req, res){ var user =...

c# - Remove first 4 bits from a byte array (shift left) -

this question has answer here: remove first 16 bytes? 4 answers i have byte array of 3 bytes : byte[] vg = new byte[3]; this values of array: 00-28-a0 . have remove first 4 bits, , result: 02-8a-00 // shift 4 left vg[0] = (byte)((byte)(vg[1] >> 4) + (byte)(vg[0] << 4)); vg[1] = (byte)((byte)(vg[2] >> 4) + (byte)(vg[1] << 4)); vg[2] = (byte)(vg[2] << 4); // shift 4 right vg[2] = (byte)((byte)(vg[2] >> 4) + (byte)(vg[1] << 4)); vg[1] = (byte)((byte)(vg[1] >> 4) + (byte)(vg[0] << 4)); vg[0] = (byte)(vg[0] >> 4);

c++ - Qt sending image between dialog -

i'm writing simple application 2 dialogs, first 1 original image, sent dialog , processed. image processed sent first dialog: imagedialog::imagedialog(qwidget *parent) : qdialog(parent), ui(new ui::imagedialog) { ui->setupui(this); ui->graphicsview->setscene(&mscene); mpixmapitem = new qgraphicspixmapitem(); connect( this, signal( sigcommitimage(qimage) ), parent, slot( updateimage(qimage) ) ); } imagedialog::~imagedialog() { delete ui; delete mpixmapitem; } void imagedialog::processimage(const qimage &image ) { cv::mat tmp(image.height(),image.width(),cv_8uc4,(uchar*)image.bits(),image.bytesperline()); cv::cvtcolor(tmp, tmp, cv_rgba2gray); mimage = qimage( (uchar*)tmp.data, tmp.cols, tmp.rows, tmp.step, qimage::format_indexed8 ); mpixmapitem->setpixmap(qpixmap::fromimage(mimage)); mscene.clear(); mscene.addpixmap(qpixmap::fromimage(mimage)); mscene.setscenerect(0, 0, mimage.widt...

Ember.js, throttle REST adapter calls -

i using parse, allows 30 reqs/sec backend. therefore, i'd throttle calls going parse via rest adapter (specifically ember-parse-adapter , extends ds.restadapter ). i tried throttling ajax method, assumed needed return promise: export default parseadapter.extend({ applicationid: env.app.applicationid, restapiid: env.app.restapiid, ajax: function(url, type, options) { var self = this; return new ember.rsvp.promise(function(resolve, reject) { ember.run.later(this,resolve,5000); // prefer ember.run.throttle, not sure if work }).then(function() { return self._super(url,type,options) }); } }); however error: typeerror: cannot read property 'results' of undefined @ exports.default.ds.default.restserializer.extend.extractarray (vendor.js:115817) @ apply (vendor.js:30197) @ superwrapper (vendor.js:29749) @ ember$data$lib$system$serializer$$default.extend.extractfindall (vendor.js...

spring - Unable to autowire attributes in package -

Image
for reason, in config package, can not autowire fields while in controller package, there not seem problem. for instance: servlet-context.xml <context:component-scan base-package="service, controller, config" /> root-context.xml (tried adding service here well) <context:component-scan base-package="security" /> this not work: setup class inside config package. receive null pointer error. @component public class setup { //inside config package @autowired private userservice userservice; //null pointer error /*..other stuff */ } this work: controller inside controller package: @controller @requestmapping(value="/contact") public class contactcontroller { //inside controller package @autowired private userservice userservice; //this works /*..other stuff..*/ } why work controller package not config package? this happens because @service class userservice not visible in of 2 packages "...

PHP/MySQL Critical section -

i'm using php pdo , innodb tables. i want code allow 1 user-submitted operation complete, user can either cancel or complete. in case user posts both operations, want 1 of requests fail , rollback, isn't happening right now, both completing without exception/error . thought deleting row after checking exists enough. $pdo = new pdo(); try { $pdo->begintransaction(); $rowcheck = $pdo->query("select * table id=99")->rowcount(); if ($rowcheck == 0) throw new runtimeexception("row isn't there"); $pdo->exec("delete table id = 99"); // either cancel, 1 bunch of queries. if (isset($_post['cancel'])) ... // or complete, bunch of queries. if (isset($_post['complete'])) ... // bunch of queries on other tables here... $pdo->commit(); } catch (exception $e) { $pdo->rollback(); throw $e; } how can make cancel / complete operations critical section? second o...

python - Paypal Payflow Pro return url does not work correctly - 'processTransaction.do' appended - raises 404 -

currently trying migrate working php paypal payflow implementation new python-based system. i use secure token hosted checkout pages. secure token works fine , redirected checkout page (although has horrible formatting errors). the problem: after payment should redirect return url. works 'processtransaction.do' appended it. return url defined as: ' https://mywebsite.com/paypal/succes/ ' redirected to ' https://mywebsite.com/paypal/succes/processtransaction.do ' , raises 404. my secure token request parameters: params = {} params["partner"] = "paypal" params["vendor"] = "...." params["trxtype"] = "s" params["amt"] = payment_amount #amount pay params["createsecuretoken"] = "y" params["securetokenid"] = time.time() #needs unique params["user"] = "...." params["pwd"] = "...." then send request , catch return...

c++ - Function to multiply 2 arrays -

i need make function multiplies 2 arrays , puts result in third array print using "print function". if input array11: 5, 10, 20; , array22: 1, 2; should result: result_array:5, 10, 10, 20, 20, 40. each element first array multiplied each element second array , stored in third array. but don't expected result. instead random numbers. can me figure out doing wrong? array11 , array22 first 2 arrays array_result resulting array dim1 , dim2 dimensions of first 2 arrays dim3 dimension of third array calculated outside function this: dim3 = dim1 * dim2; #include <iostream> using namespace std; void remplir(int array[], int dim); void aficher(int array[], int dim); void multiplier(int array11[], int array22[], int dim1, int dim2, int dim3); int main() { int dim1 = 0, dim2 = 0, dim3; cout << "la dimension de la 1ere table?" << endl; cin >> dim1; while (dim1 > 20) { cout << "la dimension maximum est 20! r...

architecture - Determining what segment, page, and byte a hex address is trying to access -

so i'm reviewing final , i've come across problem can't find solution to. i've looked through google try , find answers 1 thing has come up. https://stackoverflow.com/questions/5927684/calculating-page-size-and-segment-size# = this link helped answer of questions not all. can't use reference in selected answer don't have access page. question can't figure goes follows: which segment, page, , byte in page hex address (000a0c02) trying access? the step know take convert hex address binary , i've done follows: 0000 0000 0000 1010 0000 1100 0000 0010 can't point me in direction of go here? i'm not asking answer, i'm looking formula's/steps need take. thanks

html - Javascript validation form with no alert() -

im trying build html form validate if user entering values in each of input boxes. far i've found in google examples when user leaves input box blank call alert() annoying users if have fill 10 boxes , accident hit submit have close 10 alerts. thinking if possible show red message next empty box(es) indicating boxes empty. here code showing alerts: <form name="examentry" method="post"> <input type="text" id="name" name="name" /> <input type="text" id="subject" name="subject" /> <input type="text" id="examnumber" name="examnumber" /> <input type="submit" name="submit" value="submit" onlick="return validateform()" /> </form> javascript: function validateform(){ var result = true; var msg = ""; if(document.examentry.name.value==""){ msg...

android - QML - Show MenuBar or Menu items by click event -

is there way show menubar , menuitem onclicked event of control (or other event)? i've tried use popup function of menu did nothing. purpose re-implement menu button in applicationwindow on android application build make alike different current menu button, or use clicking on other widget popup other menu. learning qml 3 weeks, can me it? think should quite easy, , want make more simpler , logical. appreciated code examples. looks wrong direction of question. understood need show menu , it's quite easy done popup function. example standard template of qtquick project button show specified menu. menu { id: menufile title: qstr("&file") menuitem { text: qstr("&open") ontriggered: messagedialog.show(qstr("open action triggered")); } menuitem { text: qstr("e&xit") ontriggered: qt.quit(); } } button{ onclicked: menufile.popup() } but i've tried...

c# - FileInfo in UserSettings saves as Null? -

i've looked @ fileinfo class , see marked serializableattribute. not understand attribute indicates, me suggests fileinfo class should serialize xml file settings save, not case, fileinfo setting comes through null when project loads. how can save fileinfo usersettings? you can't. xmlserializer requires parameter-less constructor - fileinfo not have. it's marked serializable because there other serializers don't have same requirement. related question.

nginx - Highload rails server with backgrounder architecture -

here task. every second backgrounder task should generate json based on data. operation not cpu intensive ( network) , generates json content (5-10kb). operations take 200ms. also have 1000 clients asking content once every few seconds. let's it's 200 requests/sec. server should output current actual json. currently have rails 4+nginx+passenger+debian sever doing other jobs, related work. being student want make server in cost-effective way having ability easy-scale in ways: adding few more backgrounder jobs, generating more json's increasing number of requests 10 000 per second currently have linode 2048 ssd 2 cpu cores. questions are: what gem/solution should use backgrounder tasks ( written in ruby ) how effectivly store actual json , pass backgrounder(s) rails/nginx. how make serving json fast possible. you mentioned "server should output current actual json", guess json generation may not become bottleneck can cache memcache...

php - Can I create object of child class using method from parent class -

so have parent class: class table { protected static $table_name; protected static $tbl_columns=array(); public static function instance($row_from_db){ $object=new self; foreach (self::$tbl_columns $key=>$property){ $object->$property = $row_from_db[$property]; } return $object; } } when call "instance" method in child class of class table generates object of class table not object of child class. is there way code? or advice on how solve it? thanks since php 5.3.0 use late static bindings : $object = new static; foreach (static::$tbl_columns $key=>$property){ this works: $class = get_called_class(); $object = new $class; foreach ($class::$tbl_columns $key=>$property){

c# - Get Datetime of month and year -

i trying month range of first of month last 2 days (-2) so example: may 1st 2015 or 05/01/2015. i want pull last 2 days end date 04/29/15 , first of month 04/01/15. so range 04/01/15 - 04/29/15 when current day 05/01/2015. so if current day 05/02/15 want range 04/01/15 - 04/30/15. but once hits 05/03/15 switches 05/01/15. so have far: static datetime getmonthly = datetime.today.adddays(-2); static string startmonthly = ????? static string endmonthly = getmonthly.tostring("yyyy-mm-dd"); i know how endmonthly not first day of getmontly -2 days. also need grab year according getmonthly. when 01/01/2016, want grab 12/01/15 - 12/30/15 does know how this? i know there better way ended doing this: static datetime getmonthly = datetime.today.adddays(-2); static string startmonthly = getmonthly.year + "/" + getmonthly.month.tostring().padleft(2, '0') + "/" + "01"; static string endmonthly = get...

tomcat - Connection Pool Empty Hibernate 4, but Unable to Find the Culprit -

i'm monitoring sql database connections every 5 minutes. days it'll hover around 5 connections (my idle) i'm @ 50. recursive issue because can't see why jump 5 50 within 5 minutes 0 traffic. i'm using hibernate 4 , tomcat , know of issue in hibernate patched in 4.3.2, i'm on 4.3.5 more details: pool empty event happens every day @ 7:13:20pm... sounds automatic. using quartz , runs every 1 minute, can't see how they're related. my properties: jmxenabled = true initialsize = 5 maxactive = 50 minidle = 5 maxidle = 25 maxwait = 10000 maxage = 10 * 60000 timebetweenevictionrunsmillis = 5000 minevictableidletimemillis = 60000 validationquery = "select 1" validationquerytimeout = 3 validationinterval = 15000 testonborrow = true testwhileidle = true testonreturn = false jdbcinterceptors = "connectionstate" defaulttransactionisolation = java.sql.connection.transaction_read_committed environment: tomcat 7.0.59 java 1.7.0 upda...

ios - App Interruption - Siri Fails To Hear Human Voice -

in team's ios app have bug when siri invoked while our app running. siri pops , waveform shown briefly , appears not detect one's voice waveform remains flat. thereafter begins list things can ask siri. we using xcode 6.3, tested on ipad mini ios 8.3 iphone 5 ios 8.3. the app never uses microphone or queries of device audio inputs can't see problem attributed our app using microphone directly. play looping ambient music , has sound effects. is there specific should calling an interruption ensure siri work properly? has experienced similar issues? this not related app. ios sdk doesn't provide siri api lead kind of events. you may try pause ambient music/sounds effects whenever app goes in background. (in appdelegate.m)

c - Convert WAV to base64 -

i have wave files (.wav) , need convert them in base64 encoded strings. guide me how in python/c/c++ ? python the easiest way from base64 import b64encode f=open("file.wav") enc=b64encode(f.read()) f.close() now enc contains encoded value. you can use bit simplified version: import base64 enc=base64.b64encode(open("file.wav").read()) c see this file example of base64 encoding of file. c++ here can see base64 conversion of strings. think wouldn't difficult same files.