Posts

Showing posts from June, 2015

installation - Fixing Homebrew Warning: Directory should not end in a slash -

i installed homebrew today, , application suggested, ran brew doctor i got warning: warning: directories in path end in slash. directories in path should not end in slash. can break other doctor checks. following directories should edited: /users/myusername/ after googling this, opened vi ~/.bash_profile from terminal , manually removed "/" after username. .bash_profile looks this: export path=$path:/users/myusername export path=/usr/local/git/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/users/myusername then retyped prompt , got same warning. how fix this? did try restarting terminal? or @ least opening new session (tab)?

c# - how to pass entire model (with data) from view to controller? -

i don't know, may silly question trying find way solve this. need return entire model information (data) controller though of model properties not using in view. need them in controller action. example id, lable value. example <div class="col-md-6"> @html.labelfor(model => model.abstracttitleinenglishlabel, model.abstracttitleinenglishlabel, new { @class = "control-label mandatory" }) </div> from above first time able see label property value abstract title (in english) . after submitting controller not getting value in controller model.. if return same view controller. i can see property namel ike abstracttitleinenglishlabel , not value. means value of property not storing in model when passing controller. [httppost] public actionresult index(meetingabstract meetingabstract) { if (!modelstate.isvalid) { // re-render view when validation failed. return view(meetingabstract);

.net - Powershell won't preserve the type cast when updating an object's property -

i have array of objects want sort on "device" property. challenge "device" property can ip or hostname. so, approach separate them array ips , name (strings). the problem when cast device column net.ipaddress , save reverts string. here doing: $devicebyip = @() $devicebyhostname = @() foreach ($row in $data) { try { [net.ipaddress]$row.device = $row.device $devicebyip += $row } catch { #[string]$row.device | out-null $devicebyhostname += $row } } when this: [net.ipaddress]$row.device = $row.device reverts string. if this: $devicebyip | %{$_.device.gettype().fullname} i see device property of objects system.string. what doing wrong here? you didn't mention type of object $row is, appears $row native .net object device exposed system.string. if don't have access source code of $row type, can use select-object replace each $row object pscustomtype object has same properties: $devicebyip =

java - How write a compound Hamcrest statement (with a logical "or" operation) -

how go writing following junit assert hamcrest? asserttrue(var1 == 5 || var2 == 10); i can't use anyof() matcher wrapper because dont need multiple matchers, need multiple statements, 1 each variable var1 , var2 you write single hamcrest assertion turning variables single composite object: assertthat(immutablelist.of(var1, var2), either(contains(is(5), anything())) .or(contains(anything(), is(10)))); i suggest not particularly easy understand, nor explain mean , why represents success.

sitecore6 - How to Sort a TreeList in Sitecore 6 in the Source -

my team uses sitecore 6 content management system , .net interface sitecore api. in many of our templates make use of treelist . when adding new item selected items treelist automatically puts item @ bottom of list . in lists large. in cases end users see these lists sorted descending date field part of templates can added selected treelist. programmatically on .net side easy handle using linq orderbydescending , displays great in site visitors. trying figure out how display same in sitecore content editor . i've not found google search other there seems sortby can specify in source tried , can't have effect. has dealt before? again, main goal sort items in treelist in sitecore content editor itself. thanks input has. i created sorted-by-name treelist in response question: how sort selected items in sitecore treelist? it works , should converted sort date. unfortunately, have copy/paste quite lot of sitecore's existing code. significant cust

vb.net - How to Show my My Queried Data using OleDbDataReader vb -

i know walk in park of on site, n00b me giving me little trouble now, i'm trying program "query" button show/search data access file based on string entered in corresponding textbox. example if trying search access db employees named eric. want able type eric in firstname txtbox , show list of employees named eric within access file. far have code runs without error when click button whatever in textbox disappears. positive im missing , need guidance. here code far.doing in vb please help!!! using con = new oledbconnection("provider=microsoft.ace.oledb.12.0;data source=c:\users\eric\documents\fadv.accdb") dim sql string = ("select firstname, lastname info") dim cmd new oledbcommand(sql, con) con.open() dim reader oledbdatareader reader = cmd.executereader() while reader.read() txtfirstname.text = reader(0).tostring() console.writeline(" {0} = {1}", reader("

php - My autocomplete results are appearing with html tags -

when start writing on input, results appear html tags, example, if search "t" get: title<p><span>content</span></p> . , want title content, without no html tags. this php: $search = isset($_get['term']) ? $_get['term'] : ""; $pdo = conecting(); $read = $pdo->prepare("select * articles title ?"); $read ->bindvalue(1, "%$search%", pdo::param_str); $read ->execute(); $data = array(); while($res = $read ->fetch(pdo::fetch_assoc)) { $data[] = $res['title'].'-'.$res['content']; } echo json_encode($data); this jquery start autocomplete: $('.j_autocomplete').autocomplete({ source: 'http://localhost/project/tpl/search.php' select: function(event, ui){ var get= ui.item.value; returndata(get); }, change: function(data) { returndata($(this).val()); } }

javascript - Flood Fill after clearRect -

Image
i have script flood fill html5 canvas: $("#crop-canvas-draw").on("click touchstart", function(e){ if(selectedtool != 'pbucket') return false; var pagex = device == 'touch' ? e.originalevent.touches[0].pagex:e.pagex; var pagey = device == 'touch' ? e.originalevent.touches[0].pagey:e.pagey; var x = parseint(pagex - $("#crop-canvas-primary").offset().left); var y = parseint(pagey - $("#crop-canvas-primary").offset().top); var r = 255, g = 0, b = 0; var cwidth = cvsdraw.width, cheight = cvsdraw.height; var layerdata = ctxdraw.getimagedata(0, 0, cwidth, cheight); var layerdataori = ctx.getimagedata(0, 0, cvs.width, cvs.height); var layerdatacopy = ctxcopy.getimagedata(0, 0, cvscopy.width, cvscopy.height); var pps = []; var match = function(pp){ // pp = pixelpos var lr = layerdata.data[pp]; var lg = lay

html - Overflow:Visible outside the container -

i have fixed width div paragraph inside. demo: http://jsfiddle.net/hrasz/1/ the paragraph styled following css: p { white-space: nowrap; overflow: hidden; background: grey; color: white; text-overflow: ellipsis; } i add new css class p:hover, , show hidden text when hovered. p:hover { white-space: nowrap; overflow: visible; background: grey; color: white; } but seems text using overflow: visible, not background color. there way achieve this? note: can't change div with. paragraphs block elements - take width of containers, not content. try this p:hover { display:inline-block; white-space: nowrap; overflow: visible; background: grey; color: white; }

sql - duplicate rows MySQL -

hey using query this: insert likes( likes_memory_id, likes_comment_id, likes_owner_id, likes_like ) values ( :likes_memory_id, :likes_comment_id, :likes_owner_id, :likes_like) when ever user click button, query adds new row. query allows multiple time. prevent may use select statement , might succeed in 2 queries assue there better way it. (i made research if not exists statement didnt understand ) how avoid multiple likes? the simplest create unique index on columns want unique; create unique index uq_mem_own on likes( likes_memory_id, likes_owner_id ); ...and insert likes using insert ignore, insert value if it's not prevented index, otherwise ignore it; insert ignore likes( likes_memory_id, likes_owner_id, likes_like ) values ( :likes_memory_id, :likes_owner_id, :likes_like)

php - Custom function with MySQLi extension issue -

i don't know should wrong query written below this $username passed form post method, $mysqli connection variable, code: $mysqli = new mysqli("127.0.0.1", "root", "", "securelogin"); function usernamecheck($username, $mysqli) { $query = "select username user username = '$username'"; $stmt = $mysqli->prepare($query) $stmt->execute(); $stmt->store_result(); if($stmt > 1) { $stmt->close(); return false; } } this function checks if username exists in database ~~~~ i have solved function following code function usernamecheck($username, $mysqli) { $query = "select `username` `user` `username` = '$username'"; $result = $mysqli->query($query); if($result->num_rows != 0) { return false; } } but is, said, sql injection vulnerable. don't how code non-injectable your quer

HTML+CSS Formatting a button with <a> and <h> -

i've started learning html , css, , i've got problem: http://i.stack.imgur.com/npkl9.png the 3 buttons "spausk mane" should have text @ bottom of box, or 10px off bottom centered. line-height, margins etc. aren't working reason. hover settings doesn't work them, because think went wrong somewhere 'h3' , 'a' tag formatting, help? :s html: <div class="cta-wrap cf"> <a href="#" class="cta"><h3>spausk <br> mane</h3></a> <a href="#" class="cta"><h3>spausk <br> mane</h3></a> <a href="#" class="cta"><h3>spausk <br> mane</h3></a> </div> css: a.cta { color:white; text-decoration: none; text-align: center; } a:hover.cta {} .cta h3 { background-color:#287d7d; width: 150

javascript - Changing links in variable -

i have variable (loaded via ajax) contains piece of html document (but not whole document html, head , body. i change way: for each links in variable points same domain add class internal_link. for filtering links in whole document use example: $('a').filter(function() { return this.hostname && this.hostname === location.hostname; }).addclass('internal_link'); and works without problems. don't know how use code not on whole document on variable change value way. i tried below code: html = data.content; alert(html); $(html).find('a').filter(function() { return this.hostname && this.hostname === location.hostname; }).addclass('internal_link'); alert (html); but seems doesn't work. internal_link class isn't in html when run second alert. how can done? sample page script: <html> <head> <script src="jquery-1.11.1.min.js"></script> </head>

python - Zombie Connection in SQLAlchemy -

dbsession = sessionmaker(bind=self.engine) def add_person(name): s = dbsession() s.add(person(name=name)) s.commit() everytime run add_person() connection created postgresql db. looking at: select count(*) pg_stat_activity; i see count going up, until remaining connection slots reserved non-replication superuser connections error. how kill connections? wrong in opening new session everytime want add person record? in general, should keep session object (here dbsession ) separate functions make changes database . in case might try instead: dbsession = sessionmaker(bind=self.engine) session = dbsession() # create session outside of functions modify database def add_person(name): session.add(person(name=name)) session.commit() now not new connections every time add person database.

How do I group by hour and count number of entries in each bin using R -

sample of data imported form csv file: 1 24/05/2014 00:15 2 24/05/2014 00:17 3 24/05/2014 00:17 4 24/05/2014 00:17 5 24/05/2014 01:40 6 24/05/2014 01:48 i group hour , have group count in r, eg. date count 24/05/2014 00:00 4 24/05/2014 01:00 2 would appreciate help! thanks here example db <- data.frame(time = sys.time() + seq(1, 10000, = 100), counter = 1) res <- aggregate(db$counter, by=list(format(db$time, "%y-%m-%d %h")), sum) names(res) <- c("date","count") res hth

c# - listbox selectedindex only selecting last element -

i have listbox bound list of objects database. have secondary list has less objects want use mark selected elements. cell = new htmltablecell(); list<clasaautor> listaautori = datatabletoclasaautor(dal.citestetotiautori()); list<clasaautor> listaautoripublicatie = datatabletoclasaautor(dal.citestetotiautoriuneipublicatii(guidpublicatie)); listbox list = new listbox(); list.selectionmode = listselectionmode.multiple; list.id = "cbautori"; list.datasource = listaautori; list.datatextfield = "numecomplet"; list.datavaluefield = "guidautor"; list.databind(); foreach (clasaautor autor in listaautoripublicatie) { (int = 0; < list.items.count; i++) { if (list.items[i].value == autor.guidautor.tostring()) list.selectedindex = i; } } cell.controls.add(list);

java - am i allowed to use member variables in static inner class for fragments? -

all static fragments are: public static class somefragment extends fragment { int somenum; string name; } are values of somenum , name shared between different instances because class static? are values of somenum , name shared between different instances because class static? no. if want them shared, declare members static : public static class inner { static int somenum; static string name; } the static modifier on class valid on nested classes , , job there nested class not inner class (a class that's tied instance of containing class). has nothing whether members of class static.

ios - Change Storyboard View using Seague -

i have following code checks connection server, , depending on want change views if no connection found. nsstring *connect = [nsstring stringwithcontentsofurl:[nsurl urlwithstring:@"http://myserver.com"] encoding:nsutf8stringencoding error:nil]; if (connect == null) { [self performseguewithidentifier:@"network_failure" sender:self]; } else { // other code here } my problem not change views. have added storyboard segue between 2 views identifier of network_failure . not have navigation controller or that, problem? thanks help! no not problem. first of all, in objectivec exists nil object oriented null . must use that. so: if(connect == nil) or better: if(!connect) so due fact nil not same of null , probably code does't enter in if scope . you have been able discover breakpoint. anyway: be sure set trigger segue (line) 2 view controller , , name network_failure (that not best name. should instead view1toview2 ) as, m

What is the difference between printing signed and unsigned number in assembly (80x86)? -

i have task take existing assembly program prints signed number (word sized), , need change print unsigned numbers (word sized)... please me understand difference , how should accomplish this. that program prints signed number: .model small .stack 100h .data num dw -32768 nums db 6 dup(' '),'$' .code mov ax, @data mov ds, ax mov ax, num mov bx, 10 mov si, offset nums+5 next: cwd idiv bx cmp dx, 0 jge cont neg dx cont: add dl, 48 mov [si], dl dec si cmp ax, 0 jz sof jmp next sof: cmp num, 0 jge soff mov byte ptr[si], '-' soff: mov ah, 9 mov dx, si int 21h .exit end thanks! since word size 16 bits, range of signed numbers -32768 32767, range unsigned numbers goes 0 65535. , while you're declaring num -32768, computer represents in hex 0x8000, if it's performing signed operations -32768, if performing unsigned operations

django south migrations sqlite to postgres on heroku -

i've been working stupidly without database migrations since django 1.2 , i've said enough enough, time times seeing 1.7 brings in db migrations. south new me, it's been rough ride trying things working straight, , right i'm pulling hair out trying working on heroku. i think might have made things lot worse leaving late add south project. initial problems have been getting transition local heroku , being able migrate data. right i'm getting django.db.utils.programmingerror: column "campaign_id" of relation "beaconmanager_beacon" exists when trying run migrate on beaconmanager . i guess need know right is: does south work different databases, have sqlite3 local development dev heroku server runs postgres? the error above, better delete migrations folders , attempt run convert_to_south on of apps? what correct way of using south on heroku – i've noticed migrations should made on local , pushed heroku, run schemamigration myapp

Simple way to view members' Facebook basic info and friends list? -

thanks in advance advice. manage private, local community , looking use facebook's api verify information applicants. i'd have app authorize access basic info , friends list, , gives me simple interface view information. hoping there'd existing tool doing couldn't find one. i've created app, i'd prefer avoid having nitty gritty of api if possible. can suggest tool supports these goals, or easy way of assembling using off-the-shelf tools (maybe wordpress?) minimum of coding? ideally it'd store authorization token re-verification purposes if that's hard accomplish it's not mandatory requirement.

mysql - Allowing user to select report parameter in BIRT -

how build birt reports parameters view page:instead of birts default input box, here user provides required parameter codeigniter view page.i have built view page input parameter. have used , tested birts feature allow user input! want input form codeigniter controller. in advance if understand correctly, want run birt report directly application without using birt default window filling out report filters (parameters). can done specifying report parameters within url calling birt report. example: http:// host : port /birt/run?__report=report_name.rptdesign&parameter1=parameter1value&parameter2=parameter2value...

c++ - Is this "Tag Dispatching"? -

say have code: void bara() { } void barb() { } void fooa() { // duplicate code... bara(); // more duplicate code... } void foob() { // duplicate code... barb(); // more duplicate code... } int main() { fooa(); foob(); } and want remove duplicate code between fooa , foob use number of dynamic techniques such passing in bool parameter, passing function pointer or virtual methods if wanted compile time technique this: struct { }; struct b { }; template<typename tag> void bar(); template<> void bar<a>() { } template<> void bar<b>() { } template<typename tag> void foo() { // duplicate code bar<tag>(); // more duplicate code } int main() { foo<a>(); foo<b>(); } where have introduced 2 empty "tag" classes indicate bar use , templated foo , bar based on tag class. seems trick. questions: does technique have name? example of "tag dispatching"? read tag dispatching diffe

Why Java identifies unreachable code only in case of while loop? -

this question has answer here: if(false) vs. while(false): unreachable code vs. dead code 2 answers if have code like public static void main(string args[]){ int x = 0; while (false) { x=3; } //will not compile } compiler complaint x=3 unreachable code if have code like public static void main(string args[]){ int x = 0; if (false) { x=3; } for( int = 0; i< 0; i++) x = 3; } then compiles correctly though code inside if statement , for loop unreachable. why redundancy not detected java workflow logic ? usecase? as described in java language specification , feature reserved "conditional compilation". an example, described in jls, may have constant static final boolean debug = false; and code uses constant if (debug) { x=3; } the idea provide possibility change debug true false without making other c

ios - Fading in a background on opening a view -

seems simple, can't work different methods try. all want do, fade in image black background when open new view controller. so far i've tried this: //i've set image alpha 0 on storyboard - (void)viewdidload { [uiview animatewithduration:5.0 delay:0 options: uiviewanimationoptioncurveeasein animations:^{ myimage.alpha = 1; } completion:^(bool finished){ nslog(@"done!"); }]; } it runs, , image comes (just doesn't seem animating!) know simple question have spent hours looking solution. if appreciated! thanks! animation should work within -viewdidload may doing more in -viewdidload disrupting animation. or... instead move animation code -viewdidappear: -(void)viewdidappear:(bool)animated { //do animation here }

javascript - Is there a way to debug rendering problems in a famo.us app? -

Image
is there way turn debugging on or command show rendering problems when using famo.us? log statements helpful or other way of telling going when app being rendered. edit: here rendering problems have seen far 1- layout inconsistent across browsers (not talking ie yet!!!!). safari 7.02: chrome35: android firefox 29: 2- scrolling famo.us screwed. i have 3 main sections app (website): header (which scrollcontainer 4 surfaces). footer (which scrollcontainer 1 surface). content (2 scrollcontainers on left side , 2 scrollcontainers inside deck component on right side. each text/paragraph surface in respective scrollcontainer). now, if go app , notice scrolling screwed , have no idea why! don't know how can debug mess. p.s: code left un-minified , comments on purpose. but wait there more. scrolling confusing user the user has no idea view scrollable because no scrollbars visible . you can see on famo.us demo page . go , try scroll :). way can scroll

c# - Jquery Text Animation -

i coverting flash banner html5 banner . working fine except text animation. text should work like text working fine coming on border should work image animation working within border. here code enter link description here <div id = "wrapper" > <div id="maincontainer"> <div> <img id="introimg" src="http://i.imgur.com/fclbhjn.png"/> </div> <div id="images"> <p id="headline1txt" >striped bag</p><br /> <p id="headline2txt" >$14</p><br /> <p id="headline3txt" >sale $25</p><br /> </div> <div id="ctabtn"> <button class="btn btn-primary" type="button">shop now</button> </div> </div> </div> $(document).ready(function () { banneranimation(); }); function banneranimation(){

Android copy selected text in webview -

i want copy selected text in android webview, tried many methods nothing done. : android.text.clipboardmanager clipboard = (android.text.clipboardmanager) getsystemservice(context.clipboard_service); keyevent shiftpressevent = new keyevent(0, 0, keyevent.action_down, keyevent.keycode_shift_left, 0, 0); shiftpressevent.dispatch(webview); if(clipboard!=null) { string text = clipboard.gettext().tostring(); toast.maketext(this, "select_text_now "+text, toast.length_long).show(); } many thanks; according link copy text in webview in android 2.3 , below copy functionality in webview available default in android 3.0 , above , and may information may help, android: how select texts webview edit override text selection post may override onlongtouch in webview, keep text selection

postgresql - Ruby on Rails group -

i using postgresql in rails application , have following model log(id: integer, session: string, user: string, application: string, activity: string, event: string, time: datetime, parameters: hstore, extras: hstore, created_at: datetime, updated_at: datetime) now, count of event each user. type following in rails console log.select("count(event) event_count").group("user") but , get log load (0.7ms) select count(event) event_count "logs" group user => #<activerecord::relation [#<log id: nil>]> am doing terribly wrong? to statistics every user use group , count this: log.group('"user"').count(:event) this return hash having user key , value count value this: {name1: 2, name2: 12, ... } the query sent database: select count("logs"."event") count_event, "user" user "logs" group "user" i double escaped user column let postgres use col

ios7 - UITextView not scrolling in a loop -

i have uitextview updated in loop. text appended end of text view @ every loop. textview updates not scroll show end of text view. the method use append text is: - (void)appendtext:(nsstring*)text totextview:(uitextview *)textview { dispatch_async(dispatch_get_main_queue(), ^{ nsattributedstring* attr = [[nsattributedstring alloc] initwithstring:text]; [[textview textstorage] appendattributedstring:attr]; [textview scrollrangetovisible:nsmakerange([[textview text] length], 0)]; [textview setneedsdisplay]; [textview setneedslayout]; }); } the textview updates text continues show top. this compiled ios 7+ only. other answers on not solving this. any clues? you might want see this: https://github.com/steipete/pspdftextview basically, need give uitextview time calculation. don't scroll immediately, wait few moments (~0.2sec) before trying scroll text view. and, avoid having blank line @ end of text. needed add @ least 1 character in

css - Image/text opacity gradient to transparent -

Image
ive found looking on here not totally. ive seen gradients added images colours, im looking fade image out 0% opacity. in addition, in possible text also? effect this? this may helps fiddle added layer have opacity changing top bottom. html <div id="layer"></div> lorem ipsum dummy text of printing , typesetting industry. lorem ipsum has been industry's standard dummy text ever since 1500s, when unknown printer took galley of type , scrambled make type specimen book. has survived not 5 centuries, leap electronic typesetting, remaining unchanged. popularised in 1960s release of letraset sheets containing lorem ipsum passages, , more desktop publishing software aldus pagemaker including versions of lorem ipsum. long established fact reader distracted readable content of page when looking @ layout. point of using lorem ipsum has more-or-less normal distribution of letters, opposed using 'content here, content here', making readabl

matlab - Comparing two images with corr2 function -

i'm dealing recognition of traffic signs, i'm trying compare 2 images corr2 function on matlab, not giving results sometimes, using threshold find best images among template images. evaluate wrong image. want improve results of corr2 function pre-processing methods. method should follow? temp=[]; i=1:10 res=sprintf('%d.png',i) yol=fullfile('cember\taslak_cember\',res); a=imread(yol); b=imread('30_1.png'); a=rgb2gray(a); b=rgb2gray(b); a=im2bw(a,0.4); b=im2bw(b,0.4); c=corr2(a,b); temp=[temp c]; end max(temp) `

How can I log a functions arguments in a reusable way in Python? -

i've found myself writing code several times: def my_func(a, b, *args, **kwargs): saved_args = locals() # learned http://stackoverflow.com/a/3137022/2829764 local_var = "this other local var don't want log" try: a/b except exception e: logging.exception("oh no! args were: " + str(saved_args)) raise running my_func(1, 0, "spam", "ham", my_kwarg="eggs") gives output on stderr: error:root:oh no! args were: {'a': 1, 'args': (u'spam', u'ham'), 'b': 0, 'kwargs': {'my_kwarg': u'eggs'}} traceback (most recent call last): file "/users/kuzzooroo/desktop/question.py", line 17, in my_func a/b zerodivisionerror: division 0 my question is, can write reusable don't have save locals() @ top of function? , can done in nice pythonic way? edit: 1 more request in response @mtik00: ideally i'd way access save

php - Get Wordpress excerpt in list of posts -

i'm building custom wordpress widget/plugin return title , excerpt of post within permalink article. there struggling getting excerpt show. here current code: <?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts $recent ){ $categories = get_the_category($recent["id"]); $excerpt = apply_filters('get_the_excerpt', $recent->post_excerpt); echo '<a class="m-item diet-and-nutrition" href="' . get_permalink($recent["id"]) . '" title="look '.esc_attr($recent["post_title"]).'" > <div class="pix"></div><div class="eyebrow"> <b>' . $categories[0]->name . '</b> / '. $recent["post_date"].'</div> <figure>' . get_the_post_thumbnail($recent["id"], 'full') . '<figcaption clas

javascript - Read lines from a file and import as youtube embed to my site -

i want know how read text file , information javascript code. mean is, if have text file contained youtube video-id , title id:youtubevideoid1 "title1" id:youtubevideoid2 "title2" id:youtubevideoid3 "title3" id:youtubevideoid4 "title4" for example: id:gsjtg7m1mmm "x-man trailer!" i want web (index.html) read text-file's lines 1 1 ,by order, , show me on web embed of youtube videos this: <a href="https://www.youtube.com/watch?v=(videoid text file)" title="(title text file)"><img width="143" alt="(title)" src="http://img.youtube.com/vi/(video_id)/hqdefault.jpg" ></a> it need read , show lines start "id:" , first word after id video_id (so should var) , after "space" comes "title" (and can few words in language) should var also.. so if have 5 rows in text file id + title, show me on page, 5 embed videos... , if there mor

python - Replacing words tagged by #word# within a string -

i want search , replace words between 2 # marks. the text random (users add it). example: text = "hello #word1# #word2# thanks!" i need cut 2 words between # (word1 , word2) , change words title case - .title() . desired output: "hello #word1# #word2# thanks!" you can using regular expression: import re text = 'hello #word1# #word2# thanks!' print re.sub('#(\w+)#', lambda m:m.group(1).title(), text) output: hello word1 word2 thanks! edit if want retain bounding # characters, use noncapturing expressions: print re.sub('(?<=#)(\w+)(?=#)', lambda m:m.group(1).title(), text) output: hello #word1# #word2# thanks!

ruby - Use application class instance variable inside get block -

i using sinatra , have code: class app < sinatra::base configure @logger = logger.new "./log" end @logger.info "app started" #this line works "/info" @logger.info "/info inquired" #this not work , complain @logger nilclass end end why @logger inside block gives nil object? how can use @logger in case? ps. if use class variable @@logger , code above works. why instance variable not working in case? instance variables attach whatever object self @ time instance variables spring existence. on face of things, these values self: class app < sinatra::base #in here, self=app #when block executes, sees value self existed in #the surrounding scope @ time block created: configure #a block #so...in here self=app @logger = logger.new "./log" end @logger.info "app started" #this line works "/info" #a block #similarly, in here

hibernate - Spring with multiple persistence units defined in persistence.xml -

i trying have multiple persistence units different databases in spring application, without success far. have tried different scenarios, no 1 has helped, post initial code think should work: meta/persistence.xml <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/persistence http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="di-main-pu" transaction-type="resource_local"> <description>persistence unit main db (with stores) </description> <provider>org.hibernate.jpa.hibernatepersistenceprovider</provider> <non-jta-data-source>java:comp/env/jdbc/dimaindb</non-jta-data-source> <class>com.mydomainimport.entity.main.corestore</cla

firefox addon sdk - Set preferences in the user branch and unset them on uninstall -

i created firefox add-on following lib/main.js : const {cc,ci} = require("chrome"); var pref = cc["@mozilla.org/preferences-service;1"].getservice(ci.nsiprefbranch); pref.setintpref("network.http.response.timeout", 3600*24); it wasn't accepted following reason: add-ons change critical settings must revert changes when disabled or uninstalled. should make changes in default, rather user, branch. you need call getdefaultbranch("") on preferences service, , call preference methods on returned object rather on preference service directly. to revert preference default, set setintpref() , found out have this on uninstall: pref.clearuserpref("network.http.response.timeout") this command works fine if call in test-addon. have find out how implement command, executed when firefox-addon uninstalled? so how have understand these comments? how set preferences in "user branch"? i solved the second

matlab - Using textscan to read certain rows -

i trying read data text file using textscan matlab. currently, code provided below reads rows 1 4. need read rows 5 8, rows 9 13 , on. how achieve this? fileid=fopen(filename); num_rows=4; nheaderlines = 2; formatspec = '%*s %*s %s %s %*s %*s %*s %f %*s'; datain = textscan(fileid,formatspec,num_rows,'headerlines',nheaderlines, 'delimiter',',' ); fclose(fileid); use file = fopen('myfile'); content = textscan(file,'%s','delimiter','\n'); fclose(file); and have lines in file cell array of strings. take number of rows want , process them like.

Reading file from a local folder python after being imported from a parent folder -

there file main.py in folder a. folder b subfolder of folder a. there files subfolder.py , data.txt inside folder b. subfolder.py has function reads data.txt . reading happens when run file subfolder.py now in main.py import subfolder.py , call function reads data.txt says "no such file or directory data.txt " don't understand do. can help? could please show function in subfolder.py . the program may unsure of data.txt file is. run in first file: import os print os.path.dirname(os.path.realpath(__file__)) then add on string needed if python behaves in way expect behave, may need run import os filepath = os.path.dirname(os.path.realpath(__file__))+"\\"+"subfolder"+"\\"+"data.txt" and use filepath in function in subfolder.py open data.txt. does help?

ruby on rails - Receiving already loaded object from find_by method of ActiveRecord::Associations::CollectionProx -

i have following models class parent < activerecord::base has_many :children end class child < activerecord::base belongs_to :parent end what want changing child object parent.children.find_or_initialize_by() , modify child object, save parent.save . children doesn't saved. here's code. # prepare parent child p = parent.new({:name=>'parent'}) p.children << child.new({:name => 'child'}) p.save # modify , save child p = parent.first c = p.children.find_or_initialize_by({:name=>'child'}) #=> returns child created above c.name = 'new child' p.save #=> children aren't saved i know because find_by method returns new object rather 1 loaded. seems more natural me if code above works because method invoked through activerecord::associations::collectionproxy . missing work? or there reasons find_by on activerecord::associations::collectionproxy have work does? (i know can save modified child c.save , wa

c# - how to update other columns after select from DataGridComboBoxColumn when the row is still editing? -

i searching solution quite time without luck , hope can expert here. for example, have product class: public class productmodel : observableobject { private int id; public int id { { return id; } set { id = value; onpropertychanged("id"); } } private string name; public string name { { return name; } set { name = value; onpropertychanged("name"); } } private decimal unitprice; public decimal unitprice { { return unitprice; } set { unitprice = value; onpropertychanged("unitprice"); } } } and have class called order: public class order : observableobject { sportsentities db; private int id; public int id { { return id; } set { id = value; onpropertychanged("id"); } } private int productid; public int productid { { return productid; } set { productid = valu

arduino - Mac + Uno + avrdude: stk500_recv(): programmer is not responding -

i'm trying upload .hex file arduino. don't have problems uploading code through ide (like blink example or other). port , board correct. so problem appears when try upload avrdude -pm328p -carduino -p/dev/tty.usbmodemfd121 -b57600 -d -uflash:w:grbl_v0_8c_atmega328p_16mhz_9600.hex -v -v -v -v avrdude: version 6.1, compiled on mar 23 2014 @ 04:42:55 copyright (c) 2000-2005 brian dean, http://www.bdmicro.com/ copyright (c) 2007-2014 joerg wunsch system wide configuration file "/usr/local/cellar/avrdude/6.1/etc/avrdude.conf" user configuration file "/users/mikhail/.avrduderc" user configuration file not exist or not regular file, skipping using port : /dev/tty.usbmodemfd121 using programmer : arduino overriding baud rate : 57600 avrdude: send: 0 [30] [20] avrdude: send: 0 [30] [20] avrdude: send: 0 [30] [20] avrdude: ser_recv(): programmer not responding avrdude:

python - django models dependancy between two classes -

this question has answer here: manytomanyfield relationships between multiple models 1 answer i have 2 models in django app, both models contain multiple instances of other class. eg) topic can contain many books, , book may belong many topics. so, both must have manytomanyfield of other. code: class topic(models.model): books = models.manytomanyfield(book) class book(models.model): topics = models.manytomanyfield(topic) now problem is, error 'book' not defined. how rid of this? pass name of model string manytomanyfield instead of model itself, see here ( foreignkey behaves same way). code: class topic(models.model): books = models.manytomanyfield('book') class book(models.model): topics = models.manytomanyfield('topic') edit: i blindly answered without noticing same thing daniel. need have relationshi

.net - How are different types handled on the stack in CIL -

experimenting ildasm dive cil code became obvious cil working stack-based support expressions like il_0001: ldc.i4.s 13 ; 1f 0d il_0003: stloc.0 ; 0a il_0004: ldc.i4.s 31 ; 1f 1f il_0006: stloc.1 ; 0b il_0007: ldloc.0 ; 06 il_0008: ldloc.1 ; 07 il_0009: add ; 58 doing same float32 instead of int32 using ldc.r4 <num> there no difference in calling add making me wonder whether there different stacks different types or if there 1 stack holds metadata type specific element has on stack. there information specific implementation in ecma-335 or somewhere else? this addressed in partition i, part 12 (from e.g. pdf ), discusses virtual execution system (ves): as described below, cil instructions not specify operand types. instead, cli keeps track of operand types based on data flow , aided stack consistency requirement described below. example, single add instruction add 2 integers or

javascript - Can I dynamically inject a module into another module? -

assume have 2 modules in 2 separate files: the first everyone, call myapp: var myapp = angular.module('myapp', ['dependency.one', 'dependency.one']); in file: admin.js have module manages administrative functions. var myadmin = angular.module('myadmin', ['dependency.three', 'dependency.four']); only logged in admin users served admin.js. is possible inject myadmin module myapp module within admin.js file? alternately, there way include myadmin stuff, if admin.js file linked in page header, or alternative solution not seeing? $inject not appear work in context. no, not in current (1.x) version of angularjs. when application starts needs provided full set of modules used within application. so, have re-bootstrap whole application take additional modules account.

mysql - Multiple table query with wrong rows -

i want query 2 tables resulting query has more rows should be. my statement is: select * deal d, item d.dealstate = 'accepted' , ((d.owner = 'username1') or (d.itemid = i.itemid , i.owner = 'username1')) , d.deadline < now() with statement want user's active deals. deal table has owner (the requester), dealid, itemid, creationdate, dealstate, deadline, explanation , item table has owner (the owner of item), itemid, itemname, description . the problem want query 1 result. because 'username1' has 1 deal. query 10 rows, each of items matched deal. thought using "join" if user not owner of item, item table won't used. then, should do? i hope i'm clear enough. your query doesn't join correctly 2 tables because d.itemid = i.itemid isn't true in wrote. try select * deal d, item d.dealstate = 'accepted' , d.itemid = i.itemid , ((d.owner = 'username1') or ( i.owne

Boost-pp: how to determine if a macro parameter is a tuple -

a tuple comma-separated list enclosed parens, e.g. () (,) (thing,) (2,3) if have #define istuple(x) \\... i'd istuple(nope) resolve 0 , istuple((yep)) resolve 1. [fwiw, have _rtfm_'d plenty.] it done in preprocessing library little work, variadic macro data library (added boost since question posted) has ready-made solution. boost_vmd_is_tuple , defined in boost/vmd/is_tuple.hpp, should you're looking for: #include <iostream> #include <boost/vmd/is_tuple.hpp> #if boost_vmd_is_tuple() != 0 #error boost_vmd_is_tuple() != 0 #endif #if boost_vmd_is_tuple(nope) != 0 #error boost_vmd_is_tuple(nope) != 0 #endif #if boost_vmd_is_tuple((yep)) != 1 #error boost_vmd_is_tuple((yep)) != 1 #endif #if boost_vmd_is_tuple(()) != 1 #error boost_vmd_is_tuple(()) != 1 #endif #if boost_vmd_is_tuple((,)) != 1 #error boost_vmd_is_tuple((,)) != 1 #endif #if boost_vmd_is_tuple((thing,)) != 1 #error boost_vmd_is_tuple((thing,)) != 1 #endif