Posts

Showing posts from July, 2010

javascript - AngularJS Custom Filter orderBy sortPredicate not working -

the problem have array of recipe objects. each recipe object has comments on it. want sort array in angularjs controller using $filter service provided angular. $scope.recipes = $filter('orderby')($scope.data, function(recipe) { return recipe.comments.length; }); but not giving required results. however, i'm able achieve desired results using js array sort functionality this $scope.data.sort(function(a, b) { if (a.comments.length < b.comments.length) return 1; if (b.comments.length < a.comments.length) return -1; return 0; }); the plunkr same scenario : http://plnkr.co/edit/l9bt67xhrcjlbowg8ezp?p=preview thanks in advance. please help! it can done lot simpler using orderby http://plnkr.co/edit/b0fmi7fotgmg2tkcjyst?p=preview <ul> <li ng-repeat="r in recipes | orderby:'-comments.length'"> {{r.title}} - {{r.comments.length}} </li> </ul>

angularjs - Angular-material md-select with images or svg -

Image
i using angular material, want use md-select images/svg; using md-option ng-repeat , list of options works, when select see text. is feasible? thanks <md-select ng-model="mkt.bookmaker" placeholder="select bookmaker"> <md-option ng-value="opt" ng-repeat="opt in mkt.selected.matchinfo.bookmakers"> <md-icon md-svg-src="{{ opt.logo }}"></md-icon>{{ opt.name }} </md-option> </md-select> here screenshots: i found nice way use md-select in angular material github here plunker solution, , below preview. controller: var app = angular.module('demoapp', ['ngmaterial']); app.controller('mainctrl', function($scope) { $scope.options = [ { name: 'rome', size: '200€', image: 'http://lorempixel.com/120/60/cats/' }, { name: 'naples', size: '230€&

javascript - Animating a circle border to fill up -

Image
how go animating (and creating) circles shown in image javascript? i'm not sure call this, said "border". there lot ways it, here some js/canvas: http://p.ar2oor.pl/cprogress/ http://anthonyterrien.com/knob/ css3: http://fromanegg.com/post/41302147556/100-pure-css-radial-progress-bar http://www.alessioatzeni.com/blog/css3-loading-animation-loop/ svg: http://raphaeljs.com/

java - Setting width of SeekBar to make "swipe to unlock" effect -

Image
i attempting make swipe unlock feature using seekbar. aiming shown here: this composed of 2 images, background, , button. put both background , seekbar in framelayout seekbar should sit on top of background. like so: <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" > <textview android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="testing 123..." /> <framelayout android:layout_height="wrap_content" android:layout_width="wrap_content" > <imageview android:id="@+id/imageview01" android:layout_width="wrap_content" android:layout_height="

mysql preserve backslashes on select query -

i have mysql database , value in column of table string "{1,1,{1\,1\,1\,}}". when use select query returns "{1,1,{1,1,1,}}", there anyway preserve slashes so, if echo result, "{1,1,{1\,1\,1\,}}" thanks add statement in session : set session sql_mode='no_backslash_escapes';

swift - Why is the message not showing up? -

i created pop up, nothing showing up, added uiviewcontrollers pop ups. why not working? http://puu.sh/hrel9/75081b2a90.png class interestviewcontroller: uiviewcontroller, uipopoverpresentationcontrollerdelegate { override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) { if segue.identifier == "popoversegue" { let interestviewcontroller = segue.destinationviewcontroller as! uiviewcontroller interestviewcontroller.modalpresentationstyle = uimodalpresentationstyle.popover interestviewcontroller.popoverpresentationcontroller!.delegate = self } } func adaptivepresentationstyleforpresentationcontroller(controller: uipresentationcontroller) -> uimodalpresentationstyle { return uimodalpresentationstyle.none } i believe don't need segue in case. can use example listed below. shows popover button when press it. import uikit class viewcontroller: uiviewcontroller, uipopoverpresentationcontrollerdelegate {

maven - Android Studio - Cannot resolve symbol FacebookContentProvider -

i'm using facebook sdk 3.22.0 maven. building android sdk version 15. i'm using android studio 1.1.0 gradle. in androidmanifest.xml i'm trying use facebookcontentprovider, every time try, issue cannot resolve symbol facebookcontentprovider. ideas on how solve this? the specific line i'm having issue is: <provider android:authorities="com.facebook.app.facebookcontentprovider1234" android:name="com.facebook.facebookcontentprovider" android:exported="true"/> here's androidmanifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.whatever" android:versioncode="100" android:versionname="1.0" > <uses-sdk android:minsdkversion="11" android:targetsdkversion="11" /> <uses-permission android:name="android.perm

ruby on rails - Adding an object to one to many relationship ROR -

Image
i having trouble adding object associate class. parent class, user, has has_many relation ad class. when try access user's has_many object ":ads" ad controller, returns me "undefined method ads" exception. posting model , controller code below. please me on issue. user model class user < activerecord::base has_many :ads has_secure_password has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "50x50#" }, :default_url => "/images/:style/missing.png" validates_attachment_content_type :avatar, :content_type => /\aimage\/.*\z/ def self.searchid(query) where("id ?", "#{query}") end end ad model class ad < activerecord::base belongs_to :user scope :ordernewestfirst , lambda { order("id desc") } has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#&q

html - Understanding Pull Classes - Centering Items -

so following code included in on line shop. i think designed pull items left says below , change depending on amount of items. i have 1 item , center. what best way without ruining responsive code , understand method? /*============================================================================ pull - pull classes, move grid items left amounts ==============================================================================*/ @mixin pull-setup($namespace: "") { /* whole */ #{$class-type}pull--#{$namespace}one-whole { right:100%; @include silent-relative(); } /* halves */ #{$class-type}pull--#{$namespace}one-half { right:50%; @include silent-relative(); } /* thirds */ #{$class-type}pull--#{$namespace}one-third { right:33.333%; @include silent-relative(); } #{$class-type}pull--#{$namespace}two-thirds { right:66.666%; @include silent-relative(); } /* quarters */ #{$class-type}pull--#{$namespace}one-quarter { right:

java - jsoup crawling image width and height from amazon.com link -

following example amazon link trying crawl image's width , height: http://images.amazon.com/images/p/0099441365.01. sclzzzzzzz .jpg i using jsoup , following code: import java.io.*; import org.jsoup.*; import org.jsoup.nodes.document; import org.jsoup.select.elements; public class crawler_main { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub string filepath = "c:/imagelinks.txt"; try (bufferedreader br = new bufferedreader(new filereader(filepath))) { string line; string width; //string height; while ((line = br.readline()) != null) { // process line. system.out.println(line); document doc = jsoup.connect(line).ignorecontenttype(true).get(); //system.out.println(doc.tostring()); elements jpg = doc.getelementsbytag("img"); width = jpg.attr("width"); system.out.printl

c - Why is there a long delay between pcap_loop() and getting a packet? -

i'm writing sniffer using libpcap. problem there's 7-10 second delay between calling pcap_loop() or pcap_next() , getting packet(the callback function being called). however, if use wireshark same filter on same device, there no such delay after hit "start" button. why there delay in program , there way fix that? i'm working on atheros wifi chips. device set monitor mode using airmon-ng start wlan0 i'm sure there're plenty of traffic listen to, can see packages in wireshark. thank you. i'm using 10000 the to_ms argument pcap_open_live() , pcap_set_timeout() in milliseconds. 10000 milliseconds 10 seconds. try using 1000, value tcpdump uses - that'll reduce delay 1 second - or using 100, value wireshark uses - that'll reduce delay 1/10 second. i read on tutorial field: " on @ least platforms, means may wait until sufficient number of packets arrive before seeing packets, should use non-zero timeout"

php - In python requests library, cannot do authorization? -

i try wrote code on python: http://vestacp.com/docs/api/#add_user like this: http://pastebin.com/xdzkkzpg but cant authorize in last line, auth missing ' = ' sign: req = r.post(vst_hostname, auth(vst_username, vst_hostname), \ params=postvars, verify=false) see authentication section in requests documentation more information.

c# - Caliburn Micro WPF: Message.Attach with guard property disables whole host control -

i'm using caliburn.micro (2.0.2, latest version) wpf application. have simple list of items, , want enable action on selected item. action bound button. so, vm exposes bindable collection of items (e.g. persons ), , object of same type bound selected item (e.g. selectedperson ). action corresponds method named test , , have guard property cantest , returns true when selected item not null. when selectedperson changes, call notifyofpropertychanged cantest . this trivial scenario works fine: when nothing selected button corresponding action disabled; when select item, gets enabled. the issue arises when bind method control event, using message.attach : want attach mouse double click. xaml this: <listbox itemssource="{binding path=persons,mode=oneway}" selecteditem="{binding path=selectedperson,mode=twoway}" cal:message.attach="[event mousedoubleclick] = [action test]"/> this totally disables control (the whole cont

excel vba - Want to rename mp3 files from 1 to words mentioned in column1 in that order -

rename mp3 file, using words in column in worksheet: sub rename dim integer dim new_name string i=1 while range("a1").offset(i,0)<>"" range("a1").offset(i-1,0).select new_name=worksheets("sheet1").range("a1").offset(i-1, 0) name "g:\" &i& ".mp3" as"g:\" & new_name & ".mp3" = i+1 loop end sub at line name "g:\" ... line highlighted in yellow.. , says error 53! you can't declare old name new name. need file system object rename files. used movefile method rename file. the as keyword used when declaring variable. dim variable_name as specific data_type instance dim idx integer first add these things declarations dim fso dim srcfile string dim destfile string then replace line 'name "g:\" &i& ".mp3" as"g:\" & new_name & ".mp3" with of thi

jsp - Print an array in a table using JSTL -

this example of array have : string[] dataname = {"gene name","promoter name","source","year","author"}; string[] proteinlist = {"protein01","aox","yarrowia","2006","john doe","protein02","pgap","homo sapiens","1997","john smith"}; the actual array can contain 30 values. the display of data should in table : | gene name | promoter name | source | year | author | | protein01 | aox | yarrowia | 2006 | john doe | | protein02 | pgap | homo sapiens | 1997 | john smith| but result : | gene name | promoter name | source | year | author | | protein01 | aox | yarrowia | 2006 | john doe | protein02 | pgap | homo sapiens | 1997 | john smith| in jstl, how have written : <tr> <c:foreach items="${dataname}" var="name

c# - How to create a separate DbCompiledModel for each type of server being used -

i know question has been asked before , have read of them did not me :( i trying create controller views. i using ef 6 , had configuration in web.config: <entityframework> <defaultconnectionfactory type="npgsql.npgsqlfactory, npgsql" /> <providers> <provider invariantname="system.data.sqlclient" type="system.data.entity.sqlserver.sqlproviderservices, entityframework.sqlserver" /> <provider invariantname="npgsql" type="npgsql.npgsqlservices, npgsql.entityframework" /> </providers> then found out ef6 not support scaffolding downgraded ef version 5. turned out ef 5 not recognize tag removed it: <entityframework> <defaultconnectionfactory type="npgsql.npgsqlfactory, npgsql" /> </entityframework> now when try create controllers error: using same dbcompiledmodel create contexts against different types of database servers not supported. instead, crea

c# - MahApp Flyout CloseCommand and IsOpen are Not Binding Properly -

i'm following strict mvvm pattern. in flyoutcontrol , i've bound following: <controls:flyoutscontrol> <controls:flyout isopen="{binding flyoutisopen, updatesourcetrigger=propertychanged, mode=twoway}" closecommand="{binding closeflyoutcommand}"> ... </controls:flyout> </controls:flyoutscontrol> i have 2 scenarios, both not work: scenario 1: i set flyoutisopen true in viewmodel constructor, , bind closeflyoutcommand delegatecommand accepts method sets flyoutisopen false . in scenario, view loads flyout open (as expected). however, when click flyout close button, nothing happens unless click again. if print output of method, can confirm command sets flyoutisopen false , reason, require second click (after flyoutisopen set false ) close flyout . scenario 2: i set flyoutisopen false (or uninitialized) in constructor. bind button delegat

android - MPAndroidChart - How to set range values from BarChart at 2.0.9v? -

i´m using mpandroidchart 2.0.9 version. set labels on y-axis 0 100 , display range, can´t find chart.setyrange() method. the range can customized via yaxis class. here documentation: https://github.com/philjay/mpandroidchart/wiki/yaxis-%28ylabels%29 yaxis y = chart.getaxisleft(); y.setaxismaxvalue(100); y.setaxisminvalue(0);

How to buid ffmpeg with android-ndk-r10d in windows -

Image
in application user can selects several images , create movie(mp4) images, reason want use ffmpeg library. have searched more 2 days did not find tutorial build ffmpeg ndk in windows. can body describe me, how that?(if have link, please share me) i used roman10 tutorial , do: 1-i have decompressed "ffmpeg-2.6.2" folder "android-ndk-r10d/sources". 2-i have created "build_android.sh" file "ffmpeg-2.6.2" folder , these build_android.sh codes: #!/bin/bash ndk=c:/users/hakhasin/desktop/android-ndk-r10d sysroot=$ndk/platforms/android-9/arch-arm/ toolchain=$ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64 function build_one { ./configure \ --prefix=$prefix \ --enable-shared \ --disable-static \ --disable-doc \ --disable-ffmpeg \ --disable-ffplay \ --disable-ffprobe \ --disable-ffserver \ --disable-avdevice \ --disable-doc \ --disable-symver \ --cross-prefix=$toolchain/bin/arm-linux-androideabi- \ --target-o

java - What is the need for having Abstract classes and interfaces separately? -

this question has answer here: interface vs abstract class (general oo) 32 answers i having doubt java 8's default method feature interfaces. means java 8 can provide default implementation method in interface, no longer necessary implementing classes override method. now interface able contain abstract method concrete method same abstract class. both behaving in same manner. talking differences between interface , abstract methods can identified - 1. multiple interfaces can implemented class, 1 class can extended. 2. interface fields public static final, while in case of abstract class have control on access modifiers of fields , methods. my doubt difference comes picture, whether should go abstract class or interface? actual purpose having both abstract class , interface separately? in java 8 differences between abstract class , interface have be

regex - Matching Barcodes to sequences python? -

i have sequence files , barcode files. barcode files may have barcodes of length "attg, agct, acgt" example. sequence files "attgcccccccggggg, attgtttttttt, agctaaaaa" example. need match barcodes sequences contain them @ beginning. each set of sequences same barcode have calculations on them rest of program (which written already). dont know how them match. ive went through using print statements , part messed "potential_barcode = line(:len(barcode)" line. also, says #simple fasta should reading in matched sequences. i'm pretty new @ made lot of mistakes. help! bcodefname = sys.argv[1] infname = sys.argv[2] barcodefile = open(bcodefname, "r") barcode in barcodefile: barcode = barcode.strip() print "barcode: %s" % barcode outfname = "%s.%s" % (bcodefname,barcode) # print outfname outf = open("outfname", "w") handle = open(infname, "r")

sql update - How to add additional Value in MySQL DB -

how can add 1 value field in table? i update field below mysql, update value. update table set value= 3 id= 1 so here actual want do: before add value +--------------+ | table | +--------------+ | id | value | +--------------+ | 1 | 1 | +--------------+ | 2 | 2 | +--------------+ after add value +-------------------+ | table | +-------------------+ | id | value | +-------------------+ | 1 | 1 , 3 | +-------------------+ | 2 | 2 | +-------------------+ it seems using integer field 'value' column, can't store more 1 number in 1 integer field, might it's set both 'id' , 'value' columns primary keys able insert more 1 value same id. if that's not want, consider using 'set' type. more info https://dev.mysql.com/doc/refman/5.0/en/set.html

android - Mulitple Fragment Outputs in GLSL 300 es -

while writing unit tests simple ndk opengl es 3.0 demo, encountered issue in using multiple render targets. consider simple fragment shader 2 outputs, declared in c++11 string literal. const static std::string multipleoutputsfragment = r"(#version 300 es precision mediump float; layout(location = 0) out vec3 out_color1; layout(location = 1) out vec3 out_color2; void main() { out_color1 = vec3(1.0, 0.0, 0.0); out_color2 = vec3(0.0, 0.0, 1.0); } )"; i have correctly setup fbo 2 color attachments (via glframebuffertexture2d) , glcheckframebufferstatus comes gl_framebuffer_complete. call gldrawbuffers(2, &attachments[0]), attachments vector of gl_color_attachmenti enums. afterwards, compile , link shader, without linking or compile errors (just used simple vertex passthrough irrevelant post). is there reason why can fragment location out_color1 not out_color2, using following opengles function? auto location = glgetfragda

oracle - The use of double vertical bars in pl/sql -

i want find reverse string program. there many examples have found none explain happens inside loop: declare ln_rev_input varchar2(50); ln_input varchar2(50):= '&input'; begin in reverse 1..length(ln_input) loop ln_rev_input := ln_rev_input||substr(ln_input, i, 1); end loop; dbms_output.put_line(ln_rev_input); end; i don't understand line, use of '||' in program: ln_rev_input := ln_rev_input||substr(ln_input, i, 1); i know '||' used concatenate strings don't understand how ln_rev_input being assigned. thanks the oracle/plsql || operator allows concatenate 2 or more strings together. what above code is reversing input string. lets pass string named oracle , starts end of string oracle , takes 1 character @ time using function substr(ln_input, i, 1) , concatenates character whatever value there in ln_rev_input variable. when starts, ln_rev_input null , result of ln_rev_input := ln_rev_input||subst

Python writing to a json -

ive been working on address book in python, , need make function can write json file. function needs able add/append specific json layout json layout example - {"addresses": [ {"name": "example", "town": "example", "address": "example"} ] } the problem - know how write json file, not how write json object... can please show me example of how add/append json object json string in python. can load , dump json whenever need return or change respectively. example: import json py_dict = {'a': 'b'} # convert dict string json_obj = json.dumps(py_dict) # oops need make change -> convert string dict py_dict = json.loads(json_obj) # append dict py_dict['hello'] = 'world' # convert dict string json_obj = json.dumps(py_dict)

Analysis of Algorithms - Find missing Integer in Sorted Array better than O(n) -

i working through analysis of algorithms class first time, , wondering if assist below example. believe have solved o(n) complexity, wondering if there better version not thinking of o(logn)? let a= a[1] <= ... <= a[n+1] sorted array of n distinct integers, in each integer in range [1...n+1]. is, 1 integer out of {1,...,n+1} missing a. describe efficeint algorithm find missing integer. analyze worst case complexity (number of accesses array a) of algorithm. the solution have relatively simple, , believe results in worst case n complexity. maybe on thinking example, there better solution? my solution for(i = 1; < n +1; i++) : if(a[i-1] > i) : return the logic behind since sorted, first element must 1, second must 2, , on , forth, until element in array larger element supposed be, indiciating element missed, return element should , have missing one. is correct logic? there better way go it? thanks reading , in advance assistance. th

c# - Get & Set MySQL Select -

what missing here, seems main form not calling method tsdbcon class , not connecting database, need help, i'm new get:set properties, doing wrong or what? thanks. public class tsdbcon { private string _user; private string _pass; public string user { { return _user; } set { _user = value; } } public string pass { { return _pass; } set { _pass = value; } } public void queryuser() { tsdbcon = new tsdbcon(); var connsettings = configurationmanager.connectionstrings["mydb"]; { string cn = connsettings.connectionstring; mysqlconnection conn = new mysqlco

ios - metadataquery deallocation before stopquery -

i'm using nsmetadataquery obtain list of files in icloud ubiquity documents directory in order populate tableview. code seems working, error stating query being deallocated without first calling stopquery. can't seem find discussion on topic. missing simple here? here function query , notification: var mymetadataquery : nsmetadataquery = nsmetadataquery() var cloudbackfiles : [anyobject] = [anyobject]() func metadataforlistoffiles() { mymetadataquery.predicate = nspredicate(format: "%k '*.sqlite'", nsmetadataitemfsnamekey)//change "%k '*.sqlite'" mymetadataquery.searchscopes = [nsmetadataqueryubiquitousdocumentsscope] nsnotificationcenter.defaultcenter().addobserver(self, selector: "metadataquerydidfinishgathering:", name: nsmetadataquerydidfinishgatheringnotification, object: mymetadataquery) mymetadataquery.startquery() }//metadataforlistoffiles func metadataquerydidfinishgathering(notification : nsno

How to set picture as background in python? I am only importing Graphics. No pygames or turtles -

i checked document graphics. says: image(anchorpoint, filename) constructs image contents of given file, centered @ given anchor point. can called width , height parameters instead of filename. in case, blank (transparent) image created of given width , height. but tried type: window = graphwin("game", 400, 400) image((200,200),"flower.png") but doesnt work. do need import picture first??or add window? please help. this should work, missed anchorpoint from graphics import * window = graphwin("game", 400, 400) myimage=image(point(200,200),"flower.png") myimage.draw(window)

c# - Adding List<object> to listBox (form2 to form1) -

this question has answer here: communicate between 2 windows forms in c# 10 answers i want transfer data form2 form1 's listbox1 . form2 includes several textboxes, i have tried face problem placing of code form1 cannot values needed form2 . can help, understand i'm not clear can answer questions code. private void button3_click(object sender, eventargs e) { list<form1other> filelist = new list<form1other>(); form1other[] f1other = new form1other[10]; form1 testform1 = new form1(); string tname = textbox1.text; string tdesc = textbox2.text; decimal tprior = numericupdown1.value; string tdate = datetimepicker1.value.toshortdatestring(); string tcompl = "unfinished"; filelist.add(new form1other(tname, tdesc, tprior, tdate, tcompl)); testform1.listbox1.items.add(filelist[0].tname);

bash - Generating a file path -

does know tool showing path 1 file another? ie, if css file in: /user/foo/bar/source/assets/myscreen and image in: /user/foo/bar/gamethings/smallimages how can quickly, without having count file levels (which simple, tedious, , has done often), generate path css image? first, realpath(1) gnu coreutils. then: $ realpath --relative-to=/user/foo/bar/source/assets/myscreen /user/foo/bar/gamethings/smallimages ../../../gamethings/smallimages

go - GOLANG HTTP Basic-Auth with Google App Engine URLFetch -

how can add authorization header urlfetch client go? there similar question answered java , python , not go . urlfetch.client(ctx) returns http client ( http://godoc.org/google.golang.org/appengine/urlfetch#client ) the http.client has methods get , post , etc... has do can hand arbitrary request. create request using http.newrequest : req, err := http.newrequest("get", "http://www.google.com", nil) then can add header this: req.header.set("authorization", "whatever") and call do : res, err := client.do(req)

angularjs - 2 different controllers in abstract view -

here thing <ion-tabs ng-controller="loginctrl"> <!-- news tab --> <ion-tab href="#/tabs/news"> <ion-nav-view name="tab-news"></ion-nav-view> </ion-tab> <!-- dashboard tab --> <ion-tab href="#/tabs/promotions"> <ion-nav-view name="tab-promotions"></ion-nav-view> </ion-tab> <!-- account tab --> <ion-tab href="#/tabs/signup"> <ion-nav-view name="signup"></ion-nav-view> </ion-tab> </ion-tabs> this mobile app, , abstract view, have there loginctrl attached because need everywhere, also, need controller present everywhere. need present everywhere because streaming music app, music must in every view out stopping. so, options have ? loginctrl defined there, need set controller named audioctrl . you can add number of controllers html, add more divs to this: <div ng-cont

c - First time working with opaque pointers -

i trying implement stack, not understanding use of opaque pointer. here declaration: /* incomplete type */ typedef struct stack_t *stack; /* create new stack, have call first */ stack new_stack(void); and here stack structure , new_stack function: struct stack_t { int count; struct node_t { void *data; struct node_t *next; } *head; }; stack new_stack(void) { struct stack_t new; new.count = 0; new.head->next = null; return new; } in eyes, returning address of new stack, throws error on compilation returning new. doing wrong? you returning stack_t value, return type of stack_new function stack , typedef struct stack_t* stack . need return pointer - change allocation of stack_t stack heap use malloc dynamic allocation. don't remember free() stack when not needed anymore, because dynamically allocated. stack new_stack(void) { struct stack_t* new = malloc(sizeof(struct stack_t)); new->count

WebSocket broadcast to all clients using Python -

i using simple python based web socket application: from simplewebsocketserver import websocket, simplewebsocketserver class simpleecho(websocket): def handlemessage(self): if self.data none: self.data = '' # echo message client self.sendmessage(str(self.data)) def handleconnected(self): print self.address, 'connected' def handleclose(self): print self.address, 'closed' server = simplewebsocketserver('', 8000, simpleecho) server.serveforever() it echoes messages sent each client same individual client, i trying send message received ws server clients connected it. can me please? or this: class simpleecho(websocket): def handlemessage(self): if self.data none: self.data = '' client in self.server.connections.itervalues(): client.sendmessage(str(self.address[0]) + ' - ' + str(self.data)) #echo mess

zsh - What does `(.N)` do in this extended glob? -

the prezto documentation has following example script setting symlinks: setopt extended_glob rcfile in "${zdotdir:-$home}"/.zprezto/runcoms/^readme.md(.n); ln -s "$rcfile" "${zdotdir:-$home}/.${rcfile:t}" done i understand in "${zdotdir:-$home}"/.zprezto/runcoms/^readme.md(.n) until (.n) . (.n) mean here? bonus question, ${rcfile:t} ? understand resolves name of rcfile don't know :t for. the bellow piece denies or negates (.n) content wich starts '^' readme.md ^readme.md(.n) the ^ symbol regular expression means beginning of something. the ${rcfile:t} part allows name stripping dir name of string. therefore loop create needed symlink each configuration file of zpresto dir.

Python: How to track "correct" answer in randomized multiple choice -

i built function prompt user question, followed randomly ordered answer choices. however, since answer choices randomized, how python recognize user input (a number: 1, 2, 3, or 4) "correct" answer? import random def answers(): answerlist = [answer1, answer2, answer3, correct] random.shuffle(answerlist) numberlist = ["1: ", "2: ", "3: ", "4: "] # loop print numbers in consecutive order , answers in random order, side side. x,y in zip(numberlist,answerlist): print x,y # question prompt = "what average migrating speed of laden swallow?" #incorrect answers answer1 = "gas or electric?" answer2 = "metric or english?" answer3 = "paper or plastic?" # correct answer correct = "african or european?" # run stuff print prompt answers() # ask user input; how program know number associate "correct"? inp = raw_input(">>> ") y

python - How can I view queries used for .create or .save without executing -

i want able retrieve sql statement being executed when calling mymodel(**kawrgs).save() or mymodel.objects.create(**kwargs) but without creating object in database. know can access queries via django.db.connection.queries and querysetobject.sql , , guess using transactions in way may useful, seems bit on head. any suggestions? thanks! a. you figure out method called in inner workings of save() or create() run final sql statement against database (probably in db backend cursor.execute() ) , use mock library prevent being executed , capture it's arguments instead.

ruby on rails - How to add multiple images to a single product in spree -

i want add ability on spree assign multiple images same product. from experience, best way ? there spree extension ? ( before develop scratch...) thanks! spree supports multiple images. assign them in admin panel. https://guides.spreecommerce.com/user/creating_products.html#images

ms access insert multiple rows into parent child tables -

hi i've been trying adapt prior stack overflow post situation coming short. have 2 ms access tables in parent child relationship (one many). i'm trying write vba insert 1 record parent table , multiple records child table. saw post close want 1 one relationship. provide me example of how multiple rows in child table? how can make new records cascade across 1 one relationship in ms access? i'm using ms access 2010 , i'm writing vba module in ms excel 2010. it relates how connect "many" entries table "one" table. (unless i'm missing point of question.) example works illustrate: option explicit sub addclasswithstudents() dim tblclass recordset dim tblstudents recordset dim db database dim classid long dim newkids() string dim kid variant set db = dbengine(0).opendatabase("database1.accdb") set tblclass = db.openrecordset("tblclasses", dbopendynaset) set tblstudents = db.o

Including attributes in custom Rails routes -

i hope title not misleading, don't know better title problem i'm working on: i have doctor belongs location , specialty. i'd route show action of doc controller this: /dentist/berlin/7 i defined routes this: get ':specialty/:location/:id', to: 'docs#show' and in views create following url link show action of doc controller: <%= link_to doc.name, "#{doc.specialty.name}/#{doc.location.name}/#{doc.id}" %> is solution problem? if not, there cleaner way construct urls possibly using resources? heck name problem? thank your in advance. for references, should have @ this page (especially the end of section 2.6 ) if single route, it's okay did. if want have more 1 route (like /dentist/berlin/7 , /dentist/berlin/7/make_appointment , etc.) might want structure bit more routes take advantage of rails resources . for example, instead of get ':specialty/:location/:id', to: 'doctors#show' ':specia

html - CSS beginner, help creating this layout? -

Image
in image below, on left output of html/css, on right layout like. i'm pretty clueless to: how center header why 'upper right' text , button being forced next line header (as opposed orienting in upper right how align text area right of image <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="outer_border"> <div class="inner_border"> <!--just use div represent image --> <div class ="image"> </div> <span class="upper_left_text"> upper left </span> <span class ="header"> <h2> header </h2> </span>