Posts

Showing posts from May, 2010

Sails.js query for waterline association -

Image
in sails.js i've post model many-to-many association model called "tag" posts model module.exports = { attributes: { title: 'string', content: 'string', coverimage: 'string', owner: { model: 'user' }, tags: { collection: 'contenttag', via: 'posts', dominant: true // --- } } }; tags model module.exports = { attributes: { name: 'string', posts: { collection: 'post', via: 'tags' } } }; now want related posts same tags. i've try play around .populate('tags') , and .populate('tags',{name: ['tag1','tag2']) can't figure out how solve. sails.js waterline share | improve question asked may 15 '15 @ 14:36 ...

set a key without value for a dictionary in python -

this question has answer here: python function global variables? 6 answers i trying set dictionary staff's salary in python. want create 2 functions, getname() , getsalary() tried: empdic={} def setname(n): empdic={'n':''} and in python interactive 2.7 typed: >>>setname('marson') >>>print empdic {} the result still empty dictionary, how can deal that? you need modify original dict: empdic={} def setname(d, n): d[n] = "" setname(empdic,"marson") print(empdic) {'marson': ''} you creating new local variable empdic in function, using string "n" not name n passed in function.

recursion - Recursive Combination on Fortran -

i wrote recursive program on fortran calculate combinations of npoints of ndim dimensions follows. first wrote program on matlab , running. in fortran, problem after first iteration assigning absurd values list of points, no explanation. give me hand? program main implicit none integer :: ndim, k, npontos, contador,i,iterate, test integer, dimension(:), allocatable :: pontos print*, ' ' print*, 'npoints?' read *, npontos print*, 'ndim?' read *, ndim k=1 contador = 1 open(450,file= 'combination.out',form='formatted',status='unknown') write(450,100) 'comb ','stat ',(' pt ',i,' ',i=1,ndim) write(450,120) ('xxxxxxxxxx ',i=1,ndim+1) allocate(pontos(ndim)) i=1,4 pontos(i)=i end test = iterate(pontos, ndim, npontos,k,contador) end program main recursive integer function iterate(pontos, ndim, npontos, k,contador) ...

php - Page loading progressively -

i'm building basic scraping tool, i'm running locally on laptop, backup data cms. the basic procedural script wrote loads urls database , each url, scraps page, saves content database , echoes page saved. the problem when manages go through urls @ once (a few hundreds of @ times), output of script loads progressively in browser. in firefox can see part of echo statements few pages (indicating pages saved), rest comes in batches , @ bottom firefox indicates me "transferring data localhost..." i'm confused because thought when php script runs, outputs , sends response single block, when it's done, , not this, progressively. maybe i'm forgetting in code? think it? here basic structure of script: <?php try { // login cms // connect db urls ($i = 0; $i < count($urls); $i++) { // data page $data = $scraper->getdata($urls[$i]); // store data page if ( $db->save($data) ) { echo 'data saved "...

javascript - PureRenderMixin breaking with bound event handlers -

i'm trying optimize as can react components using purerendermixin , making sure props being passed immutable , don't change render render. one issue i'm running case of mutating bound event handlers passed props. more specifically, have renders , array of children: in parent: onchange: function(key, data) { ... }, render: function() { return this.state.array.map(function(object, index) { return <child key={object.key} onchange={this.onchange.bind(key)} stuff={object.stuff}/> } }) } in child: ... mixins: [purerendermixin] ... it turns out purerendermixin triggers update inside child because onchange prop new instance (even though it's bound same key). is, each call anyfunction.bind(123) generates new value (ie. not ===). how people deal this? here's 2 ways can think of: pass unbound onchange handler, pass key separately, , have child call onchange key -- bit messy adds unecessary complexity child. c...

java - Script goes to bash then back to script a few times before running -

i have binary file (saved dpl ) made shc . here simple source file: #!/bin/bash java -jar /users/eli/documents/dpl.jar $@ it should run jar program arguments. works fine, except there few seconds of delay on startup. noticed in title bar of terminal (os x) switches dpl bash dpl bash few times, until switching java , running jar. don't understand going on here. edit: additionally, actual java program seems slowed down effect. edit2: need binary file can use shell interpreter ( #!/usr/bin/dpl ) try saving .sh file , giving executable permission. chmod +x <your file>.sh

http status code 404 - Ektron and Elmah - 404 Errors not being logged -

i configuring elmah 1.2 log errors within our ektron 9.1 application, not log 404 errors. elmah functional logging other errors (including unhandled exceptions), not 404 errors. not running mvc environment / 3-tier ektron architecture, still using traditional asp.net / ektron web forms solution. i know elmah logs these errors default, i'm wondering if i'm missing regards how elmah interacting ektron. there's not information out there on topic, , 1 article found dated 2010, information severely outdated. it's different urls end in .aspx , other ones. if user goes site , accesses /thisfileisnothere.html static file handler handle that. ektron replaces static file handler ekdavhttphandlerfactory. ektron's handler doesn't throw exception. doesn't trigger application.error event. sets statuscode 404. if wanted custom log error elmah, hook application.postrequesthandlerexecute , check response.statuscode if user tries go /thispageisnthere.aspx ...

How can my app tell if it's running in Chrome vs on an Android device? -

if use arcwelder port app chrome, there way know it's running on chrome? maybe through build.version? quoting the documentation : if need check if app running on chrome os, chromium android.os.build.brand , android.os.build.manufacturer.

arrays - What is causing my custom zsh script terminal command to hang? -

i've created custom zsh script taking notes day , keeping track of time can fill out time sheets easier. works fine of time every , again hangs. logs txt file when hangs doesn't execute "say" command. i think it's problem how i'm selecting random string don't know enough zsh fix it. i'm using zsh , in .zshrc file. createlog() { logfile=$home/google\ drive/autosdls.txt # chmod 755 $logfile lastline="$(tail -1 $logfile)" lasttime="$(grep -oe "[[:digit:]]{10}" <<<"$lastline")" time="$(date +%s)" timespent=$((($time-$lasttime)/60)) echo "$timespent" echo "[ ] $timespent minutes : $1 |$(date +%s)|" >> $logfile 2>&1 # seed random generator random=$$$(date +%s) encouragements=("greatjob!" "thank you." "productivity node assimilated" "well done. ambition matched zeal" "engage" "yo...

c# - Is STAThread attribute a requirement or recommendation? -

i wrote managed extension autocad. when autocad loads extension launch iextensionapplication.initialize() method. need method launched in main thread of application. enough set stathread attribute method purpose? attribute requirement or recommendation ? the [stathread] attribute works on main() entrypoint of standalone executable program. promise make operating system, telling main thread of program "well-behaved". must pump message loop , never block. breaking promise causes hard diagnose misbehavior, deadlock common. none of applies when write autocad extension. did not create thread, autocad did. can't make promises, autocad has implement them. nor "main thread", that's term can apply standalone program. the thread calls extension single-threaded apartment, can use thread.getapartmentstate() in code double-check. sta requirement thread displays ui, commonly in extension.

list - Define predicate in prolog -

i'm struggling one: define predicate len_nm(l,n,m) checks if list of lists l contains @ least n elements length no less m . the op stated: define predicate len_nm(l,n,m) checks if list of lists l contains at least n elements length no less m . in answer not solve original problem, following variation: define predicate len_nm(l,n,m) checks if list of lists l contains exactly n elements length no less m . similarly this answer , define dcg seqq1//1 establish relationship between list of non-empty lists , flattened opposite: seq([]) --> []. seq([e|es]) --> [e], seq(es). seqq1([]) --> []. seqq1([es|ess]) --> { es=[_|_] }, seq(es), seqq1(ess). sample use: ?- phrase(seqq1([[1,2],[3],[4]]),xs). xs = [1,2,3,4]. note seqq1//1 works in "both directions": ?- phrase(seqq1(xss),[1,2,3,4]). xss = [[1],[2],[3],[4]] ; xss = [[1],[2],[3,4]] ; xss = [[1],[2,3],[4]] ; xss = [[1],[2,3,4]] ; xss = [[1,2],[3]...

vb.net - Killing a thread completely in Multithreaded application -

i new vb bare me please.... can show/tell me i'm steering wrong this? running second thread in application read values registers in motion controller , updates values appropriate fields on ui every 100ms. when disconnect controller (ie...ethernet cable disconnected, lost comms), want destroy/terminate thread (thread1) completely. when reconnect ethernet cable, click button on ui reestablish comms controller, , execute runthread() sub. when want recreate thread , start it. however, when debugging part of code, appears thread (thread1) never destroyed though have verified code line (case 1) , execute it. after comms re-established, code goes right case 3 , starts thread1, expect jump case 2 , recreate thread. public class frmmain private rmc rmclink public thread1 system.threading.thread = new system.threading.thread(addressof readregisters) private sub runthread() dim conditions integer if rmc.isconnected(pingtype.ping) = false , thread1 isn...

Python XML parse this doc -

i couldn't find this, , can't use beautifulsoap. i've xml url doc. wanna parse items called contenido, has atribs , don't know how them. i've tried xml.sax don't know how use attrib <contenido> <tipo>evento</tipo> <atributos idioma="es"> <atributo nombre="id-evento">8006941</atributo> <atributo nombre="titulo">582 mapas, compañía teatral “la cola del pavo”</atributo> <atributo nombre="tipo"> /contenido/actividades/recitalespresentacionesactosliterarios </atributo> </atributos> </contenido> this example using xml.sax import xml.sax class myhandler( xml.sax.contenthandler ): def __init__(self): self.is_atributo = false def startelement(self, tag, attributes): if tag == 'atributo': self.is_atributo = true def characters(self, content): if self.is_atributo: print(content...

Consuming Rabbit MQ messages using Eclipse on Tomcat -

i using eclipse, tomcat , rabbit mq. i want able consume messages of queue hit queue. have managed using java class in eclipse (see below), have not been able working when deploying war file on tomcat server. package org.com.hello; import com.rabbitmq.client.connectionfactory; import com.rabbitmq.client.connection; import com.rabbitmq.client.channel; import com.rabbitmq.client.queueingconsumer; public class hellorecv { public static void main(string[] argv) throws java.io.ioexception, java.lang.interruptedexception { connectionfactory factory = new connectionfactory(); factory.sethost("172.24.3.53"); factory.setport(6672); factory.setusername("user"); factory.setpassword("password"); connection connection = factory.newconnection(); channel channel = connection.createchannel(); channel.queuedeclare("q1", true, false, false, null); system.out.println(" [*] waiting messages. exi...

javascript - How to go about to create general messages -

i new meteor , coming laravel enviroment got stuck on creating template general messages (error, success, info, warning etc). this layout. can see, when event occurs , goes wrong (or succeed) want show message. <template name="layout"> <div class="ui grid"> {{>header}} </div> <div class="ui stackable page grid"> {{#if somestatement}} {{>messages}} {{/if}} {{>yield}} </div> </template> for example login event: template.login.events({ 'submit #login-form' : function(e, template) { e.preventdefault(); var email = template.find('#login-email').value, password = template.find('#password').value; meteor.loginwithpassword(email, password, function(err){ if(err) { /*here want return error , type template */ } else { route.go('da...

Accessing Environment Variables in a linked Docker -

how access environment variables of source container container linking --link argument? docker manual states: environment variables docker creates several environment variables when link containers. docker automatically creates environment variables in target container based on --link parameters. expose environment variables originating docker source container. these include variables from: the env commands in source container's dockerfile the -e , --env , --env-file options on docker run command when source container started http://docs.docker.com/userguide/dockerlinks/ but can't access environment variable set with env my_variable = "example" in linking container with #!/bin/sh echo $my_variable it contain no value. environment variables source container prefixed alias set --link <source container>:<alias> in target container: $<alias>_env_<env variable> the environmen...

android - Dagger 2 error: dependency "cannot be provided without an @Inject constructor" while it actually annotated with @Inject -

i've started using dagger 2 , faced strange issue looks bug me. i have 3 modules, composed 1 subcomponent, in turn extends/pluses higher level component. subcomponent pretty simple: combination of modules , single injection point: @singleton @subcomponent( modules = { navigationdrawermodule.class, navigationlistmodule.class, switchermodule.class } ) public interface navigationdrawercomponent { navigationdrawerfragment inject(navigationdrawerfragment object); } first modules looks - provides general fragment-level dependencies: @module public class navigationdrawermodule { private final activity activity; private final view rootview; private final loadermanager loadermanager; public navigationdrawermodule(activity activity, view rootview, loadermanager loadermanager) { this.activity = activity; this.rootview = rootview; this.loadermanager = loadermanager; ...

validation - Tel Number visualization pattern - space after every second number -

i have editabe datatable. after user inserts tel number tel column input text box, , ok button clicked, need visualize following: input 390239266655 output +39 02 39 26 66 55 so need put space after every second number, , putting + @ begining. how can ? the following validation have: <ui:define name="validation-tag"> <f:validateregex pattern="[0-9+]*" for="contactphonenumber" /> </ui:define> we had write converter, here solution : @facesconverter(value = "phoneconverter") public class phoneconverter implements converter { @override public object getasobject( facescontext context, uicomponent component, string value) { string stringtodisplay = null; // // if (value != null && !value.equals("") && value.startswith("+")) { // stringtodisplay = value.substring(1).trim(); // ...

Best way to interpret JavaScript in an Android Java Application -

i need way java app regex-based string analysis , replacement. each replacement rule, , app should capable of reading file containing these rules. allow users download sets of rules, , development of them sped considerably way, since app not need recompiled each new or changed rule. here example rules executed server-side in python # ---------- copy ---------- title = item['title'] uri = item['action']['uri'] # ---------- spiegel online ---------- title = title.replace(" - spiegel online - nachrichten", "").replace(" - spiegel online", "") if domain == "m.spiegel.de": uri = "http://www.spiegel.de" + uri[19:] if domain == "spon.de": r = requests.head(uri) # <----- resolve url try: uri = r.headers['location'] except: traceback.print_exc() # ---------- stack overflow ---------- if title.endswith(" - stack o...

flask - jinja2 template takes over 10 secs to render, how to optimize? -

in flask web app, there route display either member first name starting 'a, b, c, etc..' or show button shows members registered . right sum 750 users. problem displaying 'show all' list takes on 10 seconds. request db fast, it's rendering takes seconds. wondering if there way speed up? i'm pretty new python, flask , jinja2 don't know optimiztion paths yet. here views.py, when click 'show all" button on webpage, calls url letter argument set '0': @main.route('/all-members') @login_required @admin_required def all_members(): alphabet = list(string.ascii_lowercase) first_letter = request.args.get('letter') if first_letter == '0': user_ = user.query.order_by(user.fullname.asc()).all() else: user_ = user.query.filter(user.username.startswith(first_letter)).order_by(user.fullname.asc()).all() return render_template('all_members.html', all_members = user_, alphabet = ...

pattern matching - Clustering Using MapReduce -

i have unstructured twitter data retrieved apache flume , stored hdfs. want convert unstructured data structured 1 using mapreduce. task wanted using mapreduce: 1. conversion unstructured structure one. 2. want text part contain tweet part. 3. want identify tweets particular topic , grouped according sub part. e.g. have tweets of samsung handset want make group according handsets groups of samsung note 4, samsung galaxy etc. it college project guide suggested me use k means algorithm, search lot on k means failed understand how identifies centroid failed understand how apply k means situation in mapreduce. please gude me if doing wrong new concept k-means clustering algorithm. cluster or group similar data , calculate common centroid. can create time-series above questions have mention. group tweets according topic. k-mean implementation in mapreduce. https://github.com/himank/k-means using k-means in twitter datasets. you can check following links https://g...

android - Using <include> tag with ?attr/myAttr -

Image
i'm trying include different layouts in view depending on parent theme . following idea: attrs.xml <attr name="themelayout" format="reference" /> styles.xml <style name="apptheme" parent="theme.appcompat.light.darkactionbar"> <item name="themelayout">@layout/layout_a</item> </style> <style name="appthemesecond" parent="theme.appcompat.light.darkactionbar"> <item name="themelayout">@layout/layout_b</item> </style> activity.xml <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <include layout="?attr/themelayout" /> </relativelayout> when run code abo...

vb.net - How to limit the scope of a variable to the function when declared in an If statement -

i need limit scope of variable function resides need declare within if statement it's type change depending. i'm working within vb.net public function coursedatatable() if radiocourses.checked dim searchby new classsearchcourses elseif radioattendees.checked dim searchby new classsearchattendees end if the obvious problem variable doesn't persist outside of if statement. want limit scope of variable because a, it's used else , b, memory leakage, class end holding whole sql tables , don't want persisting when it's not needed. can't use inheritance or polymorph here because i'm working legacy system. this rework (i'm struggling think of different way of approaching evidently) can't find in msdn allows procedure scope ignores other blocks @ declaration. it still possible use polymorphism in legacy system. can find common functionality must exist between 2 in order want reuse same variable. can create ...

jQuery running C# code after other codes -

i have click event on button runs code in c# put c# code in jquery using @{...} however, codes in @{...} runs after other codes. html code: <button type="submit" id="testregex" class="btn btn-default">test regex</button> jquery: $("#testregex").click(function () { @{ var testdata = request["testdata"]; var expression = request["regexpattern"]; string regexmatchresult = "no match"; string datematchresult = "no match"; if (!string.isnullorempty(testdata) || !string.isnullorempty(expression)) { bool regexmatch = system.text.regularexpressions.regex.ismatch(testdata, expression, system.text.regularexpressions.regexoptions.ignorecase); bool datematch = false; foreach (var item in system.text....

Elasticsearch and MongoDB: no river _meta document found after 5 attempts -

i have mongodb database named news tried index es. using these plugins: richardwilly98.elasticsearch/elasticsearch-river-mongodb/2.0.9 , elasticsearch/elasticsearch-mapper-attachments/2.5.0 this happening when tried create index. have tried delete index , recreating it, without helping. $ curl -xput 'http://localhost:9200/_river/news/_meta' -d @init.json init.json { "type": "mongodb", "mongodb": { "db": "news", "collection": "entries" }, "index": { "name": "news", "type": "entries" } } here log update_mapping [mongodb] (dynamic) mongodb river plugin - version[2.0.9] - hash[73ddea5] - time[2015-04-06t21:16:46z] setriverstatus called mongodb - running river mongodb startup pending starting river mongodb mongodb options: secondaryreadpreference [false], drop_collection [false], include_collection [], throttlesize [5000], gridf...