Posts

Showing posts from September, 2013

oracle - Error in dynamic SQL query. Missing expression with correct syntax -

i have problem working stored procedure on work. it's stored procedure used several bigger procedures. procedure work called c , , ones call a , b . the problem have when run a , goes smoothly, when run b , missing expression error , don't when call a , tough b , a have same flow of procedure calls (so, it's kind of weird error). the c procedure has same code: procedure c ( lo in varchar2, en in varchar2, ca in array1d, ia in number, ar in array2d ) cq varchar2(5); et varchar2(2000); ol varchar2(100); ne varchar2(100); te varchar2(100); xu varchar2(100); begin lo := '05'; te := 'var'; cq := ''''; ol := cq || lo || cq; te := cq || te || cq; ne := cq || en || cq; et := 'par1 = ' || ca(1) || ',' || 'par2 = ' || ca(2) || ',' || 'par3 = ' || ca(3) || ',' || 'par4 = ' || c

c# - NUnit Visual Studio run TearDown on test cancel -

is there way make nunit tests run [teardown] method when test interrupted clicking on "cancel" in test explorer? at moment happens test stops executing , browser stays open. thanks as far know, if cancel test running, vs stops there execution, nothing more of code executed, "idisposable" implementation or "try/finally" steatments.

jquery - Receive value from callback javascript function -

i having problem following programming scenario i want confirm deletion of tag before tag deleted when user confirm message tag removed. what facing callback function doesn't return true value , returning null due asynchronous js callback. here code $(document).ready(function () { $("#categories").tagit({ allowspaces: true, beforetagremoved: function (evt, ui) { var isdeleted; $.confirm({ title:"deactivate confirmation", text:"are sure want deactivate idea? users not able see idea more.", confirm: function(button) { isdeleted = true; }, cancel: function(button) { isdeleted = false; }, confirmbutton: "yes", cancelbutton: "no", confirmb

Mapping very large GPS tracks using HTML and Javascript -

i'm making blog upcoming bicycle tour , i'd have map showing progress. i've searched hours existing product or service , nothing came close. know it's possible because i've seen done before ( https://dl.dropboxusercontent.com/u/19443192/billy/billysroute.html ). i recording each day's ride , getting single .gpx file each day. ideally i'd able upload each day's .gpx online database google drive or dropbox , have map automatically update including new track. nice able embed map on blog, linking map fine. so far haven't been able find method place many tracks on single online map. tried dissecting example posted above see how made , found writing simple html/javascript might answer. did best reading through google developer pages having no coding experience pretty overwhelmed. tl;dr questions are: 1) how ( https://dl.dropboxusercontent.com/u/19443192/billy/billysroute.html ) made and/or how can make similar 1 using several gps tracks? 2) pos

javascript - Angular bootstrap ui accordion group "open one at a time" not working -

i have been using angular ui-bootstrap . in here oneatatime not working though value set true . here code. <div ng-repeat="group in groups track group.key"> <uib-accordion close-others="oneatatime"> <uib-accordion-group> <uib-accordion-heading > <div> {{ group.title }} <i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': status.open, 'glyphicon-chevron-right': !status.open}"></i> </div> </uib-accordion-heading> </uib-accordion-group> </uib-accordion> </div> plnkr link. your html structure wrong. there should single uib-accordion element , multiple uib-accordion-group element. change code this: <uib-accordion close-others="oneatatime"> <uib-accordion-group ng-repeat="group in groups track group.key"> <uib-accordion-he

arrays - Customize legend AngularJS -

i want draw bar chart in angularjs this html: <canvas id="bar" class="chart chart-bar" chart-data="datta" chart-labels="labels" chart-legend="true"> </canvas> i haven't used chart library, idea want customize legend , want declare array data $scope.legend = ["item1", "item2"] and array want display below chart. there way ? thanks in advance! i'm not sure if got it. if you're trying set legends of graph need set in chart options, not setting chart-legend true. you're html should like: <canvas id="bar" class="chart chart-bar" chart-data="datta" chart-labels="labels" chart-options="chart-options"></canvas> than need create $scope.chart-options like: $scope.chart-options = { legend: { display: true, }, }; you can have more info here: chartjs legend documentation

c# - Sum of Values in SortedList and Condition on Keys -

i want sum values (time range start till end) of sortedlist<datetime, double> linq. keys contain dates of workingdays , values contain number of possible workhours given day. question want answer is, how many hours possible in given timeframe. i managed count of keys, i'm stuck @ sum. the code count keys (thanks stackoverflow) looks this: double ats = (from n in daysandhours.keys n >= start n <= end select n).count(); how have change it, fill ats values in date range? thanks! assuming post applying condition want add values, use following code , modify required double result = daysandhours.where(n => n.key >= start) .where(n => n.key <= end) .sum(n => n.value)

Spring boot with spring data repository - cannot autowire own repository -

Image
i'm trying create new project spring boot use spring data (spring repositories...), i'm getting error org.springframework.beans.factory.beancreationexception: error creating bean name 'hqltester': injection of autowired dependencies failed; nested exception org.springframework.beans.factory.beancreationexception: not autowire field: com.service.companyrepository com.example.hqltester.companyrepository; nested exception org.springframework.beans.factory.nosuchbeandefinitionexception: no qualifying bean of type [com.service.companyrepository] found dependency: expected @ least 1 bean qualifies autowire candidate dependency. dependency annotations: {@org.springframework.beans.factory.annotation.autowired(required=true)} @ org.springframework.beans.factory.annotation.autowiredannotationbeanpostprocessor.postprocesspropertyvalues(autowiredannotationbeanpostprocessor.java:334) ~[spring-beans-4.2.6.release.jar:4.2.6.release] @ org.springframework.beans.factory.su

javascript - How to send cookies in an Image() constructor -

i'm injecting image canvas have securely passing cookies request. issue image constructor doesn't seem send cookies request when src set. cookies not accessible through js, sent browser. var img = new image(); img.setattribute('crossorigin', 'anonymous'); validateurl(originalurl, function (validatedurl) { img.src = validatedurl; //get fails after happens }); img.onload = function () { drawimageprop(context, img); } if set crossorigin attribute on image, cookies not sent request image. that's how feature written work. cookies tied specific domain/subdomain (and optionally path within domain). when requesting image, cookies domain image being requested automatically sent image request. the browser gives javascript access cookies in same origin host web page. so, javascript has no ability read cookies other domain. so, when request image setting .src property, cookies belong domain of image url sent image request automatically

python - Pyglet VBOs glVertexPointer -

Image
i've used pyopengl long time, now, i've switched pyglet. pyglet more strict pyopengl, i'm learning it. i've written simple code using vbos render triangle(i've took base pyglet tutorial), doesn't works me. it shoud render colored triangle, instead of, renders white triangle. wrong? here's code: from pyglet.gl import * window = pyglet.window.window() glenableclientstate(gl_vertex_array) vertices = [ 0,0,0, window.width,0,0, window.width,window.height,0] colors=[1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0] class vbo(): def __init__(self): self.buffer=(gluint)(0) glgenbuffers(1,self.buffer) def data(self,data): data_gl= (glfloat * len(data))(*data) glbindbuffer(gl_array_buffer_arb, self.buffer) glbufferdata(gl_array_buffer_arb, len(data)*4, data_gl, gl_static_draw) def bind(self): glbindbuffer(gl_array_buffer_arb, self.buffer) def vertex(sel

spring - Error handling on controller SpringMVC -

i developing application in jax-rs , spring mvc. want notify client each time when default error occured 400, 403, 404, 405 , 415. controller @controller @requestmapping("/customer") public class customercontroller { @autowired customerservice customerservice; // ........xxxxxx..............xxxxxxx................xxxxxxx.............// @crossorigin @requestmapping(value = "/", method = requestmethod.get, produces = mediatype.application_json_value) public @responsebody string fetchcustomer() throws jsonprocessingexception { return new objectmapper().writevalueasstring(customerservice.fetchallcustomer()); } // ........xxxxxx..............xxxxxxx................xxxxxxx.............// } client $http({ method: "get", contenttype: "application/json"

java - Selenium Apply button not working on combo box? -

i have problem apply button. have combo box filter , fine, switching between squares.but when suppose apply, somehow continue not selected , test finishes successfully, there no filtering need. can check code , part inspector bug. maybe missing something? my java code: if (type.equals("")) { elementlist = driver.findelements(by.xpath("//div[@id='" + id + "_menu']//a[@class='fitext']")); if (elementlist.size() > 0) { if (driver.findelements(by.xpath("//div[@id='" + id + "_menu']//div[@class='cfapplybuttoncontainer']//button[@class='tab-button']//span[@class='label'][text()='apply']/..")).size() > 0) { type = "multi_checkbox_with_apply"; }else { type = "multi_checkbox_without_apply"; } } } inspector bug: <div class="cfapplybuttonconatiner" style="height: 21px;">

java - Swing & AWT: ContentPane items not showing in JFrame -

i'm creating basic java swing app having problems content pane not showing objects. this main class calling other classes in future , calling frame.java: public class main { public static void main(string[] args) { system.out.println("hi"); frame frameobject = new frame(); frameobject.main(); } } this frame class create frame: import javax.swing.*; import java.awt.*; public class frame { public static void main() { swingutilities.invokelater(new runnable() { public void run() { jframe frame = new mainframe("warlock of firetop mountain"); //implementing toolkit allow computer dimensions of screen , assign them 2 int values toolkit tk = toolkit.getdefaulttoolkit(); int xsize = (int) tk.getscreensize().getwidth(); int ysize = (int) tk.getscreensize().getheight(); frame = ne

git - github exclusions on live server -

so using tutorial here: https://gist.github.com/oodavid/1809044 to deploy gituhub project our live server. looks , easy enough, have set of files on our production server want excluded versioning, because special production versions of same files have in repository, , not changed. have files on live server, don't need commit them or anything. can't have them overwritten or deleted when pull origin onto server, , see how delete them if didn't exist in repo and/or there like-named files(but development versions) in repo. else set way on our server svn way when, , have same git. open other ways of handling it. i know need file exclusions... not sure how tell git exclusions file given flow listed in github tutorial. sincere help. appreciated. you can modify deployment script replacing git pull these commands: git commit -a -m "local changes" , it's required because cannot merge when have uncommited changes; git fetch , fetch changes remot

api - c# accessing methods based on condition -

i have application have 2 parts (2 separate application): designer (call configurationbuilder) , executer (call configurationexecutor). there class library object consist of manager class , shared above applications. within configurationbuilder user can run custom code consume methods of manager class , these methods create objects. (serialize , create dbtables) configurationexecutor user consume methods of manager class , these methods create rows on tables. now, want prevent user consuming api in configurationbuilder sepcific configurationexecutor , vise-versa. appreciate sharing best practices. thanks. create 2 interface separate methods suppose manager class class manager() { method1(); method2(); method3(); method4(); } divide methods in interfaces imethodsforconfigurationbuilder { method1(); method2(); } imethodsforconfigurationexecutor { method3(); method4(); } implement these interfaces in on manager manager : imethodsforcon

c - Wrong output in printf -

ok simple , scolded im new c , trying learn best can. have problem wich solved , logic works pretty good.but whenever there wrong input shows message on screen , plus condition not true.so whenever there supposed invalid input message ne - wich print out if condition isnt true.this code : #include <stdio.h> #include <stdlib.h> int main() { int a, b; scanf("%d %d", &a, &b); if(a <= 0 || b <= 0) { printf("invalid input"); } else { if(a < b) { int tmp = a; = b; b = tmp; } } a/=10; int c1,c2; while (a!=0 && b!=0){ c1 = a%10; c2 = b%10; /= 100; b /= 10; } if (c1 == c2) printf("paren\n"); else printf ("ne\n"); return 0; } its because there nothing thats stop so: if want terminate program return whenever if condition true: if(a <= 0 || b &

dataframe - Reshape data in R: merge by rows and rows to columns -

this question has answer here: how reshape data long wide format? 7 answers so - have data.frame looks this: id snpindex a1 a2 id1 1 b id1 2 b b id1 3 b id2 1 b id2 2 b b id2 3 id3 1 b b .... and this: id 1_a1 1_a2 2_a1 2_a2 3_a1 3_a2 id1 b b b b id2 b b b id3 ... i.e. 1 row each id , 2 columns each snpindex - each column 1 a1/a2 value. i appreciate help! i'm sure a) duplicate , b) code can simplified appears after dat <- data.frame( id = c("id1" , "id2" , "id3") , snpindex = c(1,2,3) , a1 = c("a", "b" , "a") , a2 = c("b" , "b" , "b") , stringsasfactors = f) library(tidyr) library(dplyr) dat %>% gather( key, v

vb.net - Error copying from resources -

Image
while copying resources folder under appdata folder: error, i'm not finding mistake in code.. private sub help_load(sender object, e eventargs) handles mybase.load file.writeallbytes(mainpath & "\help.rtf", my.resources.helprtf) dim helprtf = (mainpath & "\help.rtf") helpbox.loadfile(helprtf) end sub helprtf .rtf file, mainpath directory under %appdata% folder error: value of type 'string' cannot converted 'byte()'. error at: my.resources.helprtf the reason why error because second parameter of file.writeallbytes() method takes byte() , not string . if want write text ( string ) file, can use file.writealltext() method. since rtf's can contain images, text, etc. treating text can corrupt , needless say, encoding issues might occur. so, instead of using file.writealltext() method, change filetype of helprtf resource binary instead of text this: after that, can use code was: private su

ssh - Why suddenly is Capistrano unable to read from my Bitbucket Git repository during deploy? -

i use capistrano (v3.5.0) deploy small rails application local development machine vps hosted on linode using deployment key set on bitbucket. late last week, working charm. today, however, when run usual cap deploy command, fails @ third step when tried read bitbucket git repository: debug [6906a62c] command: ( export rbenv_root="$home/.rbenv" rbenv_version="2.2.1" git_askpass="/bin/echo" git_ssh="/tmp/app/git-ssh.sh" ; /usr/bin/env git ls-remote --heads git@bitbucket.org:klenwell/app.git ) this error: debug [6906a62c] conq: repository access denied. debug [6906a62c] fatal: remote end hung unexpectedly i've done obvious troubleshooting: googled errors messages, confirmed vps operational, verified repository accessible, double-checked ssh keys, confirmed ssh agent running. if else fails, try generating new key on vps host. these points in particular have me flummoxed: there have been (as far can tell) no ch

c# - GlassMapper - GetItem<T>() method is failing to get item as specific type -

i'm trying item using glassmapper follow: var mycustomobj=sitecorecontext.getitem<imy_custom_type>(itemid); but mycustomobj null. when try item iglass_base object, works: var mycustomobj=sitecorecontext.getitem<iglass_base>(itemid); edited: here how imy_custom_type looks: /// <summary> /// imy_custom_type interface /// <para></para> /// <para>path: /sitecore/templates/user defined/###/pages/my custom type</para> /// <para>id: dfacd744-0cf8-4917-922c-4baeb07dfe35</para> /// </summary> [sitecoretype(templateid=imy_custom_typeconstants.templateidstring, automap = true )] //, cachable = true public partial interface imy_custom_type : iglassbase , global::sc.global.models.templatemodels.base_templates.imetadata, global::sc.global.models.templatemodels.base_templates.ibase_background_image { /// <summary> /// custom field. /// <para>

html - Eliminating Span Elements in a nested TD using BeautifulSoup -

Image
i'm pretty new webscraping, wrote small little script extract player scores site: http://fold.it/portal/players here's code: import urllib2 bs4 import beautifulsoup soup = beautifulsoup(urllib2.urlopen("http://www.fold.it/portal/players").read() row in soup('tr', {'class':'even'}): rank = row('td')[0].string td2 = row('td')[1] name in td2('a'): user = name.text score = row('td')[2].string print rank, user, score now, works pretty except user has 2 other scores in name well. looking @ html, seems there 2 span elements after href. my first thought split 'user' on white space, names have spaces in them, didn't work. thought looking numeric, users have numeric names well. i figure eliminating span best option. however, i'm not sure best way parse them out be. appreciated! the scores in separate span tags - use it: for row in soup('tr', {'class&

c++ - clang rewriter: add structure definitions to invalid program -

i need rewrite body of c/c++ code inject structure definitions automatically when used. specifically, need recognize function bodies of form: int func(struct struct_x_y *args) { /* access args->field here */ } ... , generate structure declaration prior function's body, e.g.: struct struct_x_y { int field; }; int func(struct struct_x_y *args) { /* access args->field here */ } when trying use clang's rewriter insert structure declaration (e.g. following this skeleton program ), errors because original program text doesn't compile without these declarations -- function attempts access fields on undefined structure. is possible use clang's rewriter on program isn't valid c++? can place further restriction -- function body invalid, rest of program fine. (i can, of course, hack ugly solution uses regular expressions sort-of-detect function signature , generate structure, i'd rather harness power of clang's parser , rewriter.) w

php - PHQL "WHERE xxx IN ()" can get only 1 data -

i'm creating restful api phalcon. want data "shop" table ids. php code: $app->post('/api/shops/search', function () use ($app) { $ids_shop = $app->request->getjsonrawbody(); $ids = array(); foreach($ids_shop $id){ $ids[] = $id->id_shop; } $ids_str = implode(",", $ids); $shops = getshopsdata($ids_str, $app); return $shops; }); function getshopsdata($ids_shop, $app) { $phql = "select * shops shops.id in ( :ids: )"; $shops = $app->modelsmanager->executequery($phql, array( 'ids' => $ids_shop )); return $shops; } test: curl -i -x post -d '[{"id_shop":1},{"id_shop":2}]' http://localhost/sample/api/shops/search however can 1 data id 1. , tried it: curl -i -x post -d '[{"id_shop":2},{"id_shop":1}]' http://localhost/sample/api/shops/search this returns 1 data id 2. why cannot multiple

javascript - Performing a delete in mvc-5 action through JQuery -

i have website i'm working on, user can add or delete booked traffics tram network. i've come far delete button. <input type="button" value="delete" class="deletetraffic btn btn-link noborder nobackground" data-id="@traffic.id" /> jquery(document).ready(function() { jquery('.deletetraffic').click(function() { var id = $(this).data('id'); var url = '@url.action("deletetraffic", "trafficdate", new { trafficid=id })'; url = url.replace("id", id); $.post(url, function (data) { if (data) { $('#pnledittraffics').hide().fadein('fast'); } else { alert("error."); } }); }); }); public actionresult deletetraffic(int id) { return json(trafficdata.deletetraffic(id)); } the button works fine , parameter comes through fine, action in contr

Remove a parameter from queryParams angular 2 -

i navigate page in app query parameter. after parameter url want delete it, ideally have this: let usertoken: string; this.sub = this.router .routerstate .queryparams .subscribe(params => { usertoken = params['token']; params['token'].remove(); }); but remove function doesn't exist. have alternative? just in case people find thread (like did). have scenario receive jwt token in query string (/login?jwt=token). needed fetch token (and store etc), needed make sure got safely removed url. reloading login route (by using this.router.navigate(['login']) works in principe, however, user can use browser button, replaying token login. i solved not using navigate di'ing 'location' service (from @angular/common). service has 'replacestate' method, removes token history wel url this.location.replacestate('login') hope helps someone.

ios - NSURLConnection willSendRequestForAuthenticationChallenge persistence -

the (soon deprecated) nsurlconnectiondelegate allows handle tls trust challenge so: -(void)connection:(nsurlconnection *)connection willsendrequestforauthenticationchallenge(nsurlauthenticationchallenge *)challenge { if ([challenge.protectionspace.authenticationmethod isequaltostring:nsurlauthenticationmethodservertrust]) [challenge.sender performdefaulthandlingforauthenticationchallenge:challenge]; } assuming same x509 certificate being presented same server, testing shows effect of method cached duration of application execution. method not hit again. is there way force application forget effect of method after handling has occurred, such subsequent hits same web service force method called? i think i'm using [challenge.sender cancelauthenticationchallenge:...].

python - GenericForeignKey data migtation error: 'content_object' is an invalid keyword argument -

i want create data migrations model( comment ) has genericforeignkey relation. model made according django documentation contenttypes . models: ... class nicememe(models.model): """ example model. """ name = models.charfield(max_length=140) image = models.imagefield(upload_to=get_path_to_store_nice_meme_images) class comment(models.model): """ model add comments other (non abstract) model. """ ... user = models.foreignkey(extendeduser) content = models.charfield(max_length=140) content_type = models.foreignkey(contenttype) object_pk = models.positiveintegerfield() content_object = genericforeignkey('content_type', 'object_pk') data migration : ... def create_comment(apps, schema_editor): ... nice_meme = nicememe.objects.create(name='nice nice meme') comment.objects.create( user=user, content='

java - JavaFX scrolling table update performance degrades over time -

Image
i have tableview shows last n items, new items @ top, remove items bottom etc... appears happening cpu load increases on time point other x applications on same machine become sluggish. platform details: redhat 6.7, 32 bit, java 1.8u40 things i've tried introduced runlater() - original code updated observable list non-fx thread - apparently wrong optimize - place new runnables on javafx application thread if there isn't update in progress optimize -bulk updates observable list rather individual adds used jvisual vm indentify memory leaks, couldn't find anything. i've tried recreate windows 7 (on metal) - jdk 8u40 64 bit => not occur ubuntu 16.04 jdk 8u40 64 bit (inside vm vmwgfx) => not occur ubuntu 16.04 openjdk + openjfx latest (8u91) (on metal) => does occur jvisual vm - redhat 6u7 (32bit) on newish hardware jvisual vm - ubuntu 16.04 (64bit) on old hardware (2008 imac) this issue part of larger app, i've isolated smaller

Local Variable Must be Final Java Error -

i want update variable every time click on jlabel. however, error because variable not declared locally. timer pictimer = new timer(1000, new actionlistener(){ int oldrr=0; int oldrc=0 ; @override public void actionperformed(actionevent e) { arraywm[oldrr][oldrc].seticon(null); random random = new random(); arraywm[oldrr][oldrc].seticon(null); int rr = random.nextint(3 - 0 + 1) + 0; int rc = random.nextint(3 - 0 + 1) + 0; oldrr = rr; oldrc = rc; arraywm[rr][rc].seticon(new imageicon("img/one.jpg")); int score=0; arraywm[rr][rc].addmouselistener(new mouseadapter(){ @override public void mouseclicked( mouseevent e){ score++; lbltimer.settext(string.valueof(score)); }

ruby on rails - How can I ensure that calling #changed? on an instance of an ActiveRecord model after a transaction rolls back returns true? -

i found issue in code transaction block rollback explicitly raising activerecord::rollback. in case if instance of model saves in transaction before rollback ends in weird state. here example of simple case causes issue: record = somemodel.last record.attributes = { name: "a new name"} somemodel.transaction record.save raise activerecord::rollback end if called record.changed? after transaction return false. however, if call record.name after transaction "a new name". reason in case record has changes not persisted in database, activerecord not identifying these changes anymore. in real-world application causing issue in 1 area use transactions. have code if transaction fails attempt retry transaction again changed parameters. if reuse instance went through first transaction without reloading results in changes not being saved since don't appear changes. does have suggestions how ensure instance has changes , activerecord still identifies the

ruby on rails - Mested attributes with cocoon gem are not saving in the form and showing in the view -

when enter data form association (lines) , save form. information not saving , gone when got edit form. information not showing in view. seems checkout on end feel i'm missing 1 simple thing. how can nested attributes save database? controller class lyricscontroller < applicationcontroller before_action :find_lyric, only: [:show, :edit, :update, :destroy] def index @lyric = lyric.published.order("created_at desc").take(1) end def show end def new @lyric = lyric.new end def create @lyric = lyric.new(lyric_params) if @lyric.save redirect_to @lyric, notice: "successfully created new lyric" else render 'new' end end def edit end def update if @lyric.update(lyric_params) redirect_to @lyric else render 'edit' end end def destroy @lyric.destroy

Why is the class passed to a function being called inside a class function when using self in Python? -

so, have code snippet. class logobserver(object): def write_log(...): self.logger.log(self, level, message, *args, **kwargs) ... looking debugger , error messages well, noticed variable level contains logobserver instead of integer. expecting integer. however, when remove self self.logger.log() like: self.logger.log(level, message, *args, **kwargs) level contains integer instead of logobserver object. error messages disappear well. what explanation behind behavior? if call instance method ( not staticmethod or classmethod), instance implicitly passed first parameter. why method definitions take self first parameter; name self convention, way. example, foo.bar() translated type(foo).bar(foo) . if explicitly pass on instance argument, passed along other argument - after instance passed in implicitly already. example, foo.bar(foo) translated type(foo).bar(foo, foo) . now, inside method, self first parameter. let's have defined c

Django group by foreign key id -

how can group query qualifications , group them quote__uuid ? looked aggregation doesn't seem fit need. my ideal output [{'quote_uuid_1':[qualification_1, qualification_2], 'quote_uuid_2':[qualification_3] }] class quote uuid = models.charfield() class qualification quote = models.foreignkey(quote) try: result = [{quote.id:quote.qualification_set.all()} quote in quote.objects.all()]

javascript - AngularJS | Passing directive's name as an attribute to another directive -

in markup have container, , 2 buttons inside of it. each button opens same popup window different content. container , buttons made directives , popup - service. html: <div my-container> <my-button ng-click="openpopup()" popupcontent="<popup-content1></popup-content1>"></my-button> <my-button ng-click="openpopup()" popupcontent="<popup-content2></popup-content1>"></my-button> <my-popup></my-popup> </div> as can see try add content popup window attribute , value of attribute name of directive has inserted in dom. first, attributes in my-button directive: //... link: function(scope, elm, attrs) { scope.openpopup()(true, attrs.popupcontent); } //... then pass value of attribute my-container directive's controller scope: //... $scope.openpopup = function(msg, content) { //... $scope.popupcontent = content; }; and after try attribute

java - How to use the Chinese calendar system in Joda Time? -

i'm developing calendar app needs convert dates other calendar systems gregorian dates. decided use jodatime. soon found different calendar systems represented chronology s. , looked through list of chronology s , see nothing chinese calendar system aka lunar calendar. searched "lunar calendar joda time" , see islamicchronology don't think right 1 says on page used in muslim countries. so i'm not sure how use chinese calendar system using joda time. looked @ stack overflow post suggests should use library. however, joda time not seem have interface support library means cannot consistent. of project use joda time , of don't. sounds weird me. the library has support icu4j far know. strength of library extended i18n-support. disadvantage api similar java.util.calendar . joda-time not support , has no plans, (since officially "largely finished" project, project owner recommends implement new calendars on base of threeten-extra , wel

Run Ansible playbook without inventory -

consider if want check quickly. doesn't need connecting host (to check how ansible works, like, including of handlers or something). or localhost do. i'd give on this, man page says: -i path, --inventory=path the path inventory, defaults /etc/ansible/hosts. alternatively , can use comma-separated list of hosts or single host trailing comma host,. and when run ansible-playbook without inventory, says: [warning]: provided hosts list empty, localhost available is there easy way run playbook against no host, or localhost? as @ydaetskcor suggested, it's follows: $ ansible-playbook playbook.yml -i localhost, -k and test playbook, matter - hosts: tasks: - debug: msg=test

resize - Android: resizing a surface from a surfaceview -

i using tutorial camera2 api android , 1 of steps resize textureview's surface acceptable format doing following: surfacetexture surfacetexture = mtextureview.getsurfacetexture(); surfacetecture.setdefaultbuffersize(mpreviewsize.getwidth(), mpreviewsize.getheight(); surface previewsurface = new surface(surfacetexture); previewbuilder = cd.createcapturerequest(cameradevice.template_preview); previewbuilder.addtarget(previewsurface); so mpreviewsize variable of type size , determined beforehand cycles through acceptable formats , selects optimal 1 according screen size. problem i'm using surfaceview , i'm trying resize surface object in surfaceview tried didn't work: surfaceholder sh= gamesurface.getholder(); sh.setfixedsize(mpreviewsize.getwidth(), mpreviewsize.getheight()); surface sur = sh.getsurface(); previewbuilder = cd.createcapturerequest(cameradevice.template_preview); previewbuilder.addta

python - Open a webpage and return a dictionary of links on that page -

i wanted write function opens webpage , returns dictionary of links , text on page. tried it's giving me error. can do? def process(url): myopener = myopener() #page = urllib.urlopen(url) page = myopener.open(url) text = page.read() page.close() example input <a href='http://my.computer .com/some/file.html'>link text</a> output {"http://my.computer.com/some/file.html":link text.."} welcome stack overflow, you haven't shown myopener does, have used own. code uses python 3 , beautiful soup 4 html parser (a personal favorite) on python wikipedia article. root_url = "https://en.wikipedia.org" html_string = retrieve_webage(root_url + "/wiki/python_%28programming_language%29") soup = beautifulsoup(html_string) output = {} # can redefine soup here parse part of page link in soup.find_all('a'): linkhref = link.get('href') if not linkhref: # ingnore bla

Kernel memory management: where do I begin? -

i'm bit of noob when comes kernel programming, , wondering if point me in right direction beginning implementation of memory management in kernel setting. working on toy kernel , doing lot of research on subject i'm bit confused on topic of memory management. there many different aspects paging , virtual memory mapping. there specific order should implement things or do's , dont's? i'm not looking code or anything, need pointed in right direction. appreciated. there multiple aspects should consider separately: managing available physical memory. managing memory required kernel , it's data structures. managing virtual memory (space) of every process. managing memory required process, i.e. malloc , free . to able manage of other memory demands need know how physical memory have available , parts of available use. assuming kernel loaded multiboot compatible boot loader you'll find information in multiboot header passed (in eax on x86 i

ios - Open ears Speech to text predefined text? -

i using open ears library in various code samples states there should predefined set of words. dont want this, should convert text speak. for example : nsarray *words = [nsarray arraywithobjects:@"word", @"statement", @"other word", @"a phrase", nil]; nsstring *name = @"nameiwantformylanguagemodelfiles"; nserror *err = [lmgenerator generatelanguagemodelfromarray:words withfilesnamed:name foracousticmodelatpath:[oeacousticmodel pathtomodel:@"acousticmodelenglish"]]; i dont want use words array, instaead want convert speech text any on ?

Building an empirical cumulative distribution function and data interpolation in R -

Image
here's example data frame i'm working with level income cumpop 1 17995.50 0.028405 2 20994.75 0.065550 3 29992.50 0.876185 4 41989.50 2.364170 5 53986.50 4.267305 6 65983.50 6.323390 7 77980.51 8.357625 8 89977.50 10.238910 9 101974.50 11.923545 10 113971.51 13.389680 11 125968.49 14.659165 12 137965.50 15.753850 13 149962.52 16.673735 14 161959.50 17.438485 15 173956.50 18.093985 16 185953.52 18.640235 17 197950.52 19.099085 18 209947.52 19.514235 19 221944.50 19.863835 20 233941.50 20.169735 21 251936.98 20.628585 22 275931.00 20.936670 23 383904.00 21.850000 the entire population of particular country has been sorted income , grouped 23 corresponding 'levels'. income variable average income of members of level (this importantly different saying, example, 10th percentile income 17995.50). but population size of each level inconsistent (

c# - How to mock OwinContext.Request.Query -

i trying unit test method checks query in owincontext.request.query , alters it public static async task setupquery(iowincontext context, iclientstore clientconfig) { // clientid querystring var clientidqs = context.request.query.where(x => x.key == constants.authorizerequest.clientid).select(x => x.value).firstordefault(); // more code here } i using moq mock context. how mock query object of type ireadablestringcollection if take closer @ ireadablestringcollection , see inherits ienumerable<keyvaluepair<string,string[]> . other class/interface know inherits similar. idictionary<tkey,tvalue> . so set out find way mock ienumerable<keyvaluepair<string,string[]> . take @ following extension method public static class mockqueryableextensions { /// <summary> /// converts generic <seealso cref="system.collections.generic.ienumerable&lt;t&gt;"/> <see cref="moq.mock"/> imple

javascript - Bootstrap Validator & Image Picker - How to validate form if any one of two available select inputs are chosen? -

i using bootstrap-validator form validation, , imagepicker display selects. works great, have come across instance can't solve on own. have form 2 inputs , need form validate if of 2 inputs selected. couldn't find example on bootstrap-validator or imagepicker options ideally i'd accomplish bootstrap-validator or imagepicker plugin. if not i'll if statement toggle required property. here form, appreciated. thanks html <form role="form"> <h4>select list #1</h4> <div class="form-group"> <label class="hide" for="select-list-1">select list #1</label> <select id="select-list-1" multiple="multiple" class="image-picker form-control" required> <option>option 1</option> <option>option 2</option> <option>option 3</option> </select> </div>

Extracting .rar Files in C# -

this question has answer here: ionic.zip library unable extract .rar file c# 1 answer i'm trying make auto update function little tool i'm making. got point when downloads .rar file, have extract .rar file. i'm using ionic.zip(a refference), this: zipfile zipfile = new zipfile(path.getdirectoryname(application.executablepath) + @"\tool[" + program.newversion + "].rar"); zipfile.extractall(application.startuppath); but when running gives me "system.reflection.targetinvocation" exception... knows i'm doing wrong or has solution extracting.rar files!? dotnetzip / ionic not support .rar files: can dotnetzip read or write rar files? no. dotnetzip zip files. - http://dotnetzip.codeplex.com/ you can use sharpcompress though, support .rar files among other extensions.

ElasticSearch - Average aggregation/sort over multivalued non-unique numeric fields -

i trying handle sorting on average of multivalued field called 'rating_average'. in example i'm giving you, values field [1, 2, 2]. i'm expecting average (1+2+2)/3 = 1.66666667. reality i'm getting 1.5 average. after few tests , analyzing extended stats, i've discovered happens because average calculated on non-unique items. statistical operators applied on set [1, 2] instead of [1, 2, 2]. i've proved end adding aggregations section query double check average calculated sort block identical 1 in stats aggregation. an example document following: { "_source": { "content_uri": "http://data.semint.co.uk/resource/testcontent1", "rating_average": [ "1", "2", "2" ], "fordesk": "http://data.semint.co.uk/resource/kmfmjd1rtkd" } the query i'm performing following: { "from": 0, "size": 20, "aggs": { &quo