Posts

Showing posts from April, 2012

Django inspectdb miss POSTGRESQL materialized views -

all other tables correctly converted models both views , materialized views seems skipped. am missing or views , materialized views aren't managed ./manage.py inspectdb ? this not work since 1.8, on 1.7 worked mysql views. annoying.

c# - WPF Cannot see image in runtime -

i've created 3 images context menu. problem can not see them in runtime. (i can see them in editor window) i've already changed compile type resource and image type png (just in case) <color x:key="backgroundcolor" a="255" r="19" g="19" b="19"/> <bitmapimage x:key="bicut" urisource="images/cut.tif"/> <bitmapimage x:key="bicopy" urisource="images/copy.tif"/> <bitmapimage x:key="bipaste" urisource="images/paste.tif"/> <solidcolorbrush x:key="borderbrush" color="#ececec"/> <style targettype="contextmenu"> <setter property="foreground" value="{staticresource borderbrush}"/> <setter property="snapstodevicepixels" value="true" /> <setter property="overridesdefaultstyle" value="true" /> <setter prope

ASP.NET Identity - Re-authenticate on some areas -

i'm starting new project using asp.net identity 2.1. in app, use remember me feature, so, have question. how can force users re-authenticate when access pages (for ex, admin area) if authenticated «remember me» feature? for ex, admin forgets logout. few hours later, uses browser, , logged in our app remember me feature. there no problem me, if person can navigate our app being logged admin, don't want person access admin, or sensitive areas of app without being forced login again. does know how this, or if framework has similar ready use? thanks

matlab - Reducing image bit depth -

i'm working on 800 x 800 pixels images bit depth of 24 ( png format). assume means 3 x 8 bits. these images black , white (0 or 255). want reduce depth 8 bit because*, when process images in matlab,* create 800 x 800 x 3 matrix has bigger computational cost computing 2d matrix. my idea subset first layer of matrix in matlab seems i've lost information because i've nothing left in matrix. `im4=im4(1:800,1:800);` any idea ? i'm new image processing , may not know basics... rgb2gray safest way convert m-by-n-by-3 image m-by-n.

oracle - Ranking without an order by -

is there way create row_number "on fly" without ordering column? i've got query : select regexp_substr(',a-b,b-c,c-d', '[^,]+', 1, level) legs dual connect regexp_substr(',a-b,b-c,c-d', '[^,]+', 1, level) not null and need keep order of rotation, need rank sure rotation good. tried take near rank, dense_rank, row_number,... need order by, can't use. it give this rank | legs 1 | a-b 2 | b-c 3 | c-d you can use level , though need alias it: select level rnk, regexp_substr(',a-b,b-c,c-d', '[^,]+', 1, level) legs dual connect regexp_substr(',a-b,b-c,c-d', '[^,]+', 1, level) not null; rnk legs ---------- ------------ 1 a-b 2 b-c 3 c-d

Jain sip registration successful but the client is unreachable in asterisk -

i have issue related jain sip , asterisk. using jain sip registration asterisk , can receive valid response (200 ok) asterisk when register request sent out. problem facing when check sip accounts in asterisk server (version 11) account status unreachable see host , alc port. remains unreachable. the command using sip show peers update: register request using jain sip: register sip:634@10.0.0.***:5060 sip/2.0 call-id: 2a4edd77a04edcf91a183fb5e6390ed4@10.0.7.162 cseq: 1 register from: <sip:634@10.0.0.***:5060>;tag=1536045124 to: <sip:6034@10.0.0.***:5060> via: sip/2.0/udp 10.0.7.***:6060;branch=z9hg4bk-393136-32de53e08f3695b7a99325e95a230fa0 max-forwards: 70 contact: <sip:634@10.0.7.***:6060> content-length: 0 after authentication receive ok response: sip/2.0 200 ok via: sip/2.0/udp 10.0.7.***:6060;branch=z9hg4bk-393136-a334443342b349bd19bad069fd993a24;received=10.0.7.***;rport=6060 from: <sip:634@10.0.0.***:5060>;tag=1536045124 to: <sip:634@10.0

django - $http success function does not execute in Angular js -

i trying http response django local server returns json response. json response: [{"fields": {"dob": "2015-05-08", "image": "media/jainsubh_1394437734_6.png", "text_file": "my_txt_files/jn2i0oq.png", "usr_name": "ankitmishra", "email": "anbishamar@gmail.com"}, "model": "my_fr_app.new_user_reg", "pk": 15}] angular code is: <!doctype html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="myapp" ng-controller="customersctrl"> <ul> <li ng-repeat="x in items"> {{ x.usr_name }} </li> </ul> </div> <script> var app = angular.module('myapp', []); app.controller('customersctrl', ['$http',function($http) { $http.get("http:

javascript - How do you define node_modules as externs in Closure Compiler? -

i have node.js project want compile closure compiler. not want run in browser/use browserify. want utility of type checking. got compiler work correctly using following: java -jar compiler.jar -w verbose --language_in ecmascript5_strict --externs closure-externs.js --js="lib/**.js" where closure-externs.js manually defined variables , functions using node.js in rather crude way: // closure-externs.js /** @constructor */function buffer(something){} function require(path){} var process = {}; [...] it turns out worked through sheer luck. there no dependency tracking between files, can have cases return type {foo} , compiler complain doesn't exist (depending on machine, depending on compile order). found out doing wrong , should using --process_common_js_modules compiler dependency tracking require("foo") . invoking compiler so: java -jar compiler.jar -w verbose

regex to validate HTTP request string in C? -

i don't know regex know how it's useful. want validate http requests 1 in c. get /foo.html http/1.1 following things compulsory get "/" file extension (period in file path) http/1.1 only 2 spaces, 1 after , after filepath. i wrote code without regex, it's messy, uses strncmp, 2 loops , bools validate request. still can't figure out how verify http/1.1 though. here's code (note - "line" char array stores http request) // validate request-line if (strncmp(line, "get", 3) != 0) error(405); if (line[3] != ' ') error(400); if (line[4] != '/') error(501); // initializing variable future use bool period = false; int y = strlen(line); bool secondspace = false; // quotes not allowed (int z = 0; z < y; z++) { if (line[z] == '"') error(400); }

php - sum of 2 number with object and method -

this question has answer here: php: “notice: undefined variable”, “notice: undefined index”, , “notice: undefined offset” 23 answers why getting these errors? undefined variable: num1 cannot access empty property class sum{ public $num1=1; public function fun($num2){ return $this->$num1+$num2; } } $number = new sum(); echo $number->fun(3); class sum{ public $num1=1; public function fun($num2){ return $this->num1+$num2; //removed $^^ } } $number = new sum(); echo $number->fun(3);

c# - Office365 API OutlookServicesClient hangs when acquiring token -

i following example here: get started office 365 apis when controller action executes, hangs on following line inside of var "new outlookservicesclient" var authresult = await authcontext.acquiretokensilentasync( dcr.serviceresourceid, new clientcredential(this.configuration.idaclientid, this.configuration.idaclientsecret), new useridentifier(userobjectid, useridentifiertype.uniqueid)); i cannot figure out why hanging, especially, since acquiretokensilentasync works fine in discovery client right before call. any appreciated. my controller action method: [authorize] public async task<actionresult> index() { var contacts = new list<contactitem>(); var signinuserid = claimsprincipal.current.findfirst(claimtypes.nameidentifier).value; var userobjectid = claimsprincipal.current.findfirst(claimtypesadditions.objectidentifier).value; var authcontext = new authenticationcontext(this.configuration.idaauthority, new adaltoke

jodatime - Usage of joda.time in icCube -

i use following mdx statement: with member [x] now()->plusmonths(1)->withdayofmonth(1)->minusday(1) select [x] on 0 sales but error "withdayofmonth" unknown. know function "plustmonths()" works fine. how can make other joda function work? the following line active in iccube.xml. explicitely states add child packages if these required, not know if withdayofmonth child package , not know find that: <allowedpackage>org.joda.time</allowedpackage> unfortunately, now() creating internal date/time object not support yet joda methods (we'll add them in next release). in meantime, here several way compute end of month: with // aware server's end of month not client, if don't see problem you've been lucky...for time being. // using mdx functions ( function can added schema ) function ic3_eom() datetime( now().year() , now().month() +1, 1 )->plusdays(-1) // using joda datetime ( function can added schema ) f

r - Assign class to data frame after clustering -

Image
i used k-means cluster algorithm on data-frame df1 , result shown in picture below. library(ade4) df1 <- data.frame(x=runif(100), y=runif(100)) plot(df1) km <- kmeans(df1, centers=3) kmeansres<-factor(km$cluster) s.class(df1,fac=kmeansres, add.plot=true, col=rainbow(nlevels(kmeansres))) there possibility add data frame information cluster observation come from? you have information want: kmeansres<-factor(km$cluster) just add data frame additional column. df1$cluster <- km$cluster

ios - How to set a constraint using percentage? -

Image
just direct question, had spent many hours trying find working solution faild. in xcode, storyboard, how set constraint 1 view can located 30% of total window height top of superview? , need way supported ios devices of orientations. please see illustration attached. thank help!! update sorry, have misunderstood problem. you'll need add constraints code (the xconstraint totally arbitrary, must need define x, y positions, width , height, unambiguous layout): @iboutlet weak var imageview: uiimageview! override func viewdidlayoutsubviews() { super.viewdidlayoutsubviews() let yconstraint = nslayoutconstraint(item: imageview, attribute: .top, relatedby: .equal, toitem: view, attribute: .top, multiplier: 1, constant: view.bounds.height / 3) let xconstraint = nslayoutconstraint(item: imageview, attribute: .leading, relatedby: .equal, toitem: view, attribute: .leading, multiplier: 1, constant: 30) nslayoutconstraint.activate

python - Django TypeError 'User' object is not iterable -

is not possible iterate on user objects using user.objects.all()?? trying same no avail i have form; class addmemberform(form): user = forms.choicefield(choices=user.objects.all(), initial='choose user', ) and trying render through template. corresponding part of views.py below; class stationhome(view): def get(self, request, pk): station = station.objects.get(pk=pk) channels = channel.objects.filter(station=station) members = station.members.all() form1 = addmemberform() return render(request, "home_station.html", {"form1":form1, "station":station, "channels":channels, "members":members, }, ) finally corresponding part of corresponding template, <form method="post" actio

javascript - Can not download html with phantomjs -

i have 3 different files in project , layout is phantomjs -->phantomjs.js -->phantomjs.exe index.php index.php: $phantom_script = dirname(__file__). '\phantomjs\phantomjs.js'; $response = exec ('\phantomjs\phantomjs.exe' . $phantom_script); echo $response; phantomjs\phantomjs.js var webpage = require('webpage'); var page = webpage.create(); page.open('http://www.google.com', function(status) { console.log(page.content); phantom.exit(); }); your usage oh phantomjs correct according documentation. http://phantomjs.org/api/webpage/property/content.html php exec method returns last line only. maybe line white space. http://php.net/manual/fr/function.exec.php you shall have seond parameter &$output, sent reference. array containing entire output. a problem may face later, content need evaluated before try read s dom document content. using example innerhtml of html tag, ie: $('html').html(); if p

sql server - Convert Timestamp to image? -

i looking @ cast , convert specification on msdn ( https://msdn.microsoft.com/en-us/library/ms187928.aspx ), , sql server datatype conversion chart ( https://www.microsoft.com/en-us/download/details.aspx?id=35834 ) allows implicit conversion between timestamp , image. my question - result of (what image like?!), , uses there conversion? or image not think is? or image not think is? indeed. assume images pictures. not. from msdn image variable-length binary data 0 through 2^31-1 (2,147,483,647) bytes.

ios - Image in collection view sets with animation issue -

i'm setting image in uiimageview using sdwebimage in uicollectionview. scenario there expandable uilabel expand , collapse tapping on it. on tapping reloads particular cell. works problem when user puts app in background , takes in foreground , again tap in uilabel reloads cell , image gets set in animation glow affect in screen.below code i'm using in collectionviewcell method. [uiview transitionwithview:self.imgbackground duration:0.0f options:uiviewanimationoptiontransitionnone animations:^{ [self.imgbackground sd_setimagewithurl:[nsurl urlwithstring:[dictdata objectforkey:@"seasonimage"]]]; self.imgbackground.contentmode = uiviewcontentmodescaleaspectfill; self.imgbackground.clipstobounds = yes; } completion:^(bool finished){ }]; thanks in advance.

mysql - How to increase database performance if there is 0.1M traffic -

i developing site , i'm concerned performance. in current system there transactions adding 10,000 rows single table. doesn't matter took around 0.6 seconds insert. but worrying happens if there 100,000 concurrent users , 1000 of users want add 10,000 rows single table @ once. how impact performance compared single user? how can improve these transactions if there large amount of traffic in situation? when write speed mandatory, way tackle getting quicker hard drives. mentioned transactions, means need data durable (d of acid). requirement rules out myisam storage engine or type of nosql i'll focus answer towards goes on relational databases. the way works this: set number of input output operations per second or iops per hard drive. hard drives have metric called bandwith. metric interested in write speed . crude calculation here - number of mb per second divided number of iops = how data can squeeze per iops. for mechanical drives, magic iops numbe

c# - How does a singleton property with a lock ensure thread safety? -

i use singletons, in case it's appropriate. while trying investigate best implementation thereof came across bit of code has left me believing improperly understand how brackets encapsulate "scope." public sealed class singleton { private static singleton instance = null; private static readonly object padlock = new object(); singleton() { } public static singleton instance { { lock (padlock) { if (instance == null) { instance = new singleton(); } return instance; } } } } i'm confused happens when attempt access "instance." i'm working on logging singleton (my useful application singleton) , has method "writeline(string line)" when call: singleton.instance.writeline("hello!"); it maintains lock during execution of entire method of "writel

Should i go with vb.net or VBA? Mostly working with excel files -

i'm starting new job - first - financial controller. job mean working lot excel files, example formatting document can imported , understood other financial programs sap, or creating charts data in document. there might many specific tasks vb.net/vba can come useful @ it. my question is, should vb.net through visual studio or vba via excel? understanding can achieve same things both in terms of excel-files, perhaps vba quicker , easier learn , use. vb.net on other hand has better ide through visual studio , learning give me knowledge can more useful elsewhere. correct? instead of trying 1 of them find out after time should have gone other, hope right start. i use both vba , vb.net recommend learning both. learning vba easier learning vb.net because there less learn. find vba tutorials easier master because vb.net tutorials seem more concerned demonstrating amazing functionality of vb.net teaching basics of language. once have vba under belt learning curve vb.net

python - how to delete text to end of line with curses -

how how delete text end of line ? stdscr.addstr(5, 5, "egestas curabitur phasellus magnis") result screen: egestas curabitur phasellus magnis # ok stdscr.addstr(5, 5, "elit metus") result screen: elit metusrabitur phasellus magnis # problem to delete eol ( end of line ) use window.clrtoeol() : example: import curses window = curses.initscr() window.clrtoeol() window.refresh() i recommend use of great urwid console/tui programming however. update: bhargav rao right however; have call window.refresh() explicitly: accordingly, curses requires explicitly tell redraw windows, using refresh() method of window objects. in practice, doesn’t complicate programming curses much. programs go flurry of activity, , pause waiting keypress or other action on part of user. have sure screen has been redrawn before pausing wait user input, calling stdscr.refresh() or refresh() method of other relevant window.

MailChimp send email v3.0 -

the version 2.0 of mailchimp apis has campaign send api. don't find similar api on v3.0. find automation api in can start workflow, appears documentation workflows can't created using apis , can created using gui. requirement able send emails using mailchimp api. please advise. it's possible both create , send campaign through v3.0 api. see 'action' tab here you can send saved segment, far can tell, there's no way create saved segment via api.

sql - Slow Query - uses views -

backend on cloud using sql server express 2008 r2 frontend on access 2013 i had query had add subquery to restrict results. query took 1 second run before, takes 70+. think problem may using views in query not indexed. i'm pretty new , don't use access/sql much, apologies if missing obvious here. this query code: select distinct vusearch.paid ,vusearch.pdid ,concataddress(nz([building_name]), nz([building_no]), nz([street]), nz([indest]), nz([district]), nz([town]), nz([postcode])) address ,vusearch.deal_date ,vusearch.lease_end ,vusearch.break_date ,vusearch.review_date ,vusearch.propertytype ,vusearch.acting_for ,vusearch.landlord_seller ,vusearch.tenant_purchaser ,iif(isnull([vusearch.gia]), [vusearch.nia], [vusearch.gia]) mainarea ,vudesc.comments_incentives ,tlddealsearch.include ,vusearch.incomplete ( vusearch right join tlddealsearch on vusearch.pdid = tlddealsearch.pdid ) left join vudesc on tl

c++ - efficiently copy subimage from host to opengl pixel buffer object -

i moving data cpu host opengl memory , using pixel buffer object that. can copy whole image so: glbindbuffer(gl_pixel_unpack_buffer, buffer); glubyte * data = (glubyte *)glmapbuffer(gl_pixel_unpack_buffer, gl_read_write); // copying 4 channel 8 unsigned char data memcpy(data, cpu_data, rows * cols * 4); this quite fast. however, need copy rectangular subimage of data. so, in essence need multiple memcpy this, take performance hit have copy things line line. wondering if somehow there faster way perform operation.

ruby - Where is Person and not Person::Single -

lets have 3 classes person person::single < person person::married < person lets have two persons single => person::single then 2 persons when do: person.all.count => 2 but goal persons type person , not person::single or person::married what tried is: person.where(type: person.to_s) => 2 but returns 2 because person::single , person::married inherit person what can instead? there example way ::single , ::married have same methods person not same type? thanks since marked rails tag, assume person class activerecord model. there more information missing, assume don't know ;) your person class inherits activerecord methods, example "all", , person::single (and ::maried ) inherit through person. so, naturally, when person.all regular <#activerecord>.all method, not know , not care ::single , ::maried. what can dynamically setting default_scope , based on class name of calling .all, or .where or whatev

Jeet Gird - Can I use Fixed gutters? -

is there way can use fixed gutters jeet.gs? using sass version of grid. http://jeet.gs the current version of jeet not allow fixed gutters. if need use fixed gutters can check new lostgrid project created cory simmons (the author of jeet).

python - AttributeError: 'DataFrame' object has no attribute 'ravel' -

i trying test panda program works fine on other system. import pandas pd import numpy np pandas import series, dataframe ds1 = pd.read_table('data.txt', sep=' ', header=none) ds2 = pd.read_table('dataset.txt', header=none, sep=' ') out = ds1.copy() _,c = np.where(ds1.ravel()[:,none] == ds2[:,0]) newvals = ds2[c,1] # valid positions in output array changed valid = np.in1d(ds1.ravel(),ds2[:,0]) # make changes desired output out.ravel()[valid] = newvals print out when tried gives, _,c = np.where(ds1.ravel()[:,none] == ds2[:,0]) file "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 1947, in __getattr__ (type(self).__name__, name)) attributeerror: 'dataframe' object has no attribute 'ravel' update sample raw data: ds1 = pd.read_table('https://gist.githubusercontent.com/karimkhanp/9527bad750fbe75e072c/raw/ds1', sep=' ', header=none) ds2 = pd.read_table('https://gis

python - How can I round values in Pandas DataFrame containing mixed datatypes for further data comparison? -

i have dataframe df_left: idx1 idx2 idx3 idx4 valuetype value 0 a1 q 1983 q4 w 10.123 1 a1 q 1983 q4 x 2 a1 q 1983 q4 y f 3 a1 q 1983 q4 z nan 4 a1 q 1984 q1 w 110.456 ... created previous post: background information and dataframe df_right: idx1 idx2 idx3 idx4 valuetype value 0 a1 q 1983 q4 w 10 1 a1 q 1983 q4 x 2 a1 q 1983 q4 y f 3 a1 q 1983 q4 z nan 4 a1 q 1984 q1 w 110 i compare , reconcile data both values , text of following works: df_compare = pd.merge(df_left, df_right, how ='outer', on = ['idx1', 'idx2', 'idx3', 'idx4', 'valuetype']) df_compare.columns = ['idx1', 'idx2', 'idx3', 'idx4', 'valuetype', 'from', 'to'] df_compare = df_compare[df_compare.f

jquery - How to encode/decode UTF-8 in HTTP headers in Rails? -

i using "insert rails flash messages http headers show ajax response errors" pattern, this: controller: def flash_as_header return unless request.xhr? [:error, :warning, :notice].each |type| if flash[type] response.headers["x-ajax-#{type.to_s.humanize}"] = flash[type] end end end jquery: $(document).ajaxcomplete(function(response, status, xhr) { var types = ["error", "notice", "warning"]; (i = 0, l = types.length; < l; ++i) { msg = status.getresponseheader("x-ajax-" + types[i]); if(msg) { break; } } if(msg) { $('.flash-error').text(msg).removeclass('is-hidden'); } }); this works, running character encoding issues. flash messages contain utf-8 special characters, , destination html document utf-8. here sample string, should appear: användare this how in http response (correct: %c3%a4 ä): x-ajax-err

php - Prestashop 1.6.0.13 remove Header phone -

prestashop 1.6.0.13, how can remove header phone? in: /themes/default-bootstrap/modules/blockcontact/nav.tpl at end appear lines: {if $telnumber} <span class="shop-phone"> <i class="icon-phone"></i>{l s='call now:' mod='blockcontact'} <strong>{$telnumber}</strong> </span> {/if} and changed that: {* {if $telnumber} {l s='call now:' mod='blockcontact'} {$telnumber} {/if} *} but still appears head phone i tried removing lines , apperas header phone. i have made capture/photo of "inspect element" of header contact phone (and work time phone) appears in header , want remove: the photo https://www.dropbox.com/s/zcxktazzjzkzrxa/help.jpg?dl=0 i hope can me discover line in tpl file of prestashop remove this: 1) phone icon 2)the words "días laborales de 11h 13h" 3) phone number (34) 676.... i struggling several days same reason. you hav

python - import flask on wsgi virtual host fails -

having following directory structure , setup: . ├── app │   ├── __init__.py │   ├── __init__.pyc │   ├── static │   ├── templates │   │   ├── base.html │   │   └── index.html │   ├── views.py │   └── views.pyc ├── flask ├── myapp.wsgi ├── run.py ├── run.pyc └── tmp myapp.wsgi #!/usr/bin/python import sys, os, logging logging.basicconfig(stream=sys.stderr) #sys.path.insert(0,"/var/www/otherstuff/myapp/") sys.path.insert(0, os.path.dirname(__file__)) #from app import app app import app application application.secret_key = 'xyz' if __name__ == '__main__': app.run(host='0.0.0.0',debug=true) __init__.py from flask import flask app = flask(__name__) app import views vhost.conf <virtualhost *:80> servername local.myapp.com wsgiscriptalias / /var/www/otherstuff/myapp/myappwsgi <directory /var/www/otherstuff/myapp/app> order allow,deny allow </directory>

php - How to completely remove a namespace using DOMDocument -

given xml following, how can remove particular namespace, including declaration, each element? <?xml version="1.0" encoding="utf-8"?> <document xmlns:my-co="http://www.example.com/2015/co"> <my-namespace:first xmlns:my-namespace="http://www.example.com/2015/ns"> <element my-namespace:id="1"> </element> </my-namespace:first> <second> <my-namespace:element xmlns:my-namespace="http://www.example.com/2015/ns" my-co:id="2"> </my-namespace:element> </second> </document> notice there no xmlns:my-namespace declaration @ root level , 2 declarations in different parts , levels of xml structure. how can efficiently remove namespace my-namespace without having check each node in code? this xml should afterwards: <?xml version="1.0" encoding="utf-8"?> <document xmlns:my-co="http://www.example

java - How to use "iHarder" base 64 encoder on android -

this base64 class : http://iharder.sourceforge.net/current/java/base64/ the problem is, have 2 editext , 1 button in activity.so need use encode string edittext1 1 button , show result(encoded result) on edittext2 . how can , use class encode strings? i read details class , cannot figure out how can use encode (input - output string in android) how can ? cheers!. don't use third-party class in case - android has base64 class . just use base64.encodetostring(byte[], int) , base64.decode(string, int) . note base64-encoding binary data, if actual source text, you'll need work out encoding use first... e.g. utf-8. example: string sourcetext = ...; byte[] sourcebinary = sourcetext.getbyte(standardcharsets.utf_8); string base64 = base64.encode(sourcebinary, base64.default);

javascript - http request function won't return result -

i setting server express.js , want 'get' request '/' return results of function. function making request news api. when make call '/', function being triggered, , results ('stories') being logged in console, nothing being sent in response '/' 'get' request. have tried putting 'return' statement in few different places , still doesn't work... idea hugely appreciated! thanks! app.js var express = require('express'); var app = express(); var stories = require('./stories.js') app.get('/', function(req, res){ var returnedstories = stories.searchstories(); res.send(returnedstories); }) var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('going live on port', host, port); }); stories.js var request = require('request'); function searchstories(){ var stories = ''; request({

sql server - Find string length in sql without starting of zero -

this question has answer here: removing leading zeroes field in sql statement 10 answers i have problem, uploading employee code , account number excel(.csv) file, , check employee code , update or insert account number corresponding employee code. if employee code start "0" csv file not consider 0's , send remaining character, when check in sql not match table data (employee code). i have plan match them, don't know how do. i have tried below query declare @employeecodenet varchar(max)='mj300'; declare @employeecodedb varchar(max)='00mj300'; select ltrim(replace(@employeecodedb, '0', ''))--it should return 'mj300' if spaces not expected, close tried need: declare @employeecodedb varchar(max)='00mj300'; select replace(ltrim(replace(@employeecodedb, '0', ' ')),'

regex - How to validate LinkedIn public profile url regular expression in python -

i jus want validate linkedin public profile url. tried concept below = "https://in.linkedin.com/afadasdf" p = re.compile('(http(s?)://|[a-za-z0-9\-]+\.|[linkedin])[linkedin/~\-]+\.[a-za-z0-9/~\-_,&=\?\.;]+[^\.,\s<]') p.match(a) the above concept working fine. when give url https://www.linkedin.com means it's not working. can me validate both concepts. it oring between http(s) , www. has given above problem. change them * (i.e. 0 or more). import re = "https://www.linkedin.com/afadasdf" p = re.compile('((http(s?)://)*([a-za-z0-9\-])*\.|[linkedin])[linkedin/~\-]+\.[a-za-z0-9/~\-_,&=\?\.;]+[^\.,\s<]') print p.match(a) although might want restrict www rather numbers or letters? maybe: p = re.compile('((http(s?)://)*([www])*\.|[linkedin])[linkedin/~\-]+\.[a-za-z0-9/~\-_,&=\?\.;]+[^\.,\s<]')

php - Parse Date and Time from GET Parameter -

okay pass date , time script using get. right checks exact value database, contains spaces.i want convert 1 line e.g. 2015-03-04-03:03:34 i want verify string matches timestamp in sql table displays like: 2015-05-03 12:03:23 thanks you can use regex patter remove between date , time : $str = '2015-03-04-03:03:34'; $str = preg_replace('~(\d{4}-\d{2}-\d{2})(.+)(\d{2}:\d{2}:\d{2})~', '$1 $3', $str); echo $str; // 2015-03-04 03:03:34

javascript - Bind event to multiple jquery elements simultaneously -

i need bind same event (for example click ) n jquery elements. know can achieve result selector: $("#first, #second, .third").on("click", function(){}); but if, instead of selector, want use list of jquery elements? this solution i'm using right now, assume $first , $second result of function: var $first = $("#first"); var $second = $("#second"); $([$first[0], $second[0]]).on("click", function(){ alert("click " + this.innertext) }); find fiddle play here: https://jsfiddle.net/0z2r55d6/ as can see need extract, each jquery element, html element , push array. find pretty ugly , unhandy.. there better way achieve same result? didn't find in jquery's documentation. thanks using jquery add() method: $first.add($second).add($third).on('click', handler);

sbt - What does a bare line on its own do? -

in .sbt file, have copy-pasted lines readmes, of have no idea i'm doing. example is, after adding sbt-revolver plugins.sbt, writing line revolver.settings my current understanding of magically adding re-start , re-stop commands sbt. have been led understand line in .sbt file not, in fact, perform magic, rather creates key , associates value it. what keys such line set, , value? equivalent statement in .scala build definition? *.sbt files can take bare dslentry include setting[t] , seq[setting[t]] . an expression somestring := "a" or someseq += "b" setting specific t type. these settings values though, define transformation (change, add, append, etc) of different parts of build, folded build state , structure. in example revolver.settings seq[setting[_]] defines default setup of using sbt-revolver . if setting in project/*.scala need assign root project, either: the sole project in build the project aggregates other (s

angularjs - How to ng-checked checkbox in ng-repeat? -

i have list display user reputation census. sigle option radio button use code , work great when user answer , when return on same question check previous answer. <li ng-repeat="item in items"> <input name="myname" value="{{item.id}}" type="radio" ng-selected="mymodel==item.id" ng-model="mymodel"/>{{item.text}} </li> but multiple option i've use check box , don't know how write code mantain checked previous answer. use code doesn't work: <li ng-repeat="item in items"> <input name="myname" checklist-value="{{item.id}}" type="checkbox" ng-checked="mymodel==item.id" checklist-model="mymodel"/>{{item.text}} </li> any help, please? update now have model array multiple value inside (mymodel). following code i'm not able check correct items. <li ng-repeat="item in items"&g

html - Jquery doesn't link, why? -

<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="stylesheet.css"/> <script type="text/javascript" src="script.js"></script> </head> <body> <div id="red"></div> <div id="blue"></div> <div id="yellow"></div> <div id="green"></div> </body> </html> script.js $(document).ready(function() { $('div').mouseenter(function() { $(this).animate({ height: '+=10px' }); }); $('div').mouseleave(function() { $(this).animate({ height: '-=10px' }); }); $('div').click(function() { $(this).toggle(1000); }); }); add jquery framework html head tag, before own js use jquery: <head> &

c# - How do I draw a line between all the drawn points? -

in paint event did: list<point> drawpoints = getdrawpoints(); if (drawpoints.count > 1) { foreach (point p in drawpoints) { e.graphics.drawline(pen, p.x - 2, p.y - 2, 4, 4); } } but instead of drawing lines between subsequential points, it's drawing 2 lines same place each point. i want connect point single line. use drawlines , pass list array: if (drawpoints.count > 1) { e.graphics.drawlines(pen, drawpoints.toarray()); }

javascript - How to run a function by clicking an option in a drop down select tag? -

i have drop down select tag : <select id="thisdropdown" onchange="dosomething()"> <option></option> <option>classif</option> <option>status</option> </select> notice i'm using onchange(); what need ability re-click option in drop down runs function again (as can change other drop downs affect outcome of running function). i have tried onselect() , onclick() none seem work. have write bit of script ? have been looking online can't seem find work. thanks in advance, sorry if similar has been asked before we can achieve minor tweaks required based on browser jsfiddle link https://jsfiddle.net/0kxe6br7/2/ var dom = "select#thisdropdown"; var is_firefox = navigator.useragent.tolowercase().indexof('firefox') > -1; if(is_firefox){ dom+=" option"; } $(dom).on("click",function(event) { console.log($(event.currenttarget)

Event listener when the transformation of the stream is finished, Node.js -

i trying register event listener @ end of data in pipe transformation. trying register event streams in pipe: a) custom transform stream (streamtobuffer) b) standard file read stream c) standard gunzip stream. but unfortunately, none of them works (see code below). far try, 'data' event works, not help. what need continue processing of tailbuffer in streamtobuffer class after transformation finished. can suggest how achive this? the code (simplified brevity): function samplepipe() { var streamtobuffer = new streamtobuffer(); var readstream = fs.createreadstream(bgzfile1, { flags: 'r', encoding: null, fd: null, mode: '0666', autoclose: true }); var gunziptransform = zlib.creategunzip(); readstream.on('end', function() { //not fired console.log('end event readstream'); }); streamtobuffer.on('end', function() { //not fired

ruby on rails - Setting Active Admin namespace using active admin config -

i using active admin devise , im trying set namespace active admin routes. in active_admin.rb have set default_namespace as, config.default_namespace = :abc_123 in route have, devise_for :admin_users, activeadmin::devise.config activeadmin.routes(self) the routes generated such, root / pages#home new_admin_user_session /abc_123/login(.:format) active_admin/devise/sessions#new admin_user_session post /abc_123/login(.:format) active_admin/devise/sessions#create admin_root /admin(.:format) admin/dashboard#index abc_123_root /abc_123(.:format) abc_123/dashboard#index abc_123_quotes /abc_123/quotes(.:format) abc_123/quotes#index post /abc_123/quote

MySQL Php adding <h2> to a text In the Database -

i'm trying copy 1 column column grab column name , put inside column descrption stay on top of description,so far working ,i can't figure out how put finished product h2 e.g name = best banana description = yellow thing ever end result name = best banana description = <h2>best banana</h2> yellow thing ever this code far $sql = "update product_description set description = if(description null, name, concat(name, description));"; i tried : $sql = "update product_description set description = if(description null, name, concat('<h2>name</h2>', description));"; but '<h2>name</h2>' displays word name in h2 , not table tips on how it? try $sql = "update product_description set description = if(description null, name, concat('<h2>', name, '</h2>', description));";

how to run an application using oracle -

i have application running on server. every second application checks inserted rows in table. after row inserted application sends necessary info via email. so, connection db (means session) effects system performance. takes lot of memory. is possible implement in way oracle executes batch file (batch file execute application) after row inserted? if yes, how that? p.s.: batch file has been prepared , working fine me. some methods making process sort-of asynchronous are: triggers - perhaps after statement trigger kicks off job. dbms_scheduler - create job runs every x minutes , processes rows flag not set. flag should indexed. continuous query notification‌​ - notify application when relevant row has changed.

javascript - openpgp.js on wp8 error -

i'm using openpgpjs library in app, created apache cordova. here's part of code: var publickey = openpgp.key.readarmored(_publickey); openpgp.encryptmessage(publickey.keys, text).then(function (pgpmessage) { // success callback(pgpmessage); }).catch(function (error) { // failure console.error(error); }); it works fine not on wp8. if fails, 'cause openpgp var undefined. in library source there's such code @ beginning: !function (e) { "object" == typeof exports ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : "undefined" != typeof window ? window.openpgp = e() : "undefined" != typeof global ? global.openpgp = e() : "undefined" != typeof self && (self.openpgp = e()) } so openpgp should defined. how can make work? update i've added var openpgp = window.openpgp; , error dis

android - How to achieve two sections below listview where i can place dynamic radiobuttons -

Image
how can achieve 2 sections below listview can place dynamic radio buttons, . listview can scrollable extent, , below there layouts divided 2 parts radiobuttons fit dynamically below layout : <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="@string/some_text" android:textsize="20sp" /> <button android:id="@+id/findselected" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="find countries selected" /> <listview android:id="@+id/listview1&quo

android - MvvmCross custom binding display dialog -

the goal display dialog user select date on tap on edittext . i'm truing implement binding show dialog on click. code following: public class editdatebinding : bindingwrapper<edittext, datetime> { public editdatebinding(edittext androidcontrol) : base(androidcontrol) { } public override void subscribetoevents() { target.click += inputclick; } private void inputclick(object sender, eventargs args) { datetime parseddate = datetime.now; datetime.tryparse(target.text, cultureinfo.currentculture, datetimestyles.none, out parseddate); var dialog = new datepickerdialogfragment(target.context, parseddate, ondateset); dialog.show( // can't fragment manager here , "date"); } private void ondateset(object sender, datepickerdialog.dateseteventargs e) { setvaluetoview(target, e.date); } protected override void dispose(bool isdispos

How to integrate Facebook/Google+ without redirect Safari browser in iOS app -

i tried integrate facebook/google+ in app. can inbuilt facebook framework, google plus framework, google open source framework, in ios app getting details account added in settings app of device. can opening safari browser , redirect app after login facebook , goolge+. so, need without redirect safari browser. using new google+ sdk, user not have reenter password in safari or browser. take on this: https://developers.google.com/+/mobile/ios/sign-in if user has native google or google+ mobile app installed user not have re-enter google credentials authorize app. or try gtmoauth2viewcontrollertouch - (id)initwithscope:(nsstring *)scope clientid:(nsstring *)clientid clientsecret:(nsstring *)clientsecret keychainitemname:(nsstring *)keychainitemname completionhandler:(gtmoauth2viewcontrollercompletionhandler)handler plenty of references available online. google drive ios sdk: display cancel login button

sql - Syntax error while using centroid function within the RotateCoords function in Spatialite Query -

create table rotated_bus select ao_id, rotatecoords(st_centroid(geometry) substation, 45.00) geometry busbar; i trying rotate line geometry (busbar) passing centroid of polygon geometry (substation) inside rotatecoords function. after running above query, getting error “near syntax error”. wrong query? you join 2 tables: create table rotated_bus select busbar.ao_id, rotatecoords(st_centroid(substation.geometry), 45) geometry busbar join substation on busbar.ao_id = substation.substn_id alternatively, use correlated subquery (subqueries must complete queries inside pair of parentheses): create table rotated_bus select ao_id, (select rotatecoords(st_centroid(geometry), 45) substation substn_id = busbar.ao_id ) geometry busbar

android - WebView - memory leaks in a simple code on devices <= 4.1 -

my test code: public class myactivity extends appcompatactivity { webview mywebview; relativelayout webviewlayout; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.mylayout); webviewlayout = (relativelayout) findviewbyid(r.id.webviews); mywebview = new webview(this); webviewlayout.addview(mywebview); } } causes memory leak in webview on 4.1 device (i use mat analysis): class name java.lang.thread @ 0x4212f6b8 webviewcorethread thread '- <java local>, target android.webkit.webviewcore$webcorethread @ 0x4205d390 '- core android.webkit.webviewcore @ 0x4212f608 '- mcontext com.packagename.myactivity i have added ondestroy(): @override public void ondestroy() { webviewlayout.removeallviews(); if(mywebview != null) { mywebview.removeallviews(); mywebview.onpaus

oracle adf - Difficulties in importing ADF projects(10.1.2) in JDeveloper 10g 10.1.2 -

i mayuresh , new adf technology. working on project based on adf technology. our source code developed in 10g 10.1.2 version , trying import on our machine. using same jdeveloper (10g 10.1.2) after opening .jws file in jdeveloper structure appears i.e. application name project 1 project 2 project 3 nothing inside it. have gone through many sites still not able import our source code in jdeveloper 10g 10.1.2 if can out great. thanks check project properties each of projects see source directory code set to.

Java client to authenticate against CAS server -

i have written client app java following: https://wiki.jasig.org/display/casum/restful+api i able tgt , service ticket. able "validate" service ticket against cas through app i.e. against: https://<host>:8443/cas/servicevalidate using service ticket, able verify works browser: https://<host>:8443/myproject/login/cas?ticket=<ticket_id_from_my_client_app>&service=<encoded url of service> works but service ticket not work app. tried: resttemplate rt = new resttemplate(); responseentity<string> s1 = rt.getforentity("https://<host>:8443/myproject/login/cas?ticket=<ticket_id_from_my_client_app>&service=<encoded url of service>", string.class); the response default login page cas. when trying on browser again, works. note, using identical url both testing in browser , app. (i have modified cas config extend life of tgt , service tickets 1 hour , validity count till 1000, know expiration not probl

html - i can't handle a tag <image> in svg code -

i generated svg code map in illustrator put in website had code has tag called <image> can not handle, can't give css properties nor put foreground text on it, objective have image or g or link changes foreground color hover on it, can't find thing tag, there articles path or circle or line svg tags not <image> here's code : <svg version="1.1" xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewbox="0 0 1434 1454.3" enable-background="new 0 0 1434 1454.3" xml:space="preserve"> <switch> <foreignobject requiredextensions="&ns_ai;" x="0" y="0" width="1" height="1"> <i:pgfref xlink:href="#adobe_illustrator_pgf">