Posts

Showing posts from January, 2015

.htaccess: Transfer name to index.php if not directory public -

i have piece of code: options followsymlinks <ifmodule mod_rewrite.c> rewriteengine on rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewritecond %{request_filename} !-l rewriterule ^(.*)$ index.php?url=$1 [l] </ifmodule> <ifmodule !mod_rewrite.c> errordocument 404 /index.php </ifmodule> i don't know how allow directory name "public" inside folder .htaccess, other names dir should transfered index.php. how that? add rewritecond exclude public directory rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewritecond %{request_filename} !-l rewritecond %{request_uri} ^/public(/.*)?$ rewriterule ^(.*)$ index.php?url=$1 [l] now, redirection work /public directories only. if want url have rest of path that's below public url=subfolder/page.php /public/subfolder/page.php use rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewrit

Removing non-English text from Corpus in R using tm() -

i using tm() , wordcloud() basic data-mining in r, running difficulties because there non-english characters in dataset (even though i've tried filter out other languages based on background variables. let's of lines in txt file (saved utf-8 in textwrangler) this: special satisfação happy sad potential für i read txt file r: words <- corpus(dirsource("~/temp", encoding = "utf-8"),readercontrol = list(language = "lat")) this yields warning message: warning message: in readlines(y, encoding = x$encoding) : incomplete final line found on '/temp/file.txt' but since it's warning, not error, continue push forward. words <- tm_map(words, stripwhitespace) words <- tm_map(words, tolower) this yields error: error in fun(x[[1l]], ...) : invalid input 'satisfa��o' in 'utf8towcs' i'm open finding ways filter out non-english characters either in textwrangler or r; whatever expedient. help!

asp.net - Passing data between two applications via third application -

i have asp.net application containing 2 pages add/edit customer , customer list(view). there 1 more host asp.net application uses ajax tab container/accordian host above 2 pages in iframes. shown below tab1 contains edit customer page in iframe 1 , tab2 contains view customers page(only 1 can active @ time). if have move tab2 tab1 (e.g. user clicks on edit link in customer list), have refresh host application passing name of tab in querystring(this part handled host app , available way switch tab). what best way pass data tab2 tab1 other query string? don't want change host app url appending querystring hard reset querystring without reloading. application in webfarm , has ip session affinity based load balancer. use in proc session fails obvious. there proven ways handle scenario in webfarm if remove out-proc sessions out of question? ---------------------------------------------------------------- asp.net main app content virdir-b [parent] **_______________________

primes - Need a hint/advice as to how to factor very large numbers in JavaScript -

my task produce array containing prime numbers 12-digit number. i tried emulate sieve of eratosthenes first making function enumerate produces array containing every integer 2 num : var enumerate = function(num) { array = []; (var = 2; <= num; i++) { array.push(i); } return array; }; then made function leaveonlyprimes loops through , removes multiples of every array member 1/2 max array (this not end being every integer because array become smaller every iteration): var leaveonlyprimes = function(max,array) { (var = 0; array[i] <= max/2; i++) { (function(mult,array) { (var = mult*2; <= array[array.length-1]; += mult) { var index = array.indexof(i); if (index !== -1) { array.splice(index,1); } } })(array[i],array); } }; this works fine numbers 50000, higher , browser seems freeze up. is there version of approach made

javascript - Series Data for column high chart -

Image
i working on highchart column chart. got stuck in series adding part. code function renderchart(series_data){ $("#container").height(400); var chart = new highcharts.chart({ chart: { type: 'column', renderto: 'container', marginbottom: 105 }, title: { text: 'issue sales', }, xaxis: { type: 'datetime', datetimelabelformats: { month: '%e. %b', year: '%b' }, mintickinterval: 24 * 3600 * 1000, labels: { rotation: -45, align: 'right', style: { fontsize: '13px', fontfamily: 'verdana, sans-serif' } } }, yaxis: {

Create variable BASH command -

i try customize little bash script special proprose. i'm confuse bash scripting when come time assigne command variable. my broken code: if [ -n "$2" ] top=`| head -n $2` fi awk '{print $17, ">", $19;}' $logs_folder$i | sort -g | uniq -c | sort -r -g $top so default return line if user specified number, add head command use array form instead: if [ -n "$2" ] top=(head -n "$2") else top=(cat) fi awk '{print $17, ">", $19;}' "$logs_folder$i" | sort -g | uniq -c | sort -r -g | "${top[@]}" and try add more quotes (""). actually can't save pipe variable , let bash parse normal way when it's expanded can replace command instead (cat). you use eval it's pretty delicate: if [ -n "$2" ] top="| head -n \"\$2\"" fi eval "awk '{print $17, \">\", \$19;}' \"\$logs_folder\$i\&q

java - Getting results of a search - lucene 4.4.0 -

i'm experiencing problems on lucene. i'm querying database. far know indexes ok (i checked lukeall-4.4.0). query constructed following: q = query.split(" "); booleanquery = new booleanquery(); //query[] queryy = new query[5 + 5 * q.length]; query[] queryy = new query[3 + 3*q.length]; //using text queryy[0] = new termquery(new term("designacao", query)); queryy[1] = new termquery(new term("descricao", query)); queryy[2] = new termquery(new term("tag", query)); //using separeted values (int = 3, j = 0; j < q.length; i++, j++) { queryy[i] = new termquery(new term("designacao", q[j])); queryy[++i] = new termquery(new term("descricao", q[j])); queryy[++i] = new termquery(new term("tag&quo

c++ - Curiously Recurring Template Pattern and statics in the base class -

so this answer i'm looking @ implementing problem crtp. have problem. in static base class have 2 sets of functions. 1 takes std::vectors , 1 takes standard c-style array. in base class define static function calls non-std::vector function. however when derive base class seem no longer able access public static function in base class (which thought could). template< class derived > class base { public: static void func( std::vector< float >& buffer ) { func( &buffer.front(), buffer.size() ); } static void func( float* pbuffer, int size ) { derived::func( pbuffer, size ); } }; i define derived class follows: class derived : public base< derived > { public: static void func( float* pbuffer, int size ) { // stuff } }; however when try call static function in base class: derived::func( stlvec ); from derived class throws compilation error: error c2665: 'main' : none o

xml - datagridview view hidden columns -

i convert xml dataset. looking @ relations see relations created _id, etc. want view these added columns when connect dataset datagridview assist in filtering data. wondering if knows if possible , how achieve. if need display hierarchical view on winform - datagridview not right choice - not support hierarchy. you need other controls. infragistics grid 1 of choices, there're multiple other ones well.

python - Generate all possible permutations of subsets containing all the element of a set -

let s(w) set of words. want generate possible n-combination of subsets s union of subsets equal s(w). so have set (a, b, c, d, e) , wan't 3-combinations: ((a, b, c), (d), (e)) ((a, b), (c, d), (e)) ((a), (b, c, d), (e)) ((a), (b, c), (d, e)) etc ... for each combination have 3 set , union of set original set. no empty set, no missing element. there must way using itertools.combination + collection.counter can't start somewhere... can ? luke edit: need capture possible combination, including: ((a, e), (b, d) (c)) etc ... something this? from itertools import combinations, permutations t = ('a', 'b', 'c', 'd', 'e') slicer = [x x in combinations(range(1, len(t)), 2)] result = [(x[0:i], x[i:j], x[j:]) i, j in slicer x in permutations(t, len(t))] general solution, n , tuple length: from itertools import combinations, permutations t = ("a", "b", "c") n = 2 slicer = [x x in

reporting services - Can SSRS read a file on a unix server? -

i have data file on unix server. defining datasource possible link ssrs server file on unix server. certainly, if willing install samba on said server , configure network share windows machines can see it. http://en.wikipedia.org/wiki/samba_(software) no doubt there other means of doing this, pretty standard , use.

java - ANDROID SQLITE: How to retrieve primary key of a certain row -

this question has answer here: what's best way last inserted id using sqlite java? 2 answers pretty simple question, still did not find answer around internet: finished creating new row , inserted database, want save newly created primary key of row. how access it? stands, trying use rest of column's values find row, getting sqliteexception : bind or column index out of range. here code current function trying keyid: public string getprimarykey(string gametitle, string gametype, string calories, string hours, string minutes) { cursor cursor = db.query(table_name, null, null,new string[]{gametitle, gametype,calories, hours, minutes},null, null,null,null); if(cursor.getcount()<1) { cursor.close(); return "????"; } cursor.movetofirst(); string keyid = cursor.getstri

iOS JSON serialization empty array serialized as nil instead of [ ] -

i attempting send json rails backend. when serializing payload (nsdictionary), empty array encoding nil instead of [ ] (empty array). is json encoding empty nsarray [] not supported on ios? i have tried changing 'options' within datawithjsonobject: no success. sending along @"[]" regular ol' nsstring not work. here code: nsdata* jsondata = [nsjsonserialization datawithjsonobject:payload options:nsjsonreadingmutableleaves error:&error]; [request setvalue:@"application/json" forhttpheaderfield:@"content-type"]; [request sethttpbody:jsondata]; afjsonrequestoperation *authrequest = [afjsonrequestoperation jsonrequestoperationwithrequest:request success:successblock failure:failblock]; [authrequest start]; thanks help! i suspect problem coming rails , not ios, there issue related security hole in rails since 3.2.11 https://github.com/rails/rails/issues/8832 https://github.com/rails/strong_parameters/issues/82 for

python - django social auth , create user model with email as primary key -

i trying integrate django social auth website have facebook , google login. trying customize user model make email primary key. advice ? tried creating usermodel ended errors. tried creating pipeline enter code here from social_auth.backends.pipeline.user import create_user def custom_create_user(request, *args, **kwargs): print kwargs return create_user(request, args, kwargs) my aim have site facebook , google - oauth2 login email primary key ! well doing facebook login ios app. doing is login facebook app , facebook access token send facebook email , access token django backend then is, instead of using django default authenticate method takes username , password authenticate user, overwrite own authenticate method. doing easy read django custom authentication in custom authentication class verify email-token pair sent front using fb sdk python , it. after can login user using django in built login

jQuery - attach event to dynamic element -

i have read through .on documentation, there bug in it here html: <a href="#" class="add-new">make new row</a> <ul> <li class="opts" > <select class="change" href="#" data-row="1"> <option>a</option> <option>b</option> <option>c</option> </select> </li> </ul> here javascript: var index = 2; $('.add-new').on('click',function(e) { e.preventdefault(); $('.opts:first').clone(true).insertafter('.opts:last'); $('.opts:last select').attr("data-row", index); index++; }); $(document).on('click', '.change', function(e) { e.preventdefault(); console.log($(this).data('row')); }); if dynamically generate rows, new elements work .on event. if first element changed , mo

winapi - In win32 C++ programming to close a window, should I call DestroyWindow(hWnd) myself or SendMessage(WM_CLOSE, hWnd, 0, 0)? -

i'm handling esc key in application , when key received wish close current window. should call destroywindow(hwnd) or should sendmessage(wm_close, hwnd, 0, 0) , or should closing current window in different way? you should postmessage(hwnd, wm_close, 0, 0) . puts wm_close message window's message queue processing, , window can close message queue cleared. you should use postmessage instead of sendmessage . difference postmessage puts message message queue , returns; sendmessage waits response window, , don't need in case of wm_close .

ruby on rails - "undefined local variable or method `n' for main:Object" when trying to run "rake db:populate" -

i'm going through michael hartl's tutorial , can't error: undefined local variable or method `n' main:object when run bundle exec rake db:populate sample_data.rake file namespace :db desc "fill database sample data" task populate: :environment name = faker::name.name email = "example-#{n+1}@railstutorial.org" password = "password" user.create!(name: name, email: email, password: password, password_confirmation: password) end end you have n inside interpolated string next email , not defined anywhere. remove or define it.

python - Exception signature -

what's signature class exception in python 2.x? i wish subclass , add arguments of own, while correctly invoking super . the following code works: class fooerror(exception): def __init__(self, msg, x): super(fooerror, self).__init__(msg) self.x = x but, there documentation or reference? pydoc exception not helpful. neither documentation: this or this . what have there fine. alternately, class fooerror(exception): def __init__(self, msg, x): exception.__init__(self,msg) self.x = x as docs : an overriding method in derived class may in fact want extend rather replace base class method of same name. there simple way call base class method directly: call baseclassname.methodname(self, arguments). useful clients well. (note works if base class accessible baseclassname in global scope.)

node.js - Socket.io 'on' is returning undefined -

ok, i'm trying learn socket.io , error: io.socket.on('connection', function (socket) typeerror: cannot call method 'on' of undefined heres code: var express = require('express') , app = express.createserver() , routes = require('./routes') , user = require('./routes/user') , path = require('path') , io = require('socket.io').listen(app); // environments app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyparser()); app.use(express.methodoverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.listen(3000); app.get('/', routes.index); app.get('/users', user.list); io.socket.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('m

titanium - iOS app run on selected devices -

i have created ios app , want app run on selected ios devices such ipad 3 , 4 , iphone 3,4,4s , 5. how can specify in titanium ? you can configure tiapp.xml set minimum version ios , minimum device processor. this: <ios> <min-ios-ver>4.3</min-ios-ver> <plist> <dict> <key>uirequireddevicecapabilities</key> <array> <string>armv7</string> <string>armv7s</string> </array> </dict> </plist> </ios> and here list of devices use each processor armv6 = iphone 2g/3g, ipod 1g/2g armv7 = iphone 3gs, iphone 4, iphone 4s, ipod 3g/4g/5g, ipad, ipad 2, ipad 3, ipad mini armv7s = iphone 5, ipad 4

character encoding - Fix newlines when writing UTF-8 to Text file in python -

i'm @ wits end on one. need write chinese characters text file. following method works newlines stripped resulting file 1 super long string. i tried inserting every known unicode line break know of , nothing. appreciated. here snippet: import codecs file_object = codecs.open( 'textfile.txt', "w", "utf-8" ) xmlraw = (data written text file ) newxml = xmlraw.split('\n') n in newxml: file_object.write(n+(u'2424'))# \u2424 unicode line break if use python 2, use u"\n" append newline, , encode internal unicode format utf when write file: file_object.write((n+u"\n").encode("utf")) ensure n of type unicode inside loop.

Carry form input data from one page, to a php form that emails the data, and again through to the php redirect page -

i have form on page (form.php) when submitted uses submit.php send data email address. submit.php redirects info.php. on info.php want include of data user entered form.php. user enter additional inputs on info.php , submit it. info.php use php page email me form inputs. form inputs include form.php , user input on info.php. wow, hope makes sense. summarize: form.php --> submit.php (hidden - emails me form data) --> info.php (carry inputs form.php here, user input additional data) --> emailed me again php page i not posting code it's long , think can imagine how looks. help: form.php - simple form inputs submit.php - data form.php post here, sends email info.php - simple form inputs thanks in advance! the easiest thing submit.php set session data $_session['name'] = array('myinput'=>$_post['myimput']); then after set: header('location: info.php'); in info.php <?php session_start()// forgot call @

f# - Why is using the base key word causing this error? -

i trying example programming f# o'railey, chris smith page 53. it working functions returning functions. this line straight book in vs2013 ide editor, fsi , linqpad4 giving error: code: let generatepoweroffunc base = (fun exponent -> base ** exponent) error: error fs0010: unexpected keyword 'base' in pattern what missing or there author did not include needs included. i suspect it's merely matter of base not being keyword when book written. try different identifier: let generatepoweroffunc b = (fun exponent -> b ** exponent) assuming you've got 2009 edition of programming f#, before f# 2.0 released (although after 1.0). i'm trying find out when introduced keyword... edit: actually, looking @ this version of spec written in 2009, looks base keyword @ point. wonder whether original code written before book published. either way, think it's reasonable treat error, , using valid identifier instead should fine. edit

PHP string cookie define -

i have string defined like: define('images_dir',"/portal/images/"); after place inside of cookie content becomes %2fportal%2fimages%2f i need string return like: /portal/images/ i'm kinda combining 2 answers mentioned here. 1st what described default behaviour, php automatically decode original value, don't need urldecode($_cookie['name']); 2nd you can prevent automatic url encoding using setrawcookie() docs note value portion of cookie automatically urlencoded when send cookie, , when received, automatically decoded , assigned variable same name cookie name. if don't want this, can use setrawcookie() instead if using php 5.

c++ - How to avoid the copy when I return -

i have function returns vector or set: set<int> foo() { set<int> bar; // create , massage bar return bar; } set<int> afoo = foo(); in case, create temporary memory space in function foo(), , assign afoo copying. want avoid copy, easy way can in c++11? think has rvalue thing. ok, update question: if going return object defined myself, not vector or set thing, mean should define move constructor? this: class value_to_return { value_to_return (value_to_return && other) { // how write here? think std::move supposed used? } } thanks!!! modem c++ compiler implement: given type t : if t has accessible copy or move constructor, compiler may choose elide copy. so-called (named) return value optimization (rvo) , specified before c++11 , supported compilers. otherwise, if t has move constructor , t moved( since c++11 ). otherwise, if t has copy constructor, t copied. otherwise, compile-time error emitted.

algorithm - dynamic programming proboem for minimum cost -

i have cell tower question. there n towns. want build cell tower in of towns. each cell tower can cover , neighbor. each town has cost build cell tower. want find out minimum cost build cell tower cover towns. for example, (1) town 1 2 3 cost 5 1 2 select build cell tower in town-2. cost 1. (2) town 1 2 3 4 cost 5 1 2 3 select build cell tower in town-2/3. cost 1+2=3. (3) town 1 2 3 4 cost 5 1 3 2 we select build cell tower in town-2/4. cost 1+2=3. it's dynamic programming algorithm. how can solve it? thanks ling i'd go among following lines: f(0,_) = 0 f(1,true) = 0 f(1,false) = cost[1] f(x,true) = min{ f(x-1,true) + cost[x], f(x-1,false) } f(x,false) = min { f(x-1,true) + cost[x], f(x-2,true) + cost[x-1]} the idea is: x current number of city looking at, , boolean true if city covered (by city left). f(0,_) empty base clause - free cover nothing. f(1,false) base city 1 not covered, must put tower there, , f(1,true) base cit

android - Is a listener destroyed when the view is scrolled off the screen? -

is listener, example textwatcher on edittext, destroyed or removed when view scrolled off screen. example, have listview there few edittexts in each listview item. when item scrolled onto screen necessary add new listener edittext? the listener attached edittext if edittext not destroyed neither listener attached it.

html - Why is Google indexing management not applicable to the live version? -

i have task prevent google's crawler indexing content. have read, if have kind of html: <!--googleoff: index--> <!--googleon: index--> then googleoff tells google's crawler not index content, while googleon tells google's crawler index content. far, good. so, content should not indexed google's crawler should between comments. have wrapped content should excluded google's indexing comments, using googleoff , googleon feature , content excluded google's indexing correctly wrapped inside comments locally , on staging repo. however, not see comments containing googleoff , googleon instructions in html of live version. cause of this? why google indexing instructions available in repos except live version? think might issue settings, not sure right , not sure should source of problem? it problem server settings, has been solved. after while (when reindexing complete) undesired content should filtered out google indexing.

android - LongClick not working on an empty gridview -

is possible handle longclick on empty gridview or on empty place of gridview? tried use code shown below: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); gridview gridview = (gridview) findviewbyid(r.id.gridview1); gridview.setonlongclicklistener(new onlongclicklistener() { @override public boolean onlongclick(view v) { toast.maketext(mainactivity.this, "does works?", toast.length_short).show(); return false; } }); } but, unfortunately, doesn't work. tell me, how can handle event on empty gridview? thanks i attach xml file: <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="-5dip" android:orientation="vertical" > <gridview android:i

crash - Android app crashes and returns to menu and then works -

i'm writing app info on ingress. first app i'm kinda new android. i have menu consist of 8 buttons. 1 of them opens activity has 2 imagebuttons. each imagebutton opens different activity has textview in it. my problem this. when first run app crashes if hit either of image buttons. returns menu. if go either imagebutton, works. i'm running app on gs4 running 4.2.2 debugging gave me error source not found. not sure whats wrong. the class 2 buttons public class factions extends activity implements view.onclicklistener { imagebutton resis, enligh; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_factions); setup(); } private void setup() { resis = (imagebutton) findviewbyid(r.id.ibresistance); resis.setonclicklistener(this); enligh = (imagebutton) findviewbyid(r.id.ibenlightened); enligh.setonclicklistener(this); } @override public boolean oncreateopt

php - Storing Auto-Incremented ID when using PDO for MySQL -

i'm using pdo mysql. i'm inserting table has id field set autoincrement. i'd store value reuse in next line. how can this? from php manual: returns id of last inserted row, or last value sequence object, depending on underlying driver. example, pdo_pgsql requires specify name of sequence object name parameter. return $db->lastinsertid('youridcolumn');

how do i change id of a element every time it is clicked with jquery -

how change id of element every time clicked jquery? have code works fine on first click, when clicked again, still calls old id. $("#like<? echo $msgid;?>").click(function(){ $.post("like.php?status_id=<? echo $msgid;?>", $(this).serialize()); settimeout(function() { $("#likediv<? echo $msgid;?>").load('like-count.php?status_id=<? echo $msgid;?>'); $("#like<? echo $msgid;?>").attr("id","unlike<? echo $msgid;?>").text("unlike"); },500); }); $("#unlike<? echo $msgid;?>").click(function(){ $.post("unlike.php?status_id=<? echo $msgid;?>", $(this).serialize()); settimeout(function() { $("#likediv<? echo $msgid;?>").load('like-count.php?status_id=<? echo $msgid;?>&

javascript - Zombie.js firing a visit callback before GET request completes -

i'm running issue using zombie.js access localhost url seems fire visit callback before "response" event returns. @ least, before "zombie: http://localhost/ => 200" message logged in debug mode. var browser = require('zombie'); browser.visit('http://localhost/', { debug: true }, function (err, browser) { if (err) throw err; console.log(browser.success, err); } ); when run this, following: zombie: opened window http://localhost/ zombie: event loop empty false undefined zombie: http:/localhost/ => 200 when run on live site, following: zombie: opened window http://mylivesite.com/ zombie: http:/mylivesite.com/ => 200 zombie: loaded document http://mylivesite.com/ zombie: event loop empty true undefined any reason why console.log(browser.success, err) runs before request when i'm running on localhost? maxwait set 10s, still no luck.

Access Raspberry Pi Camera from Node.js? -

is possible access raspberry pi camera node.js? how 1 go doing this? thanks! try node-raspicam " node.js-based controller module raspberry pi camera based on command structure similar johnny-five. implemented wrapper structuring command line process call using child_process.exec within node. "

javascript - Capturing consecutive non-alphanumeric characters in a string in a single group -

i want replace special characters in string dashes. use following regex replace characters. var x = "querty(&)keypad"; alert(x.replace(/[^a-za-z0-9]/g, "-")); however, causes each character replaced dash, rather replacing consecutive characters single dash. examples gives me output querty---keypad . desired output querty-keypad . you can see issue in jsfiddle . use + match 1 or more repetitions: > "querty(&)keypad".replace(/[^a-za-z0-9]+/g, "-") "querty-keypad"

c# - how to Convert label.text to linklabel -

i fetching filenames in label text: label1.text += filename+ environment.newline; i want convert these filenames hyperlinks(so when click on filename, file should open). how provide linklabel properties label ? try this: label1.text += "<a href="yourpath/"+ filename+ ">click this</a>"+environment.newline;

php - MYSQL count based off of two tables -

sorry asking this, haven't found answer i'm trying anywhere! basically, have database 2 tables. below or 2 examples i'll use: table 1: process id date ---------- ----------- 1 2008/08/21 2 2008/08/23 3 2008/08/21 table 2: process id qty ---------- --- 1 1 2 4 3 6 basically, in php select table 1, , find processes occur today (in example i'll 21st of august). want take process ids, , match them in table 2 , give count of quantities. the end result i'm trying figure out in example how output "7" using php select processes happened today in 1 table, add corresponding process quantities in table. select sum(t2.qty) table1 t1 join table2 t2 on t1.pid = t2.pid t1.date = '2008/08/21'

ruby - How can I override the Jekyll build command to set some config options only when building? -

i'm using jekyll asset pipeline build website , i'd compress website (which takes 20 seconds) when i'm publishing it. have enable these values programmatically in config file: asset_pipeline: bundle: false compress: false i've tried code plugin isn't working. me why? module jekyll module commands # overwrite here heavy work (like compressing html , stuff) # when building site, not when testing (which uses jekyll serve) class << build alias_method :_process, :process def process(options) require 'jekyll-press' options['asset_pipeline']['bundle'] = true options['asset_pipeline']['compress'] = true _process(options) end end end end you don't need special gem - can pass multiple configuration files jekyll build : first, regular config file, settings needed,

file upload - django 1.5 how to read csv from memory -

i trying find out how read uploaded csv without saving disk ... i'm stuck @ form.cleaned_data['file'].read ... don't seem output if can figure out how output, can write appropriate function deal lines of data. #addreport.html <form enctype="multipart/form-data" method="post" action="/products/addreport/"> {%csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="submit" /> #forms.py django import forms # class uploadfileform(forms.form): file = forms.filefield() -- # views.py def addreport(request): if request , request.method == "post": form = uploadfileform(request.post, request.files) if form.is_valid(): print form.cleaned_data['file'].read() else: print form.errors print request.files #form = uploadfileform() else: form = uploadfileform() return render_to_response('

ios - NSFetchResultController with UICollectionView issue with indexes/cells on update and delete action -

Image
first time i'm using uicollectionview, , i'm having difficulties. updating , deleting cells (will focus on delete here, came cause), data nsfetchresultcontroller . have made custom cell in in interface builder part of storyboard this: i have custom uicollectionviewcell subclass following properties: @property (strong, nonatomic) iboutlet uibutton *deletebutton; @property (strong, nonatomic) iboutlet uitextfield *textfield; @property (strong, nonatomic) iboutlet uiview *containerview; @property (strong, nonatomic) iboutlet uiview *textfieldcontainer; in ib have set cell class custom class, connected elements properties of custom class , set identifier cell . in collection view view controller set collection view , fetchresultcontroller , relevant methods this: - (nsinteger)numberofsectionsincollectionview:(uicollectionview *)collectionview { return [[self.fetchedresultscontroller sections] count]; } - (nsinteger)collectionview:(uicollectionview *)collection

c# - Building a YouTube-like Video Playing Site Using ASP.NET Techniques -

hi want create simple site allow users upload , view video. i'm using asp:literal:literal1 tool insert flash player after necessary coding realize user can find particular video url (eg "play.aspx?id=<%#eval("id") %>" , problem when user gets playing page shows no player how fix it?please me... it indicates can find url request cant display player my code: public partial class play : system.web.ui.page { public class operatemethod { public operatemethod() { } // ▲show flash player , can play video public static string getflashtext(string url) { url = "player.swf?filename=" + url; string str = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' width='452' height='360' id='index' name='index'><param name='allowscriptaccess' value='always' /><param name='movie&

Android: Download Manager resume issue -

i trying download file using android download manager . per docs: the download manager conduct download in background, taking care of http interactions , retrying downloads after failures or across connectivity changes , system reboots. but, download manager never resumes download, after network connection restored(at least, in case). tried setting request header, using addrequestheader() . nothing worked. code follows: request request = new request(uri.parse(base_url)); request.setallowednetworktypes(downloadmanager.request.network_wifi | downloadmanager.request.network_mobile); request.setallowedoverroaming(false); request.settitle("aarti sangrah.zip"); request.setdestinationinexternalpublicdir( environment.directory_downloads, "aarti sangrah.zip"); if (build.version.sdk_int >= build.version_codes.honeycomb) { request.setnotificationvisibility(request.visibility_visible_notify_completed); } e

sql - How can I increment the value for each INSERT INTO iteration? -

i have query shown below column1 int anothercolumn varchar(100) insert table1 (column1,column2) select (max(column1) table1)+1 ,anothercolumn table2 table1 before query column1 column2 ------- ------- 3 test1 4 test2 table1 after query column1 column2 ------- ------- 3 test1 4 test2 5 anotherval1 5 anotherval2 5 anotherval3 but want column1 column2 ------- ------- 3 test1 4 test2 5 anotherval1 6 anotherval2 7 anotherval3 how can achieve in sqlserver 2008 storedprocedure? assumed queries iterated , check condition each rows. seems aggregate function executes once! edit 1 please answer after completing select statement insert work. thats why didn't result expected??? correct? use row_number function give rows sequential numbers insert table1 (column1,column2) select (select max(column1) table1) + row_number() on (order t2.anothercolumn),

Reading and printing file contents using Perl -

can body me in reading files of particular format directory line line , should print on screen. and request include command lines in program itself. then when ever simple ran program , should display content of files. below program wrote can body me please.... #!/usr/local/bin/perl $filepath="/home/hclabv"; opendir(dir,"$filepath"); @files=grep{/\.out$/} readdir(dir); closedir(dir); $c = 0; ($c=0 ; while ($c <= @files) { $cmd = "perlsc11 $files[$c]"; system($cmd); if($#argv != 0) { print stderr "you must specify 1 argument.\n"; exit 4; } else { print ("$files[$c]\n"); # open file. open(infile, $argv[0]) or die "cannot open $argv[0]: $!.\n"; while(my $l = <infile>) { print $l; } close infile; } $c++; } you can use glob feature in perl list of filenames ".out" extension in specified directory. can open these files 1 one using loop , print contents screen. here's code, # file-nam

.htaccess - 301 redirect url with all url's that start with main url - Wordpress -

Image
we want make 301 redirect in htacces in our wordpress installation following situation. morning in our webmaster tools see 8000 new 404 pages not found. in image below have made printscreen. not know these url's come because not use url structure. can see in printscreen starts with: order/order.html?addid example: order/order.html?addid=1014&rand=920505296661072670 it looks old owner of url has this. want redirect starts order/order.html?addid homepage. @ moment see 8000 not found same url , different addid. is possible , if has best way redirect these url's? you should tell google not take account these url parameters. in webmaster tools , go exploration -> url parameters , declare addid , rand not change page rendering.

c# - Trying to select rows from different tables -

select distinct vtw.lastname, vtw.firstname, vtw.dob, vtw.clubnumber, vtw.tournamentname, vtw.bosstournamentid, vtw.tournamentdatetime, vtw.tournamentid, tp.tournamentprizeid, tp.status, tp.place, p.prizeid,p.prizename, tp.bredeemed, tp.couponnumber vwtournamentwinners vtw, tournamentprizes tp, prizes p vtw.fk_tournamentid=tp.fk_tournamentid , vtw.fk_playerid=tp.fk_winnerid , tp.fk_prizeid=p.prizeid , vtw.tournamentdatetime between '8/10/2013' , '8/10/2013' , tp.status='available' union select bossid, status, couponnumber, fk_prizeid, fk_winnerid, prizename, firstname, lastname, dob bountyprizes, prizes, players prizes.prizeid=bountyprizes.fk_prizeid , players.playerid=bountyprizes.fk_winnerid order vtw.tournamentdatetime desc error message: msg 205, level 16, state 1, line 1 queries combined using union, intersect or except operator must have equal number of expressions in target lists. note: both queries work individually. want gridview display

c - what is output ? gcc output is 0. please explain? -

this question has answer here: doubts in using switch statement in c 5 answers gcc compiler output 0. why? shouldn't 3? int main() { f(3); return 0; } int f(int t) { int c; switch(t) { case 2: c=2; case 3: c=3; case 4: c=4; case 5: c=5; default: c=0; } printf("%d",c); } because missing break; statement in each of cases. leads control falling through following case statements , default case.

iphone - How to fill plist with key-value data by Russian words? -

this question has answer here: unicode characters don't display in nslog output 1 answer i have nsdictionary this nsdictionary *result = [[nsdictionary alloc] initwithobjectsandkeys: @"usa.png", @"США", @"ec.png", @"ЕС", @"russia.png", @"Россия", @"brazil.png", @"Бразилия", ....... , more ...... nil]; and want values dictionary sending string key eventcountry xml parser. nsstring *countryimagestring = [self.countryset objectforkey:event.eventcountry]; if (countryimagestring.length == 0) { calcell.countryimageview.image = [uiimage imagenamed:@"unknown.png"];

sql - ActiveRecord polymorphic has_many with ActiveSupport::Concern -

i have following concern: module eventable extend activesupport::concern # ... included has_many :subscriptions, as: :entity, dependent: :destroy end end my models are: class experiment < activerecord::base include eventable end class subscription < activerecord::base belongs_to :entity, polymorphic: true end in controller try create subscription experiment, following: class subscriptionscontroller < applicationcontroller before_filter :find_entity def create subscription = subscriptions.new(params[:subscription]) @entity.subscriptions << subscription # why false? # ... end end but doesn't work. while debugging, noticed @entity.subscriptions.count create incorrect sql query: select count(*) [subscriptions] [subscriptions].[experiment_id] = 123 while expect: select count(*) [subscriptions] [subscriptions].[entity_id] = 123 , [subscriptions].[entity_type] = 'experiment' note: if following, works

java - Fail while installing dynamic web module2.5 -

i import java based, maven web project when trying change project facet in eclipse rightclick on project->properties->project facet getting fail while installing dynamic web module2.5 from command prompt go workspace/myproject , run following command mvn eclipse:eclipse -dwtpversion=2.0

vb.net - Visual Basic Not all code paths return a value -

in visual basic 2010, program compiles without problem. however, warning "not code paths return value" on function. since our assignment requirement must submit without error , warning need solve these error. part of sample code: dim integer = 0 dim currentchar string = frmmycompiler.textbox.text(i) function tonextword() = + 1 currentchar = frmmycompiler.textbox.text(i) end function my function did not have data type because no need return anything. can vb use void same c++ ?? know how overcome problem? use sub tonextword() return void, instead of function . here have documentation.

c# - Gridview binding not working -

i trying bind gridview control following code. getting error "data null. method or property cannot called on null values." error line " p.materialname = reader.getstring(reader.getordinal("materialname"));" have data in fields in materials table. wrong code? please me fix it. public static list<product> getmaterials() { sqlhelper objsqlhelper = new sqlhelper(); sqldatareader reader = objsqlhelper.executereader("getmaterials"); list<product> objmaterials = new list<product>(); product p = new product(); while (reader.read()) { p.materialid = reader.getint32(reader.getordinal("materialid")); p.materialname = reader.getstring(reader.getordinal("materialname")); p.desc = reader.getstring(reader.getordinal("desc")); p.materialprice = reader.getdecimal(reader.getordinal("materialprice")); p.datasheet = reader.getstring(reader.

javascript - Code Igniter add css -

although question on forum, i'd ask again. how attach css , js files in ci (code igniter framework) here code: views/header - <link href="<?php echo base_url(); ?>assets/css/example.css" rel="stylesheet" media="screen"> autoload.php - $autoload['helper'] = array('url'); but css doesn't work. help put assets folder applications, system, assets not in application , simple load url helper class in controller call header view part like $this->load->helper('url'); $this->load->view('header'); and use in header file.. because $this->base_url() return / folder.. <script src="<?php echo $this->base_url();?>/assets/javascript/jquery.js"></scirpt> changing folder structure because access within application folder core part know..

calling jsonresult in simple html site through jquery -

Image
can call mvc jsonresult in simple html project through jquery. mean can use mvc projects api , consume jsonresult method in html project. i want call above jsonresult in html page know have ti use jquery serialize data. not come. yes, possible load json result in simple html project through jquery or javascript using ajax inside js functions. use jquery.getjson() inside $(document).ready(function(){ }) loading json object while html page gets loaded intially. also refer http://api.jquery.com/jquery.getjson/