Posts

Showing posts from March, 2011

Elasticsearch: score by distance and return distance without computing distance twice -

i googled extensively , found score distance need use script_score , return distance need use script_fields , unable find solution combined 2 queries or shared data between them. computing distance twice. how can avoid computing distance twice , instead compute once?

html - Disabling printer default margin with css (with chrome)? -

Image
with adobe indesign it's possible result: i tried same result css <style type="text/css" media="print"> @page { size: auto; /* auto initial value */ margin: 0mm; /* affects margin in printer settings */ } body { background-color:#ffffff; border: solid 1px black ; margin: 0px; /* affects margin on content before sending printer */ } </style> but it's impossible set margins 0. have margin on 4 sides: i'm using google chrome tests. tried: same thing, little white margins on 4 sides...what's wrong? any appreciate. jsfiddle : https://jsfiddle.net/l63dc1yd/ i think can solve problem css3 media query . @media print { html,body { margin: 0; } }

gulp - What is the <%= syntax in the Angular2-Seed project? -

i see bunch of <% , <%= in angular2-seed project, it? angular2 thing, or gulp thing, or else? it gulp template plugin. see: https://www.npmjs.com/package/gulp-template and in angular2-seed project can see being invoked in: tools/tasks/seed/build.index.dev.ts the following extract file: export = () => { return gulp.src(join(app_src, 'index.html')) .pipe(inject('shims')) .pipe(inject('libs')) .pipe(inject()) .pipe(plugins.template(templatelocals())) <-- here .pipe(gulp.dest(app_dest)); };

python - Populate a ManyToManyField -

my models.py class ingredient(models.model): name = models.charfield(max_length=16, unique=true) price = models.smallintegerfield() def __str__(self): return self.name class topping(models.model): name = models.charfield(max_length=32) ingredient = models.foreignkey(ingredient, related_name='indole', blank=true, null=true, default='base') def __str__(self): return self.nome class pizza(models.model): nome = models.charfield(max_length=32, unique=true) toppings = models.manytomanyfield(topping) def __str__(self): return self.nome in admin work! can add topping, pizza, etc. want use script populate. my script : import os os.environ.setdefault('django_settings_module', 'recipt.settings') import django django.setup() core.models import * def populate(): cheap = add_ingredient('cheap', 3) base = add_ingredient('base', 5) = add_ingredient('good...

google apps script - Cell with no text link when copy and pasting -

i think bug google sheets, if copy , paste table ones on page: http://castlecrashers.wikia.com/wiki/weapons spreadsheet instead of image being displayed there link no text in cell. according documentation there should text. if edit link (right click "edit link") nothing shows up. haven't been able access link in script via getforumlar1c1(), getdisplayvalue() or other range function. i submitted via report problem in sheets, wondering if missing , should able in script. this isn't necessary since can follow above steps test on own, here link sheet copied values to see issue: https://docs.google.com/spreadsheets/d/1rvuxzgovnc0caaok3oyrajoeuaggluqtlztmo-rmpxc/edit?usp=sharing and here test code: function getimageformula(url) { return '=image(\"' + url + '\")'; } function imageselected() { //spreadsheetapp.getactivesheet().setactiveselection("a3:a5"); var range = spreadsheetapp.getactivesheet().getactiverange(); va...

c++ - How to set an input directory for doxygen? -

i have directory in source , header files saved. run doxygen generate documentation these source code. however, not want change in directory (in particular cannot add sub directories in doxygen documentation saved). how can achieve need? using doxygen first time. so, detailed instructions appreciated. i think need following. create , go 'documentation' directory. in directory execute doxygen -g create template configuration file named "doxyfile". then, think, need modify doxyfile indicate source code not in current directory. way, output automatically (by default) saved in directory in doxygen executed? i found answer already. procedure follows: execute doxygen -g . doxyfile generated. open doxyfile , find input = after 'input =' put name of directory source code located. execute in command line doxygen doxyfile . the output put directory doxygen executed.

html - Bootstrap CSS row change in height causes jumping & usability trouble for everything below -

with bootstrap seems challenging deal variable height rows while remaining responsive in css. in case variable number of articles load carousel in sets of 4 or less depending on available in database. this causes content below jump around articles row height changes. if use relative positioning, or set height div, may cause css flow error on different screen sizes. example on phones when carousel loads single column of 4, rather 2 columns of 2, height required increase. need sort of min-height in media query css append file, however, couldn't min-height click on div of bootstrap carousel. <!-- articles --> <div id="articles" class="padding-bottom padding-top-two"> <div class="container"> <div class="row"> <!-- articles. --> <div class="col-lg-12"> <div class="section-title"> <h1...

How to insert a legend in grid.hexagons from hexbin in R -

how insert legend in example below? library("grid") library("hexbin") set.seed(506) x <- rnorm(10000) y <- rnorm(10000) z <- rnorm(100) w <- rnorm(100) xmin = min(x, z) xmax = max(x, z) ymin = min(y, w) ymax = max(y, w) df <- data.frame(x, y) bin <- hexbin(df, xbins=30, xbnds= c(xmin, xmax) , ybnds= c(ymin, ymax)) graphic <- hboxplot(bin, xbnds= c(xmin, xmax) , ybnds= c(ymin, ymax)) pushhexport(graphic) grid.hexagons(bin, border = gray(.7)) grid.points(z, w, pch=20, gp=gpar(col="blue")) #z , w others data vectors plot points on de grid.hexagons. upviewport() i tried grid.hexlegend not worked me, maybe did not done right. i appreciate help.

javascript - d3.js creating two elements per data point -

i'm wanting add rect element behind each bar, i'm struggling because d3.js isn't allowing me add element each data point. http://jsfiddle.net/g5hpwf0m/2/ var w = parseint(d3.select(self).style("width")), h = parseint(d3.select(self).style("height")), svg = d3.select(self) .append("svg") .attr("width", w) .attr("height", h), yscale = d3.scale.linear() .domain([0, d3.max(dataset)]) .range([0,h]); svg.selectall("rect") .data(dataset) .enter() .append("rect") .attr("fill", "green") .attr("x", function(d, i) { return * (w / dataset.length); }) .attr("y", function(d) { return h - yscale(d); }) .attr("width", w / dataset.length - barpadding) .attr("height", function(...

php - How to get start date of child time frame within parent time frame -

i know exact date of beginning of month need know when first week of month begins , week can start outside of month. i can - find weekday when "month" starts , subtract number of days beginning of "week" : $weekday = d('w', $monthstarttimestamp); $weekstart = $monthstarttimestamp - strtotime('1 day', 0) * (7 - $weekday); question : is there way make calculation more generic time frames not know in advance? possible use cases : given "datetime" datetime of first "year" given "datetime" datetime of first "month" given "datetime" datetime of first "week" given "datetime" datetime of first "day" given "datetime" datetime of first "hour" given "datetime" datetime of first "minute" for date time 2016-01-10 10:30 results : year : 2016-01-01 00:00 month : 2016-01-01 00:00 week : 2016-01-04 00:00 day : 2016-0...

Most effective way to check sub-string exists in comma-separated string in SQL Server -

Image
i have comma-separated list column available has values product1, product2, product3 i need search whether given product name exists in column. i used sql , working fine. select * productslist productname '%product1%' this query working slowly. there more efficient way can search product name in comma-separated list improve performance of query? please note have search comma separated list before performing other select statements. user defined functions comma separation of string create function [dbo].[breakstringintorows] (@commadelimitedstring varchar(max)) returns @result table (column1 varchar(max)) begin declare @intlocation int while (charindex(',', @commadelimitedstring, 0) > 0) begin set @intlocation = charindex(',', @commadelimitedstring, 0) insert @result (column1) --ltrim , rtrim ensure blank spaces removed select rt...

sed - Copy lines from multiple files in subfolders into one file -

i'm very new programming , trying learn how make tedious analysis tasks little faster. have master folder (master) 50 experiment folders , within each experiment folder set of folders holding text files. want extract 2 lines 1 of text fiels (experiment title on line 7, slope on line 104) , copy them new single file. so far, have learned how extract lines , add new file. sed -n '7p; 104 p' reco.txt >> results.txt how can extract these 2 lines files 'reco.txt' in subfolder of folder 'master' , export single text file? as explanation can bear great me learn. you can use find in combination xargs this. on own, can list of relevant files: find . -name reco.txt -print this finds files named reco.txt in current directory ( . ) or subdirectories , writes them standard output. now, can use -exec argument find , run program each file found, except typically multiple results combined single execution (appended command line). par...

Conways Game of Life trouble [java] -

public static boolean[][] calculate(boolean cellstate[][])//imports cell patern(in form of graph) { int x = 0, y = 0; int alive = 0; boolean newcellstate[][] = new boolean[50][50];//what next generation stored in while(x < 50 && y < 50)//calculation loop { try//each adjacent cell { if(cellstate[x-1][y] == true) alive++; //if adjacent cell alive alive variable gets + 1 }catch(indexoutofboundsexception e) {} try { if (cellstate[x-1][y-1] == true) alive++; } catch(indexoutofboundsexception e) { } try { if(cellstate[x-1][y+1] == true) alive++; } catch(indexoutofboundsexception e) { } try { if (cellstate[x][y+1] == true) alive++; } catch(indexoutofboundsexception e) { } try { if (cellstate[x][y-1] == true) ...

php - Kartik/Krajee Select2 not disabled -

Image
setting select to 'disabled' not disable element. user can still click on text of select2 , options box opens up. here disabled control opened clicking on text , not down-arrow button. here code: <?= $form->field($model, 'billing_currency_id')->widget(select2::classname(), [ 'data' => billingcurrency::listidcodes('','',true), 'disabled' => true, 'options' => ['disabled' => true,], 'pluginoptions'=>[ 'allowclear'=>false, 'dropdownautowidth'=>true, 'disabled' => true, ], ]); ?> clicking on down-arrow button keeps control closed, clicking on text area of control opens options box. update found own mistake - see answer below. i made mistake - have custom js code on site opens select2 when gets focus. code causing reported problem. custom code created overcome limitation of select2 whereby not automatically open when user...

c++ - Why can I return reference to local struct variable in VS2015? -

this question has answer here: can local variable's memory accessed outside scope? 20 answers my code follows: #include "stdio.h" #include "string.h" struct abc { char name[20]; int n; }; struct abc& myfun(void) { struct abc x ={ "lining",99 }; return x; } int main(void) { struct abc y = myfun(); printf("%s %d\n", y.name, y.n); return 0; } here called myfun() , returns reference local struct abc variable. should wrong because after myfun() returns, memory used no longer serve. code runs in vs2015 , print correct information "lining 99". why can outcome? the destructor pod type struct abc no-op. it's wrong you're doing, happens work because destruction doesn't anything; data lost when it's overridden due stack growing on it, memory same data s...

scala - How to configure akka send/receive buffer size and maximum frame size -

i have problem defining akka configuration maximum frame size , send/receive buffer size. how these related ? there rule of thumb these configs? i set akka settings: maximum-frame-size = 5242880b receive-buffer-size = 20971520b send-buffer-size = 20971520b any suggestion? thanks these settings have relevance if use akka-remote. these settings control underlying tcp implementation: tcp buffers allocate (this hint os, of cases os decide on own anyway) , largest remote payload accepted (maximum-frame-size). messages larger limit in serialized form rejected , not sent. avoid abusing remoting layer bulk data transfer primary purpose being control layer. bulk data transfer side-channel recommended: akka.io (actor based tcp) or akka.stream (stream based tcp) or http service via spray or akka.http.

javascript - How to compare between two or more buttons in js? -

i have 2 buttons in html code. want call 1 js function (no jquery) each buttons. the function have conditions. want know how compare between button clicked user. example : if (button 1 clicked) { block } else { block } the other way make 1 function per button don't want this. thank much. as mentioned in comment, add parameter this know button clicked getting id. function myfunction(elem) { document.getelementbyid("demo").innerhtml = "id:" + elem.id; } <button id='1' onclick="myfunction(this)">button 1</button> <button id='2' onclick="myfunction(this)">button 2</button> <p id="demo"></p>

javascript - Error myFunction(...).then is not a function -

i have following module performs request google: // my-module.js var request = require('request'); var bpromise = require('bluebird'); module.exports = get; function get() { return bpromise.promisify(dorequest); } function dorequest(callback) { request.get({ uri: "http://google.com", }, function (err, res, body) { if (!err && res.statuscode == 200) { callback(null, body); } else { callback(err, null); } }); } and want use module so: //use-module.js var mymodule = require('./my-module'); mymodule().then(function (body) { console.log(body); }); the error i'm facing following: mymodule(...).then not function. what doing wrong? bpromise.promisify(dorequest) not call dorequest , returns "promisified" version of function. should once, not @ each call. should work: module.exports = bpromise.promisify(dorequest);

c - Function without any return type -

i know there 2 types of functions: void , ones return (int, double, etc). if function declared without return statements? considered void function? example, myfunction(int value){ ....... } a function declared without return type considered returning int . ancient rule going original k&r c, left in language backward compatibility. integer promotions , conversion of float arguments double s done functions without prior definition or forward declaration same reason - backward compatibility old code. it needless relying on these rules new development bad practice. 1 should declare return type explicitly, , forward-declare or define functions before calling them.

sql server - Sum only one instance -

what want query count of hoursbilled . want first check #worked if data not exist in table want pull data #workschedule . my issue seems totalling data twice, i.e. if exists in both tables counts hoursbilled twice. works fine on test data, when roll out production data issue occurs. incorrect join, or bad query set-up? need can accurate count of hoursbilled ? essentially query trying is: if date exists in table #worked use hoursbilled table if date not exist use hoursbilled #workschedule create table #workschedule ( caldate date ,isworkday varchar(5) ,hoursbilled int ) insert #workschedule values ('01/01/2000', 'yes','3'), ('01/02/2000', 'yes','3'), ('01/03/2000', 'yes','1'), ('01/04/2000', 'no','0'), ('01/05/2000', 'yes','12'), ('01/06/2000', 'no','0') create table #worked ( d1 date ,hoursbilled int ...

node.js - Generate objectID client side to be save into db -

like blog system, each post can have media files. retain ux, want user upload images of post , save post. but need id name files /filename.jpg, how can generate id using mongodb on client side won't clash id generated on server (nodejs) also.

python - Connecting and Executing mongodb commands remotely through pymongo -

below python code connects remotely mongodb host , executes mongodb command "db.serverstatus().connections". expected output below script : { "current" : 43, "available" : 51157, "totalcreated" : numberlong(3988) } but i'm not getting output..... python code: import pymongo host = 'mongo_server.com' port = 27018 db_name='test' user='user' passwrd='password' def get_connection(): con=pymongo.connection(host,port) db=con[db_name] try: db.authenticate(user,passwrd) print db.command("serverstatus")["connections"] except: return none return db get_connection() mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostn[:portn]]][/[database][?options]] mongodb:// required prefix identify string in standard connection format. username:password@ optional. if given, driver attempt login database after connecting ...

url rewriting - OSCLASS region based listing like category page -

using osclass open source listing website. i want listing category page region see http://99business.co.uk/hotels.html its listing based on category. display listing within category. i want display listing within region like http://99business.co.uk/wiltshire-r742134 always give me error page instead of listing page region. so want page can display listing in url. not sure may rewrite rule issue. its working when disabled rewrite rule. http://99business.co.uk/index.php?page=search&sregion=wiltshire if it's working without permalinks, should check permalinks rules in admin panel under settings > permalinks, 'show rules'. having default configuration here's examples of urls: http://osclass.dev/for-sale/ http://osclass.dev/search/region,texas http://osclass.dev/search/city,dallas http://osclass.dev/search/region,texas/city,dallas http://osclass.dev/search/category,for-sale/region,texas/city,dallas most of customizable. ...

How to add Remote Event Receivers to SharePoint List through REST -

adding event receivers al list through rest: msdn has page rest calls add event receivers. https://msdn.microsoft.com/en-us/library/office/jj245049.aspx . post http://<sitecollection>/<site>/_api/web/lists(listid)/eventreceivers what bearer token needs attach ? got oauth token permission sharepoint online, still not able events if attach event receivers above post call. please point me, token needs attach event receivers, , how token. please add http/error exception app rise here. otherwise none able give answer. regarding office365 oauth have 2 steps. first app asks token_id , receive one, second phase access_token token_id received first call. access_token can use sharepoint services if app have necessary permissions. more details here: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks i haven worked rest remote receivers, might alternative task https://github.com/officedev/pnp/tree/master/samples/core.eventrec...

Export Biztalk Dynamic Send Port Handler Name -

when export binding dynamic send port no handler name shown in binding file. there alternate method that. one suggestion stephen f march use powershell script set these. from how configure send handler biztalk 2013 dynamic send port on deployment? param ( [string] $biztalkdbserver = ".", [string] $biztalkdbname = "biztalkmgmtdb", [string] $filehostinstance = "sendinghost", [string] $sendportname = "sm_dynamic_sp_test" ) [system.reflection.assembly]::loadwithpartialname("microsoft.biztalk.explorerom") | out-null $catalog = new-object microsoft.biztalk.explorerom.btscatalogexplorer $catalog.connectionstring = "server=$biztalkdbserver;database=$biztalkdbname;integrated security=sspi" foreach($sp in $catalog.sendports) { if($sp.name -eq $sendportname) { "found send port $($sp.name), analyzing send handler" foreach($sh in $sp.dynamicsendhandlers) { if($sh.sendhandler.transporttype....

combobox - MS Access 2007: Filtering selection list for a combo box -

background: record source form query ("bigquery") combines several related tables. setting combo boxes edit fields; control source these combo boxes field bigquery. 1 of fields unittype, , unitsubtype. there 100 distinct entries unitsubtype, many of them make no contextual sense when paired particular unittype: if unittype="car", unitsubtype="18 wheeler" makes no sense, , i'd not give client opportunity make mistakes. question, part a: when user chooses value unittype on form, limit combo box unitsubtype unitsubtype values paired unittype values in database. how done? example: if 1 or more instances of record containing unittype="truck" , "unitsubtype="18 wheeler" exist in table, assuming user has selected "truck" in combo box unittype 1 of choices presented in combo box unitsubtype should "18 wheeler". question, part b: user able add new unitsubtype typing combo box: if user has select...

Two or more Google maps (API v2) in tabs in Android -

does know if it's possible use (and how) mapviews (google maps api v2) on 2 or more tabs in tabhost? following (quite long) text describes problem 2 or more maps on tabhost , findings this. maybe knows better (cleaner) solution. please if can. or confirm findings. i have application tabhost , tabs need display map. there activities (and fragments) run in each tab. need display maps using mapview, call mapview's oncreate(), onresume(), ... on appropriate methods of parent activities (fragments resp.). when switch between tabs (activities) first map works. maps on other tabs display first tab map, until remove first tab map parent view group. i built own test app based on google maps api v2 demo package , have 4 map demos can run either list or in tabs. when run test 1 after each other list, works expected, there oncreate(), onresume(), onpause() , ondestroy() called on mapview , internal gms, opengl or whatever resources released , reinitialized (i suppose). each act...

.htaccess - How to redirect specific folder from HTTP to HTTPS -

i struggling redirect e-shop located in folder called shop . have 2 htaccess files, 1 on domain root (the 1 dedicated corporate website) , other 1 placed in shop folder. i've tried many variations of rewrite rule, can't make work... if put shop's htaccess file redirect loop error: rewriteengine on rewritecond %{https} off rewriterule (.*) https://%{http_host}%{request_uri} this doesn't in both htaccess files: rewriteengine on rewritecondition %{server_port} !^443$ rewriterule ^(.*)$ https://www.maindomain.com/order/$1 [r=301,l] neither when put htaccess file located on document root: rewriteengine on rewritecond %{https} !=on rewriterule ^(subdirectory/.*)$ https://www.mydomain.com/$1 [r=301,l] note: if makes difference, have redirect rule well. located in htaccess on document root: rewritebase / rewritecond %{request_uri} ^system.* rewriterule ^(.*)$ /index.php?/$1 [l] rewritecond %{http_host} !^rumako.cz$ [nc] rewriterule ^(.*)$ http://rumako.cz/$...

java - Mergesort implementation not correct -

i have been trying write basic top down mergesort, array not sorted after code has finished executing. have tried debugging recursion makes tough pinpoint. have tried comparing code other examples of mergesort, i've had no luck finding differences private void mergesort(int[] arr) { int[] aux = new int[arr.length]; sort(arr, aux, 0, arr.length - 1); } private void sort(int[] arr, int[] aux, int lo, int hi) { if(hi <= lo) return; int mid = lo + ((hi - lo) / 2); sort(arr, aux, lo, mid); sort(arr, aux, mid + 1, hi); merge(arr, aux, lo, mid, hi); } private void merge(int[] arr, int[] aux, int lo, int mid, int hi) { for(int = lo;i <= hi;i++) aux[i] = arr[i]; int x = lo; int y = mid + 1; for(int = lo; <= hi; i++){ if(x > mid) arr[i] = aux[y++]; else if(y > hi) arr[i] = aux[x++]; ...

laravel 4 - Unable to create the "app/uploads/nameof the folder/1578/3" directory Lravel4 on Digital Ocean server -

i code throwing error unable create "app/uploads/rescom summit bangalore 2016/1578/3" directory if (input::file($key)->isvalid()) { $destinationpath = 'app/uploads/'.$event.'/'.$userid.'/3'; // upload path $extension = input::file($key)->getclientoriginalextension(); // getting image extension $name = input::file($key)->getclientoriginalname(); $curfilesize = input::file($key)->getclientsize(); $mime =input::file($key)->getmimetype(); // dd($mime); //$filename = $name; // renameing image //$exstfilesize = input::file($destinationpath, $filename); if (!file::exists($destinationpath."/boq-".$name)){ //creating details saving inthe file_handler table $file...

javascript - how to find text cut off while resizing td element -

Image
i have resize option in table. when resize, cuts off text. how find size @ text begins cut off.. when resize header happens the easiest way multiply length of string point size times 1.25. should give how wide areas should title , not text goes slots. so strlen(text)*fontpointsize*1.25 also - yo yo has said - need specify width of field. so: <td width='123px'>title</td>

Getting Middle of string in php -

i have string this ameerpet,|jeans corner: 040-50607090@05:45pm/6 want substring after @ , before / . tried following echo substr($str,strpos($str,'@')+1,strpos($str,'/')) but whole string after @ output 05:45pm/6 try this, echo substr($str, strpos($str,'@')+1, strpos($str,'/') - strpos($str,'@') - 1); the third parameter not < position > , < length > refer : http://php.net/manual/en/function.substr.php

uitableview - how to rotate image in expandable cell when clicked on cell in ios? -

Image
i'm making uitableview expandable/collapsable cells ios app.in want display when user click on cell image down , when click on again image this,it possible! here code -(void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { if (selectedindex == indexpath.row) { selectedindex = -1; [mycontesttableview reloadrowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationfade]; return; } if (selectedindex != -1) { nsindexpath *prevpath = [nsindexpath indexpathforrow:selectedindex insection:0]; selectedindex = indexpath.row; [mycontesttableview reloadrowsatindexpaths:[nsarray arraywithobject:prevpath] withrowanimation:uitableviewrowanimationfade]; } selectedindex = indexpath.row; [mycontesttableview reloadrowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationfade]; } in image name "rotataeimage" please me. here expandable cell defau...

connection pooling - Maven Dependencies in web application and java application -

i trying connection pooling on remote server(not database server) using jndi, tomcat, maven , etc. in details, have 2 maven projects 1)web application 2)java application in non maven project , try access methods of java application web application. here pom of 2 projects: pom java application <dependencies> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupid>commons-pool</groupid> <artifactid>commons-pool</artifactid> <version>1.6</version> </dependency> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>1.2.13</version> </dependency> </dependencies> pom webapp <dependencies> <depend...

gulp-git. Clone remote repo from bitbucket -

i want clone repo bitbucket using gulp. gulp task: gulp.task('clonesub', function () { git.clone('https://username@bitbucket.org/xxxxx/xxxxx.git', {cwd: './gitrepo/'}, function (err) { if(err) { throw err; } })}); result: [11:49:25] starting 'clonesub'... [11:49:37] finished 'clonesub' after 12 s and further, nothing happens in /gitrepo created empty folder name of project project in bitbucket private. i can not clone private repository in way? need send password in https query https://username:password@bitbucket.org/xxxxx/xxxxx.git

jquery - Call a javascript function on tab /browser close not on reload -

i have issue . trying clear cookie value on tab close. , have created function clears value on page reload . tried solution stack-overflow question function getcookie(name) { var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function setcookie(cname, cvalue, exdays) { var d = new date(); d.settime(d.gettime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toutcstring(); document.cookie = cname + "=" + cvalue + "; " + expires+"; path=/"; } function unloadpage() { var check=getcookie('mycookie') if(check) setcookie('mycookie','','-2'); } $(document).ready(function() { window.onbeforeunload = unloadpage; }); function working problem it clearing cookie on page reload . want clear cookie if user close window. thanks. ...

gulp - Disable aurelia-bundler just on dev machine? -

i've been working on aurelia app without gulp , has gone well. want use gulp b/c page loads terrible 100+ separate files being requested. install aurelia-bundler skeleton , can working using gulp. there 2 problems: 1. have gulp bundle after every change refresh page 2. error messages make no sense b/c minified now. i can deal #1 b/c of gulp-watch (even though still takes time), can't handle minified files , not being able debug code. so, there , easy way switch non-bundled files development on machine , use bundled files when deploy heroku server? seems aurelia-bundle points dist folder default. oh yeah, tried modifying config.js point "src" instead of "dist" still looks aurelia-xxx.js file instead of non-bundled files. thanks. if using latest build files can gulp watch in dev should use src files without bundling - of course, slower, in conjunction browser-sync shouldn't have loads of refreshes. check paths.js , other config fi...

Rails 4 + BootStrap 4 button issue -

hello have quick question can't bootstrap 4 button work in rails button code <%= link_to 'lifehacks', controller: 'hacks', class: 'btn btn-primary' %> i thought work ends being apart of url instead " http://localhost/hacks?class=btn+btn-primary " without enclosing braces, ruby treat last 2 parts of method parameters single hash when in actual fact should two. wrapping route parameters in braces resolve issue: <%= link_to 'lifehacks', {controller: 'hacks'}, class: 'btn btn-primary' %> from documentation, can see how these defined: link_to(name = nil, options = nil, html_options = nil, &block) without explicit wrapping, both controller , class options being passed options rather class element being passed html_options .

php - PHPUnit and Domain Exception Testing -

i have given myself challenge making use of testing code develop figured not practice end developer helps 1 lot in building scalable , extendable code in long run. i have class defines array of supported doctrine drivers. inside class there method creates instance of annotation driver supported bundle. protected $supportedannotationdrivers = array( 'doctrine\orm\mapping\driver\xmldriver', 'doctrine\orm\mapping\driver\yamldriver', 'doctrine\orm\mapping\driver\annotationdriver' ); the method creates instance of these drivers can seen below: public function getannotationdriver($classdriver, $entitydriver) { if(!in_array($classdriver, $this->supportedannotationdrivers)){ throw new \runtimeexception(sprintf( "%s not supported annotation driver.", $classdriver )); } if('doctrine\orm\mapping\driver\annotationdriver' === $classdriver){ $annotationdriver = new...

html - Inline style vs "inline style" . What is the difference? -

this question has answer here: what's difference between html width / height attribute , css width / height property on img element? 7 answers differences between assigning attribute, style, , class in div 3 answers what difference between height="50" vs style="height:50px" ? and height="50" vs style="height:50" ? i confused this. presentation-related attributes such height="50" original way specify presentation details of html elements. however, have since been deprecated in favour of css, via style , class , id attributes, give lot more flexibility original attributes (at least because css can extended without touching definition of html itself, of course because "cascading" part, multiple un...

Node.js request to xml document not receiving properly encoded format? -

i not entirely sure why, receiving data looks n�f����s� call rss feed formatted in xml. exports.search = function(req, res) { request.get('https://secret.co/usearch/'+req.params.id+'/?rss=1', function (error, response, body) { console.log(body); if (!error && response.statuscode == 200) { parsestring(body, function (err, result) { res.json(result); }); } }); }; just on particular url, wondering how can solve , proper xml? the url in question delivers content gzip encoded. adding option gzip : true request call fix problem: exports.search = function(req, res) { request({ method : 'get', url: 'https://kat.cr/usearch/scarface/?rss=1', gzip: true }, function(error, response, body) { console.log(body); if (!error && response.statuscode == 200) { parsestring(body, function (err, result) { res.json(re...

Re-execute SQL Server job in case of failure -

currently creating sql server job. requirement whenever job fails, needs run 1 more time. possible in sql server? i'm not sure if best way it, can configure every single step of job re-run specific number of times after specific number of minutes (in case of network troubles, example). open step configuration in sql server management studio , set "retry attempts" , "retry interval (minutes)" according preferences. of course, not work if want re-run whole job beginning , not retry infinitely.

c# - Better way to write if-else block -

i have following code (sample code) works well. think if there other better way can write following code snippet more accurately less code. if(language == "english") { if(student_id == 0) { somefunction(); } else { if(getmarks(student_id) > 50 || subjectcount > 1 || projectcount > 0) { somefunction(); } } } also, please note if student_id 0 , getmarks(student_id) throws error (for more complex scenario, check out this ) what suggest case is: to write less nested if-else block one way inverting conditions and gives early return whenever possible to combine conditions same actions (in case being somefunction ) to exploit short circuit evaluation implemented in c# (also implemented in many other programming languages - noted martheen in comment). if(language != "english") return; //assuming nothing below if(student_id == 0 || getmarks(student_id) ...

wordpress - Why does a redirectPermanent after a Last RewriteRule works? -

with .htaccess file: # begin wordpress <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewriterule ^index\.php$ - [l] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . /index.php [l] </ifmodule> # end wordpress redirectpermanent /test/ /test2/ this url http://www.example.com/test/ should first pass through wordpress dispatcher's rewriterule , stop @ . /index.php [l] because of [l] . so why redirectpermanent condition after working ? when enter previous url i'm redirected http://www.example.com/test2/ . how apache handle kind of redirection ? based on @hjpotter92 comment. the [l] flag affects rules set mod_rewrite . redirectpermanent depends on mod_alias therefore not affected [l] flags put on mod_rewrite rules. [l] flag documentation redirectpermanent documentation

javascript - HTML - Jquery. Search for duplicates value in custom attribute -

i have html page has custom attributes. want make sure custom attributes in code have unique values. (like check duplicate id's instead of checking property name, check property value unique). below have posted actual code id's, not know how attributes. i need make sure custom attributes value unique ids. /* check dobbelt id */ checkid: function(){ $j('[id]').each(function(){ var ids = $j('[id="'+this.id+'"]'); if(ids.length>1 && ids[0]==this){ alert('multiple ids #'+this.id); } }); }, /* check dobbelt value in attribute. */ checkparameter: function(parmname) { $j("'["+parmname+"]'").each(function(){ var parmattr = $j(this).attr(parmname); if(parmattr.length > 1 && paramattr[0] ){ alert($j(this).id + "dublicates:" + parmattr); } }); } to check duplicate cust...

Rails 4 : Table Boolean Column Update Using "link_to "with a specific value "TRUE" always -

in customer controller update method code bellow: def update @customer= customer.find(params[:id]) if @customer.update_attributes(customer_params) redirect_to customers_path else render 'edit' end end in view in customers index page planning add "link_to" link, if clicked, particular customers field "doc_delete" should updated value "true". <td><%= link_to "[update", *************what here ?******** method: :put %></td> you can pass hidden params through button_to : <%= button_to "update", user, method: :put, params: { doc_delete: true } %> this create micro-form, marwen alluded to. whilst quite inefficient, best way send data update action. -- another, more efficient, way define custom route/action: #config/routes.rb resources :customers patch :doc_delete, on: :member #-> url.com/users/:id/doc_delete end #app/controllers/customers_con...

jQuery Sliders Moving at the same time - out of sync by one step -

i have following code:- jquery jquery('.slider').each(function() { var $el = jquery(this); $el.slider({ range: "max", min: $el.data('min'), max: $el.data('max'), value: $el.data('value'), step: $el.data('step'), slide: function(event, ui) { var percent = (100 / (jquery(this).data('max') - jquery(this).data('min'))) * jquery(this).slider('value'); jquery('.slider').not(this).each(function() { jquery(this).slider( 'value', ((jquery(this).data('max') - jquery(this).data('min')) / 100) * percent ); }); jquery('.slider').each(function() { var thistarget = jquery(this).data('target'); var thisvalue = jquery(this).slider('option','value'); ...

Python: Extract time from a file path -

i find general way extract time in format %h-%m-%s different file path follow: u'c:/users/pivo/work/data/pink_exp_2015_12031329\\2015-12-03_15-58-29_trdata.txt' u'c:/users/pivo/work/data/black_try\\2015-12-03_14-41-00_trdata.txt' i can use split , point time, 2 cases works follow looking general solution date_str = path1.split('_')[2] date_str = path2.split('_')[4] what's best way that? thank you import re reg = r'\d+\-\d+\-\d+' data='c:/users/pivo/work/data/black_try\\2015-12-03_14-41-00_trdata.txt' a=re.findall(reg, data) print(a[1]) you need try doing regex patterns find absolutely want. here python regex tutorial: http://www.tutorialspoint.com/python/python_reg_expressions.htm

Is it possible to deserialize a Shape in C# using Json.NET -

edited is possible deserialize c# object shape attribute? i have touch object, inherits circle object, inherits obstacle object shape attribute. i serialize touch object json : touch touch = new touch(0.15, 0, 4.05); touch.shape.stroke = brushes.black; string json = jsonconvert.serializeobject(touch); i deserialize object, using json, : touch test = jsonconvert.deserializeobject<touch>(json); but access violation line of code. i think comes shape attribute in obstacle object, declarated : protected shape shape; [jsonproperty(propertyname = "shape")] public shape shape { { return shape; } set { this.shape = value; } } is there way fix problem? i found way serialization. deleted shape json serialization using [jsonignore] , , create method. need 2 lines instead of 1 create object serialization: touch test = jsonconverter.deserialize<touch...

java - Is it possible, with E4, to programmatically change the active workspace? -

i want implement "switch workspace" feature of e3 , wonder if there preferred way it. first guess update eclipse.ini file contains default workspace , restart resourceplugin bundle. seems bit hard. it not possible of today e4 sdk.

Jquery get length of json array -

i've issue json array row length... i want extract correct length of data-row json (in case "2")... if try count length value "1". why ? how can correct length ? { "data-row": { "data1": [{ "firstname": "john", "lastname": "doe" }, { "firstname": "anna", "lastname": "smith" }, { "firstname": "peter", "lastname": "jones" }], "data2": [{ "firstname": "john", "lastname": "doe" }, { "firstname": "anna", "lastname": "smith" }] } } you have object , find length of object var json = { "data-row": { "data1": [], ...