Posts

Showing posts from July, 2010

ruby - Rails find_or_create_by with/without where -

let's have model named task . , want find_or_create_by task. t = task.where(done: false).find_or_create_by(title: 'epic') this model works, create task title equal epic , done equal false. want query search through done equal false, don't want new record done equal false. how can it? you can use called: find_or_initialize_by . initializes record, doesn't create it. way, can override properties later on: task = task.where(done: false).find_or_initialize_by(title: 'epic').first task.done = true # or nil or whatever want! task.save i saved first record task.done = true . if there more 1 record, can use each iterate through of them, , save them all. edit: task.where(:done => false).first_or_initialize |task| task.done = true task.title = 'epic' end

infragistics ultramonthviewsingle runtime data bind from dataset -

i'm using infragistics winform. in infragistics ultramonthviewsingle. want bind data @ run time dataset. use c#. infragistics schedule components expose calendatinfo property can set instance of ultracalendarinfo. ultracalendarinfo holds information appointments, notes, users , on. nice thing can add 1 calendar info, populate data , set different schedule controls. here can find topic showing how populate calendar info dataset.

matrix - Apply a function to all column pairs of two matrices in R -

i have 2 matrices same columns , rows names: > metilacion[1:5,1:5] a2bp1 a2m a2ml1 a4galt aaas paciente1 0.2804884 0.5816559 1.1814702 -0.6234276 -0.3997400 paciente2 0.5122471 1.2944264 0.5673766 0.4490407 -0.6045510 paciente3 -0.3116356 1.6085049 0.9970350 0.3379215 -0.4787046 paciente4 -0.7220941 0.8771948 2.1445474 -0.5837802 -0.4848246 paciente5 -0.3369999 1.5885716 0.8185654 0.2374583 -0.5698858 > expresion[1:5,1:5] a2bp1 a2m a2ml1 a4galt aaas paciente1 -0.9082274 -0.17736185 0.8846485 -0.36059775 -0.5624139 paciente2 -1.7152290 1.62368019 0.3292617 1.35968899 -0.9220157 paciente3 -1.0581859 0.33028098 1.1020073 0.01870851 -0.9669236 paciente4 -0.8389615 1.33754885 0.5122861 -0.14583960 -0.8196533 paciente5 -1.5273835 0.06418637 0.2695209 0.03381359 -0.4461490 i want compute correlation coefficient between pair of columns between 2 matrices , generate object correlation values every c...

bash - Getting name of file inside a rar without unrar -

trying bash script together, i'm stuck @ this. rar splited x files, within rar 1 single file. i'm doing below: cd $dir rarfile in $(find -iname "*.part1.rar") echo "rar file: " $rarfile >> $dir/execute.log name = $(unrar lb "$rarfile") echo "name of file inside rar container: " $name >> $dir/execute.log extension ="${name##*.}" echo "extension: " $extension >> $dir/execute.log filename = ${name%.*} echo "name: " $filename >> $dir/execute.log # unrar x -y -o- $rarfile $uprar_dir done the excecute.log below: rar file: ./file.part1.rar name of file inside rar container: extension: name: cant seem $name working. unrar working fine should. pls help. in bash assign value variable cannot have spaces ie: name=$(unrar lb "$rar...

ruby - Using external variable in rspec-puppet test -

have stuck using variable in rspec. here params.pp case $::osfamily{ debian: { $ssh_daemon = "ssh" } redhat: { $ssh_daemon = "sshd" } in rspec test need use variable $ssh_daemon this: it { should contain_service("${ssh_daemon}").with( :ensure => 'running', :enable => 'true', )} here ssh.pp file service { "${ssh_daemon}": ensure => running, enable => true, } how can write variable ($ssh_daemon) test work? you can mocking facter output. something like: context 'service on debian' let(:facts) { { :osfamily => 'debian' } } { should contain_service("ssh") } end context 'service on redhat' let(:facts) { { :osfamily => 'redhat' } } { should contain_service("sshd") } end

haskell - Parsing complex files with Parsec -

i parse files several sequences of data (same number of column, same content, ...) haskell. data sequences delimited keywords before , after. begin 1 882 2 809 3 435 4 197 5 229 6 425 ... end begin 1 235 623 684 2 871 699 557 3 918 686 49 4 53 564 906 5 246 344 501 6 929 138 474 ... end my problem after several tests parsec, have impression parsec rather made parse file line line , not whole file . is parsec right way make want or should consider other tool happy or alex ? is there website (or other ressource) providing examples of parsing complex text files parsec ? note : example give very simple one. things more tricky in files many more keywords , combinations. the format you've described wouldn't hard @ handle in parsec. as learning how use it: first step should avoid whatever guide gave impression parsec worked line-by-line. recommend chapter 16 of real world haskell place started, , once you're comfortable b...

c# - How to remove border from a maximized WPF window? -

Image
i want run wpf application in fullscreen mode. used following code this project : class winapi { [dllimport("user32.dll", entrypoint = "getsystemmetrics")] public static extern int getsystemmetrics(int which); [dllimport("user32.dll")] public static extern void setwindowpos(intptr hwnd, intptr hwndinsertafter, int x, int y, int width, int height, uint flags); private const int sm_cxscreen = 0; private const int sm_cyscreen = 1; private static intptr hwnd_top = intptr.zero; private const int swp_showwindow = 64; // 0×0040 public static int screenx { { return getsystemmetrics(sm_cxscreen);} } public static int screeny { { return getsystemmetrics(sm_cyscreen);} } public static void setwinfullscreen(intptr hwnd) { setwindowpos(hwnd, hwnd_top, 0, 0, screenx, screeny, swp_showwindow); } } in main .cs file wrote following c...

ruby on rails - Arel AND clause and Empty condition -

consider following code fragment: def sql billing_requests .project(billing_requests[arel.star]) .where( filter_by_day .and(filter_by_merchant) .and(filter_by_operator_name) ) .to_sql end def filter_by_day billing_requests[:created_at].gteq(@start_date).and( billing_requests[:created_at].lteq(@end_date) ) end def filter_by_operator_name unless @operator_name.blank? return billing_requests[:operator_name].eq(@operator_name) end end def filter_by_merchant unless @merchant_id.blank? return billing_requests[:merchant_id].eq(@merchant_id) end end private def billing_requests @table ||= arel::table.new(:billing_requests) end in method filter_by_merchant when merchant id becomes empty, should value must returned arel ignore , clause effect? also, there better way handle case? you should return true. when run .and(true) converted 'and 1' in sql. def filter_by_merchant return true if @merchant_id.blank? bi...

node.js - Mysql encoding error -

i trying insert row in mysql node using mysql2 driver, , getting following error: running query \"insert outgo (name, monthidmonth, type, distribution, recurrent, amount) values ('penalizări', (select max(idmonth) `month`), '3', '1', '1', '0');\" failed: error: incorrect string value: '\\xc4\\x83ri' column 'name' @ row 1 the outgo table created this: create table if not exists `outgo` ( `idoutgo` int unsigned not null auto_increment, `name` varchar(50) not null, `apartmentsgroupidapartmentsgroup` int unsigned null, `outgocolumninfoidoutgocolumn` int unsigned null, `metering` enum('none','cold_water','hot_water','other') null, `distribution` enum('manual','person','apartment','surface','consumption', 'automated','heat_surface') null, `amount` double(14,2) null, `camount` double(14,2) null, `cos...

Why does bower not seem to install the missing dependencies with `bower install`? -

i'm trying install ember-cli-foundation-sass in new ember-cli app. error: $ ember server --proxy http://localhost:3000 missing bower packages: package: jquery * specified: ^1.11.1 * installed: 2.1.4 run `bower install` install missing dependencies. i run bower install recommends, when start server, see same error message. what can install jquery 1.11.1 ? you can use bower install jquery! bower install jquery ...or if need install version, use bower install http://code.jquery.com/jquery-<version>.min.js

javascript - Image filename and path validation is not working in Firefox but working in Chrome -

this image filename , path validation code works in chrome not in firefox. shows validation error if upload correct image file. can make code work in firefox? function add_img(f) { z = f; img_title = $('#img_title' + f + '').val(); img_path = $('#img_path' + f + '').val(); img_desc = $('#img_desc' + f + '').val(); if (img_title == '' || img_path == '') { alert('please upload valid image title.'); return false; } var uploadcontrol = img_path; var reg = /^(([a-za-z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+ (.jpeg|.jpeg|.gif|.gif|.png|.png|.jpg|.jpg)$/; if (uploadcontrol.length > 0) { //checks control value. if (!reg.test(uploadcontrol)) { alert("only jpg,jpeg,gif,png files allowed!"); return false; } } } i don't think there difference in regex implementation across browsers. possibility not getting full path check against in firefox , getting...

php - How can i display a username as a link -

i little new php. trying display username logged in link home page. have. if (loggedin()) { echo '<a href="homepage.php"> $user->get_fullname($uid) </a>' ; echo '<a href="logout.php"> log out </a>'; } but can see not display username, display have in between link. not know go here. you want: if(loggedin()){ echo '<a href ="homepage.php">'. $user->get_fullname($uid) .'</a>' ; echo '<a href="logout.php"> log out </a>'; } else { ?> in php single quotes not parse variable. alternative syntax is: echo "<a href ='homepage.php'> $user->get_fullname($uid) </a>" ;

html - Found the following on a page - title="header=[] body=[ - how does it work? -

go http://www.paperbackswap.com/science-fiction-hall-fame-volume/book/0765305372/ scroll down looking button labeled "order book" , hover on it. it displays multi-line "title" the source shows: title="header=[] body=[did know club if make amazon purchases starting on our site? click here when want buy amazon , purchase support pbs!]" note - if inspect entity using firebug, shows title="" to see source showing you, view source of page. tried search on title="header[] google can't handle double quote , [] characters. does know how working? it appear facility text in "header[]" displayed, perhaps, header line "title" , text in "body[]" body of "title." here example line breaks: title="header=[] body=[- order book $4.94 (price includes s&h).<br />- if member, please log in request it.<br />- or join club , book 1 credit , $0.49 swap fee.]" to see ...

java - How to choose the right JDK JavaEE Spring version -

generally use following framework in project: spring mvc + hibernate tomcat container. and never care version, later better. this concrete sdk, framework version in project: jdk 1.7 spring framework: spring-webmvc >> 4.1.6.release hibernate: hibernate-entitymanager >> 4.3.10.final org.hibernate.javax.persistence >> hibernate-jpa-2.1-api >> 1.0.0.final tomcat 7 the application works under tomcat, meet problems when deploy application tomcat java ee server(which support javaee 5 only). one of error got like: java.lang.nosuchmethoderror: javax.persistence.table.indexes() it seems indexes new method in jpa2.1(which supported in javaee 7) while java ee server not provide it. but shown, hibernate dependency org.hibernate.javax.persistence >> hibernate-jpa-2.1-api >> 1.0.0.final provide methods, why java ee server can not use that? and solve problme, given javaee server support javaee 5 only, should under consideratio...

javascript - Toggle menu on click of two elements -

var main = function() { $('#menu-open').click(function() { $('.menu').animate({ left: '0px' }, 200); $('body').animate({ left: '285px' }, 200); }); $('#menu-close').click(function() { $('.menu').animate({ left: '-285px' }, 200); $('body').animate({ left: '0px' }, 200); }); }; $(document).ready(main); i want able close menu click of #menu-close or #menu-open when menu open. how can this? you can bind single function both open/close button. inside function, check menu status. example: $('.menu-open, .menu-close').click(function() { var left = $('.menu').offset().left; if (left < 0) { $('.menu').animate({ left: 0 }, 200); $('body').animate({ left: 285 }, 200); } else { $('.menu').animate({ left: -285 }, 200); $('body').animate({ left: 0 }, 200); ...

Trying to delete a directory and his hidden files in linux with php -

from command line when use: rm -fr /path/dir/{*,.??*} i can delete files in /path/dir including hidden files, when try make php code: system('rm -fr /path/dir/{*,.??*}') nothing happens. i can't find why doesn't works finally this: system('rm -fr /path/dir && mkdir /path/dir); i removed directory files , after created directory. , work done.

Xcode 6.3: Swift String 'characters' property not found -

when copy example apple swift manual code character in "dog!🐶".characters { print(character) } i error message could not find member characters what has happened 'characters' property in xcode 6.3 ? string property characters available in xcode 7 (swift 2.0). delete .characters , work xcode 6.3 (swift 1.2). for character in "dog!🐶" { println(character) }

Python tkinter "KeyError: <class __main__." error -

i relatively new tkinter. created application , ran fine. added helppage class , gave me error "keyerror: " removed helppage class , same error showed main.pagetwo. cannot seem run anymore. here code (the functions indented though doesn't show up): ## program calculates number of pixels need removed each edge of collected images based on camera paramters , measured distances ## horizontal_field_of_view = camera_distance*(sensor_width/focal_length) sensor_width horizontal width. sensor_width , focal_length measured in mm , camera distance measure in m ## resolution = horizontal_field_of_view/number_of_pixels horizontal_field_of_view measured in m. results width of single pixel measured in m. import tkinter tk import tkfiledialog import os class application(tk.tk): pixsize=0 cnt=1 height=0 width=0 numpixx=0 numpixy=0 numimages=0 file='none' def __init__(self,*args,**kwargs): tk.tk.__init__(self,*args,**kwargs) co...

java - efficient way to color text in JTextPane -

i have problem regarding coloring keywords in jtextpane. in other words, want make mini ide write code , want give color (say blue) keywords "public" "private" ... etc. problem is slow !! each time hit "space" or "backspace" key function scans whole text give color keywords, when write lot of code in textpane gets slow. here function of matching keywords: public void matchword() throws badlocationexception { string tokens[] = arabicparser.tokennames; int index = 0; string textstr[] = textpane.gettext().split("\\r?\\n"); for(int i=0 ; i<textstr.length ; i++) { string t = textstr[i]; stringtokenizer ts2 = new stringtokenizer(t, " "); while(ts2.hasmoretokens()) { string token = ts2.nexttoken(); // iterations reduced removing 16 symbols search space for(int j = 3 ; j<tokens.length-5 ; j++) { ...

Permutations of a list of length n in python -

so started learning python , thought exercise try write little script see if could. turns out couldn't right , have left it, got little determined , have vendetta against particular function. i'm wanting code take raw input of given number , generate possible permutations of list of numbers it. eg. if input "5" generate permutations of length 5 [1, 2, 3, 4, 5]. what tried follows: from itertools import permutations math import factorial n = raw_input("input number generate permutation list") factorial_func = factorial(n) print "there %s permutations follows:" %(factorial_func) print list(permutations([1:n], n)) i know faulty line line 10 because of [1:n] part , don't know how make list 1 n , put permutation function. (i hoping going [1:n] generate list 1 n in same way can use access parts of list b list_name[a:b] seems isn't case) sorry if seems trivial or obvious mistake, started trying learn python few days ago. ...

python - Unicode on Scrapy Json output -

i'm having problem on json output of scrapy. crawler works good, cli output works without problem. xml item exporter works without problem , output saved correct encoding, text not escaped. tried using pipelines , saving items directly there. using feed exporters , jsonencoder json library these won't work data includes sub branches. unicode text in json output file escaped this: "\u00d6\u011fretmen s\u00fcleyman yurtta\u015f cad." but xml output file correctly written: "Öğretmen süleyman yurttaş cad." even changed scrapy source code include ensure_ascii=false scrapyjsonencoder, no use. so, there way enforce scrapyjsonencoder not escape while writing file. edit1: btw, using python 2.7.6 scrapy not support python3.x this standart scrapy crawler. spider file, settings file , items file. first page list crawled starting base url content scraped pages. data pulled page assigned variables defined in items.py of scrapy project, encoded in ...

python - Pygame: Cell Physics -

i'm making dumbed down version of agar.io . currently, cell placed upon grid background in game. cell eats food, smaller square section inside circle eats food (in program), noticeable when big enough. also, when press spacebar, split cell 2 smaller parts, after few seconds merge back. require key_up , k_space event, not sure how implement that. also, once around mass of 34, can press w shoot tiny bit of yourself, smaller cell @ around 14 set mass. i attempted slow down cell once reaches mass bunch of if statements. in game, slows down naturally. here , here sources depicting math used in game. here code have: import pygame, sys, random pygame.locals import * # set pygame pygame.init() mainclock = pygame.time.clock() # set window width = 800 height = 600 thesurface = pygame.display.set_mode((width, height), 0, 32) pygame.display.set_caption('') bg = pygame.image.load("bg.png") basicfont = pygame.font.sysfont('calibri', 36) # set colors ...

Need Minimum Textures required for OpenGL -

quick question, minimum amount of textures can bound fragment shader opengl implementation required have? note: know opengl 1.5, opengl 2.0, , opengl 2.1 opengl 1.x , 2.x require @ least 2 texture units. opengl 3.x , 4.x require @ least 16. current gpus have 32. you can find values in opengl specification itself, in "implementation dependent values" table. specific value called max_texture_units in 1.x , 2.x , max_texture_image_units in 3.x , 4.x.

ruby - Association Error with Sorcery Gem in Rails -

i used sorcery set authentication in rails , i'm trying create model user id user linked reference model data entered, error: couldn't find user without id it refers following code: def create @user = user.find(params[:user_id]) @certificate = @user.certificates.create(certificate_params) redirect_to certificate_path(@certificate) end to answer basic questions i've asked myself, user logged in... that's weird error if above code. should have gotten couldn't find bar 'id'= instead. error above given if provide no args find @ all, ie. user.find() anyway, underlying problem here params[:user_id] doesn't contain value expect to, , contains no value @ all. haven't shown enough of other code determine why is, but doesn't matter... unless want people able change url , add certificate other user in system shouldn't rely on params[:user_id] creating associated objects, should use current_user - that's kind of w...

java - How to partially stream an mp3 file -

i'm trying partially stream mp3 file, bytes before requested "byte-mark" stil being downloaded: let's assume mp3 file 7000000 bytes in filesize. i "jump" 6000000 bytes , begin streaming there end. but notice every byte 1-5999999 being downloaded before mp3 file being played 6000000 byte mark. i using jlayer (java zoom - http://www.javazoom.net/javalayer/javalayer.html ) play mp3 file. import java.io.filenotfoundexception; import java.io.ioexception; import java.io.inputstream; import java.net.malformedurlexception; import java.net.url; import java.net.urlconnection; import javazoom.jl.decoder.javalayerexception; import javazoom.jl.player.advanced.advancedplayer; try { url url = new url("http://somerandomsite.com/audiotestfile.mp3"); urlconnection connection = url.openconnection(); connection.connect(); int filesize = connection.getcontentlength(); inputstream inputstream = url.openstream(); system.out.println(...

css - Can't set header background of a table the way I want -

Image
i’m trying adapt css code found, table seems ugly (according me). i'll explain on picture. css: td, th { border-left: 1px solid #494437; border-top: 1px solid #494437; padding: 10px; text-align: left; } th { background-color: #b8ae9c; -webkit-box-shadow: inset 2px 2px 0px 0px rgba(255,255,255,1); -moz-box-shadow: inset 2px 2px 0px 0px rgba(255,255,255,1); box-shadow: inset 2px 2px 0px 0px rgba(255,255,255,1); border-top: none; text-shadow: 0 1px 0 rgba(255,255,255,.5); } td:first-child, th:first-child { border-left: none; } i explained want image: edit: example expect white area on right side, when add padding-right: 0.2em; "th". doesn't change anything. is expecting? .table { border: 1px solid #000; float: left; } .header { border: 2px solid #ccc; border-width: 2px 0 0 2px; background-color: #b8ae9c; margin: 2px; float: left; } <div class="table...

css - Bug in Chrome: render big box-shadow -

Image
i want set box-shadow of div to: ... 0 0 500px ... (big blur value). in google chrome (last version, windows & ubuntu) see strange squares-artefacts. in firefox normal shadow. jsfiddle: http://jsfiddle.net/2grgf/1/ (from how create box-shadow covers entire page? ) is there workarounds? you can emulate inset box-shadow using filters. this: http://jsfiddle.net/igoradamenko/vmeortsf/ html: <div class="shadow"> <div class="blurred"></div> </div> css: .shadow { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: #555; } .blurred { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 60%; height: 60%; border-radius: 50%; background: #fff; -webkit-filter: blur(100px); filter: blur(100px); } today filters supported modern browsers except ie (all of them). may use conditional rules them. so, ...

php - cakephp 3.0 how to populate a select field with values instead of id -

i looking previous answer, ones i've found related older cakephp versions i have 2 tables, 'magazines' , 'issues' there relation 'issues' belongsto 'magazines', issuestable looks like: public function initialize(array $config){ $this->belongsto('magazines', [ 'foreignkey' => 'id' ]); } table magazines has 2 fields, magazines.id , magazines.name table issues has 2 fields, issues.id, issues.magazine_id issues.magazine_id foreign key to populate select input in issues view magazine.name values , save issues.magazine_id, i've set controller this $this->set('magazines', $this->issue->magazine->find('list')); then i've added following code issue view add.cpt <?php echo $this->form->input('name', [ 'type' => 'select', 'multiple' => false, 'options' => $magazines, 'empty' => ...

python - How to detect bugs on POST request(flask)? -

i'm new flask. trying apply post/redirect/get pattern program. here did. in index.html {% block page_content %} <div class="container"> <div class="page-header"> <h1>hello, {% if user %} {{ user }} {% else %} john doe {% endif %}: {% if age %} {{ age }} {% else %} ?? {% endif %}</h1> </div> </div> {% if form %} {{wtf.quick_form(form)}} {% endif %} {% endblock %} in views.py class nameform(form): age = decimalfield('what\'s age?', validators=[required()]) submit = submitfield('submit') '''''' @app.route('/user/<user>', methods=['get', 'post']) def react(user): session['user'] = user form = nameform() if form.validate_on_submit(): old_age = session.get('age') if old_age != none , old_age != form.age.data: flash('age changed') session...

vba Excel to Access: zero length string to Null number -

i have 2 values in same column in excel. select 1 of them , run following: debug.print isnumeric(selection), _ vartype(selection), _ vartype(trim(selection)), _ ">" & selection.value & "<", _ len(trim(selection)), _ len(selection), _ selection.numberformat then select other , run same debug. and this: true, 5, 8, >9.46979663546499<, 16, 16, general false, 8, 8, ><, 0, 0, general note: column has multiple occurrences of both can explain this? i've been vba'ing , excel'ing long time , still don't (in detail) number formatting excel , how work them best. think have stumble upon new this. in case objective ms access automatically understand column double/number/float/whatever column can null when import , not throw errors. have achieve through formatting/changing in excel prior importing it. (partly because work best client's process...

How to insert image into database in Java -

i want insert image database through "browse" button. problem in line, ps.setblob(l16, inputstream) ? line shows error every time. my code is: class.forname("com.mysql.jdbc.driver"); connection con=drivermanager.getconnection( "jdbc:mysql://localhost:3306/hostel_management","root",""); preparedstatement ps= con.preparestatement("insert student_info values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ps.setstring(1, tf1.gettext()); ps.setstring(2, tf2.gettext()); . . . ps.setstring(15, tf15.gettext()); inputstream inputstream = new fileinputstream(new file(tf16.gettext())); ps.setblob(16, inputstream); ps.execute(); joptionpane.showmessagedialog(null, "successfully inserted", "message", joptionpane.error_message); con.close(); convert image base64, , save text database. when want back, , revert bitmap , use it. use apache commons @ best way base64.encode(fileutils....

Where to put PHP files, root directory or public_html directory? -

i saw alot of frameworks laravel, zend, symfony .... , noticed put php files in root directory, when saw wordpress , vbulletin , alot of famous scripts, , noticed put php files in public directory. i wanna know best place put php files. root directory or public_html directory? better? , why! , difference between them? assuming "root directory" mean somewhere outside of web server's document root, , "public_html" web server's document root... it's best practice have scripts must directly accessible within web server's doc root. if happens php gets disabled, don't want whole world downloading copies of source code. scripts can include files wherever can access on disk, it's possible put loader in web server's doc root , keep whole application out of there. common , best practice. wordpress doesn't default because folks installing wordpress don't know they're doing. it's easier them extract tarball 1 pl...

python - Django - How to delete an article? -

i'm trying create button on framework django let me delete own article on blog. tried create code functionality, doesn't work. views.py if(request.get.get('delete')): #if button clicked delete_article = get_object_or_404(article, id=id) if request.post: form = deletenewform(request.post, request.files) if form.is_valid(): delete_article.delete() return httpresponseredirect("/") template.html <form enctype='multipart/form-data' action="." method="post" class="form" autocomplete="off" autocorrect="off"> {% csrf_token %} <div class="form-group">titre {{ form.title.errors }} {{ form.title }} </div> <div class="form-group">contenu {{ form.media }} {{ form.contenu.errors }} {{ form.contenu }} </div> <div class="form-group"> ...

regex - Find and replace entire value in R -

i'm looking way use find , replace function in r replace entire value of string, rather matching part of string. have dataset lot of (very) long names, , i'm looking efficient way find , change values. so, instance, tried change entire string string <- "generally.speaking..do.you.prefer.to.try.out.new.experiences.like.trying.things.and.meeting.new.people..or.do.you.prefer.familiar.situations.and.faces." to "exp" with code string <- gsub("experiences", "exp", string) however, results in substituting "exp" part of string matches "experiences", , leaves rest of long name intact (bolded clarity): "generally.speaking..do.you.prefer.to.try.out.new. exp ..like.trying.things.and.meeting.new.people..or.do.you.prefer.familiar.situations.and.faces." in case, because string contains "experiences", should replaced "exp." is there way tell gsub or other function replace...

ios - Adding gesture recognizer to UIImage, not UIImageView -

i have uiimageview 'view mode' set 'aspect fit' in interface builder.i want add gesture recognizer image inside of uiimageview .to clarify say: i have uiimageview bounds.size.width = 100; , bounds.size.height = 100; , have uiimage size 100x50. so, when add uiimage uiimageview there exists spaces of 25 top , 25 bottom. don't want recognize user's tap when he/she taps on these spaces. want know when user tapped on uiimage . how can that? as uiimage extends nsobject can not add uitapgesturerecognizer it, have add gesture uiimageview itself. in of uigesturerecognizer delegate methods: - (bool)gesturerecognizershouldbegin:(uigesturerecognizer *)gesturerecognizer; or - (bool)gesturerecognizer:(uigesturerecognizer *)gesturerecognizer shouldreceivetouch:(uitouch *)touch; get touch's location in uiimageview . using cgpoint location = [_gesture locationinview:yourimageview] touched point, image's frame using this link. check...

python - Tkinter Async Error...without multithreading? -

i've needed gui work python , stumbled on tkinter. part, it; it's clean , intuitive , brief. there is, however, 1 little sticking point me: crashes out of nowhere. program run 5 times in row , sixth time, halfway through freeze , error tcl_asyncdelete: async handler deleted wrong thread my efforts find solution problem, both on website , others, have multithreading, don't use multiple threads. not explicitly, anyway. suspect fact have timer in gui blame, have not been able figure out why error pops up, or indeed why infrequent. what follows shortest tkinter program i've written. happens in of them, suspect problem easiest see here. , appreciated, don't point me toward solution without telling me how applies code, because assure you, have looked @ it, , either doesn't apply or didn't understand how did. don't mind having missed answer, i'm new tkinter (and multithreading in general) might need told more explicitly. this code simulation of ...

How to use XSLT 2.0 in Eclipse? -

in release notes of wtp 3.1.0 talk wtp supporting xslt 2.0. have eclipse luna 4.4.1 wtp installed, but <xsl:value-of select="system-property('xsl:version')" /> still returns 1.0 . so how can use xslt 2.0 in eclipse? when go preference, have xalan 2.7.1 option selected. i've had same issue myself , able solve - @ivoronline commented - manually adding saxon he9 standard xslt processor. see: https://stackoverflow.com/a/7737731/1955204 after have downloaded saxon can set eclipse standard processor at: run runtime configurations select xsl configuration on left open "processor" tab "change preferences" "add" new processor enter name , select type saxon 2.0 use "add workspace jars" or "add external jars" , route downloaded jar file check newly added, hit ok , run

Flask-Security user_registered Signal Not Received in Python 3.3, but works in 2.7 -

i'm trying use user_registered signal in order set default roles users when register using flask-security in following link: setting default role in flask security in searches can see there bug addressed in flask-security: not getting signal flask-security , fix - user_registered signal problem i've tried following prove if signal received handler without luck: @user_registered.connect_via(app) def user_registered_sighandler(sender, **extra): print("print-user_registered_sighandler:", extra) this, however, never gets called though user gets registered , signal should sent. if helps i've set flask-security configuration follows: app.config['security_registerable'] = true app.config['security_confirmable'] = false app.config['security_send_register_email'] = false app.config['security_changeable'] = true app.config['security_send_password_change_email'] = false signals flask-login , flask-principal worki...

delphi - Create XML element without namespace -

i want create element outputpath text. want: <propertygroup condition=" '$(configuration)' == 'debug' "> <outputpath>text</outputpath> </propertygroup> and get: <propertygroup condition=" '$(configuration)' == 'debug' "> <outputpath xmlns="">text</outputpath> </propertygroup> everything when create element keeps adding xmlns="" it. and error: error msb4097: element beneath element may not have custom xml namespace. // load project (.innoproj or .nsisproj file) xmldoc := nil; currentconfigurationnode := nil; xmldoc := createoleobject('microsoft.xmldom') ixmldomdocument2; xmldoc.async := false; //xmldoc.setproperty('selectionnamespaces', 'xmlns="http://schemas.microsoft.com/developer/msbuild/2003"'); << line nothing xmldoc.load(projpath); if xmldoc.parseerror.erro...

optimization - Should Python import statements always be at the top of a module? -

pep 08 states: imports put @ top of file, after module comments , docstrings, , before module globals , constants. however if class/method/function importing used in rare cases, surely more efficient import when needed? isn't this: class someclass(object): def not_often_called(self) datetime import datetime self.datetime = datetime.now() more efficient this? from datetime import datetime class someclass(object): def not_often_called(self) self.datetime = datetime.now() module importing quite fast, not instant. means that: putting imports @ top of module fine, because it's trivial cost that's paid once. putting imports within function cause calls function take longer. so if care efficiency, put imports @ top. move them function if profiling shows (you did profile see best improve performance, right??) the best reasons i've seen perform lazy imports are: optional library support. if code has m...

c++ - Portable way of linking libgfortran with CMAKE -

one of executables requires libgfortran.so . typically i'd add -lgfortran switch compile line , links automatically g++ . however, i'm trying find library cmake using: find_library(gfortran_library names gfortran) target_link_libraries(ncorr_test ${gfortran_library}) however, fails find library. turns out way has worked far if include entire library name so: find_library(gfortran_library names libgfortran.so.3) target_link_libraries(ncorr_test ${gfortran_library}) then, link properly: /usr/bin/c++ ... /usr/lib/x86_64-linux-gnu/libgfortran.so.3 ... however, including whole .so.3 not portable. know of better way this? typically libraries need use installed in /usr/local/lib , searching library name without "lib" , extension works (i.e. find_library(fftw_library names fftw3) find libfftw3.a in /usr/local/lib fine). edit: find_library(gfortran_library names libgfortran.so) not work either. libgfortran.so.3 has worked far. using locate libgfo...

android - Listview won't update from realm -

after create or receive message send message save realm. afterwards need update threads listview on threads page , bring newest messages top. have thread list shows updated preview , updated date, stays in it's inital listview position. tried requery realm info , reorder lastupdated time, doesn't seem work. need wipe old thread list repopulate update? i have update triggered on onresume() @override protected void onresume() { super.onresume(); updatelistview = true; updatelist(); } here's update @uithread public void updatelist() { try { if (updatelistview) { thread_realm = realm.getinstance(this); results = thread_realm.where(ziplistmodel.class).findallsorted("zipupdated", realmresults.sort_order_descending); adapter = new ziplistadapter(this, results); threadslistview.setadapter(adapter); adapter.notifydatasetchanged(); if (results.size()==0){ ...