Posts

Showing posts from March, 2015

android - NPE when adding inflated button -

i try create new button programatically , existing viewgroup (i moved custom classical linearlayout ensure bug not in custom viewgroup). a code simple , working in different use case: private void appendtile() { view view = getlayoutinflater().inflate(r.layout.template_tile, null); view.setid(view.generateviewid()); view.setonclicklistener(tilelistener); hiddenpicture.addview(view, view.getlayoutparams()); } template_tile.xml: <button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" style="@style/formulavalue" /> but fails, because view.getlayoutparams() null (though there layout_width , layout_height in xml). caused by: java.lang.nullpointerexception: attempt read field 'int android.view.viewgroup$layoutparams.width' on null object reference @ android.view.viewgroup$layoutparams.<init

tomcat - Timezone issue with grails application -

i have running grails application timezone set gst parameter jvm on tomcat 7. couple weeks back, application starts misbehaving , time see in logs gmt time. im not sure should more information, setting overridding value. help? as per @jon skeet suggestion, after replacing jvm parameter user.timezone=gst user.timezone=asia/dubai solved issue

linux - combine sed and grep to find using regex and replace recursively -

i got problem when im trying find string (using regex) in files , replace it. i find strings in file contain this: "ip":"([0-9\.]+)" and replace with: "ip":"127.0.0.1" any idea?

c# - Neo4jClient node ids -

i'm having trouble working out how id work in neo4jclient. want .net model have identifier property, , ideally i'd use neo4j autoincremented id node. however, no matter case use ( id , id , id ) in model class, adds field in neo4j (keeping 0 when create new node). when view node in neo4j browser, has <id> auto-incremented, , id field 0 (unless manually set in model in c#). i want able create new .net model class (which have uninitialised id of 0), once i've created neo4j fluent cypher query, have id newly created node's autoincremented id. the examples here: https://github.com/readify/neo4jclient/wiki/cypher-examples show user class of having id this: public long id { get; set; } but in example creating new user ... var newuser = new user { id = 456, name = "jim" }; graphclient.cypher .create("(user:user {newuser})") .withparam("newuser", newuser) .executewithoutresults(); i'm unsure 456 magic n

javascript - Sending data from node.js back to client? -

i sending post request node.js client .in handler of request making http post request(in node.js) data,which gives me json data in response ,then in turn data making http post request(in node.js) gives me set of data in response . want return response data handler function ,the set of data receive response can send client .how can achieve this. server.route({ path:"/test", method:"post", handler:function(request,reply){ var load=request.payload; userauth(load); return reply({status:"ok"}); } }); function userauth(newdata){ request({ har:{ url:"url", method:"post", headers:[ { name:'content-type', value:"application/x-www-form-urlencoded;charset=utf-8" } ], postdata:{ mimetype: 'application/x-www-form-urlencoded', params:[ { name:"username", value:userdetails[&quo

wpf - MutliSelect ListBox in Menu -

Image
i creating undo button should work identical visual studios undo button. want user able mouse on item , every item above selected. on click items above passed in , actions performed. if user clicks button itself, undo top object. problem: not using context menu , no idea i'm doing wpf. right user can mouse on object mouse above selected (all code behind vb.net). appreciated! code: <menuitem header="undo" name="menuundo" isenabled="true"> <menuitem.icon> <image source="undo.png" width="24" height="24" /> </menuitem.icon> <stackpanel> <listbox name="listboxundo" horizontalalignment="stretch " verticalalignment="stretch" width="177" height="100 " margin="-33,-5,-65,-5" scrollviewer.verticalscrollbarvisibility="visible" isenabled="true"

html - Use jQuery to populate sibling hidden input -

for calculation currencies, need value of input parsed integer , value should populate sibling input of type "hidden". i make reusable possible, use same script inputs it. html : <div class="input-group" id="total-emplcosts"> <span class="input-group-addon">total employer costs</span> <input type="text" class="form-control" name="empl_costs_inp" id="empl_costs_inp" /> <input type="hidden" name="empl_costs" id="empl_costs" /> </div> jquery tried: (not doing @ all) $('.input-group input').on('keyup blur focusout',function() { if($(this).val() !== '') { var inputvalue = $(this).val(); var integervalue = parseint(inputvalue * 100); $('input').siblings('input').val(integervalue); } } and: (adding integervalue hidden inputs) $(&

c# - IDisposable object disposed before end of using block -

i have using block around idisposable directoryentry create directory entry, access 1 of properties, , dispose of it. however, directory entry being disposed prior end of using block. public static propertyvaluecollection getproperty( principal principal, string propertyname) { using (var directoryentry = principal.getasdirectoryentry()) { return directoryentry.properties[propertyname]; } } public static directoryentry getasdirectoryentry( principal principal) { return principal.getunderlyingobject() directoryentry; } the error thrown on return directoryentry.properties[propertyname]; line, saying directory entry disposed. can remove using block , code work, concerned object never getting disposed. call multiple times, multiple instances of directory entry being created , never disposed? your code isn't creating directoryentry instance, nor principal.getunderlyingobject() method (which isn't factory method). since code doe

javascript - How could I implement this navigation menu? -

i need implement menu navigation this dotnetnuke website (i looking part of navigation started "i want to...") the problem menu systems using dropdown popus in case menu needs shift down content. i using superfish , changed css make dropdowns inserted between menubar , rest of content no success in animation. how animate effect? i asp.net developer bit knowledge of javascript/css. dotnetnuke , navigation menu dynamically created. most drop down menus appear on other elements on page positioned absolute in css, if want push content down try "position:relative" instead. the menu posted jquery driven , doesn't appear have "position" element in css, expands hidden box onclick.

jquery - Is it possible to make fullcalendar.io to selectable by square in weekView? -

i making calendar web-app fullcalendar.io. want create event or block schedule same time days repeatedly. can tweak fullcalendar , make possible drag , selected in square? for example drag start 2pm 6pm monday , expand friday in right direction. when in normal fullcalendar, select monday 2pm friday 6pm. not square. not want select 6pm next day 2pm repeatedly. is possible? if is, how can this?

android - qpython kivy textinput and display -

using qpython , kivy on android phone, i'm trying write program inputs text, processes , shows output. from kivy.app import app kivy.uix.button import button kivy.uix.textinput import textinput class testapp(app): def build(self) r = textinput(multiline=false).text y = self.dosomething(r) return button(text = y) def dosomething(self, x): y = x + ' something' return y testapp().run this fails - when push run doesn't ask input , display 'something'. how fix can text input user? edit replace build with: def build(self): def cb(instance, value): print(value) r = textinput(focus=true, multiline=false) r.bind(text=cb) return r

c# - wix: Service is not being started after rollback -

we have wix project. installs 2 windows services , windows desktop application shown in task bar tray icon. purpose of these 2 services watch each other , desktop application if 1 of service not running, other service start it. , if desktop application not running, 1 of 2 services start desktop application. we want implement rollback feature in our installer if there error during upgrade latest version, installer rollback previous existing version. testing rollback using wixfailwhendeferred. <customactionref id="wixfailwhendeferred" /> the rollback seems work in tests, install rollbacks previous versions. example, in machine v8.0.1.0 installed , when run following command, tries install v8.0.2.0 rollbacks 8.0.1.0. >msiexec.exe /passive /norestart /i "d:\setup8.0.2.0.msi" /l*vx+ "d:\test\installlog8.0.2.0.log" wixfailwhendeferred=1 but, have 1 issue. if 8.0.1.0 installed in machine , double click newer version 8.0.2.0.msi, ask clo

bc - Multiply elements of array in bash -

i have 2 arrays value={00..23} i=(01 02) when multiply them using following command, results need format ... need result 00, 01...18, ...36 and get, 0,1 ..8, 18,..36 t=$(expr $value*$i | bc) anybody can show me way? and if want sum 24 @ value when second element of array days , 0 if first element of array days @ value...i have used following code without success... #!/bin/bash data=`date +%y-%m-%d` data1=`date -d "1 day" +%y-%m-%d` days=("$data" "$data1") day in "${days[@]}"; value in {00..23}; # here order sum 00 if first day, , if second day, order sum 24 @ value... if [[ "$day"="${days[0]}" ]]; i=00 else i=24 fi t=$((10#$i+10#$value)) echo $t done done i should 00, 01, 02...23, 24, 25, 26...48..but don't it.... your question isn't clear. guess you're in situation: value=( {00..23} ) # <--- defines array, unlike code in question i=( 01 02 ) and want loop through arrays val

jquery - How to append to multiple inputs with different names? -

i have multiple inputs text different names. append them adding new text box working fine. problem comes since input text fields have different names. how can work using 1 function , not having create 1 each input? i made simple https://jsfiddle.net/ke6br8xj/ $(document).ready(function() { var max_fields3 = 30; //maximum input boxes allowed var wrapper3 = $(".input_fields_wrap12"); //fields wrapper var add_button3 = $(".add_field_button11"); //add button id var wrapper6 = $(".input_fields_wrap11"); //fields wrapper var x = 1; //initlal text box count $(add_button3).click(function(e){ //on add input button click e.preventdefault(); if(x < max_fields3){ //max input box allowed x++; //text box increment $(wrapper3).append('<div> <input type="text" class="pets" name="super_stars_winner#currentrow#" size="35&q

c# forms not linking correctly -

in current code, have multiple c# windows forms linking , working, once make new form, cannot link previous form, can still link other forms idea why happening? private void closebtn_click(object sender, eventargs e) { form1 frm = new form1(); frm.show(); this.close(); } //this 1 works go close form private void passengerbtn_click(object sender, eventargs e) { lsum frm = new lsum(); frm.show(); this.close(); } //this 1 not link form,whilst code //is same , form name correct // i have used same open , close code throughout program , been working fine untill point (currently 9 forms 10th 1 wont link, there limit on forms sorry if dumb question) edit: after time of stressing out why not work , taking account comments found out why wouldn't work fig1: http://prntscr.com/btmw5z creating form inside "luton" folder causing not link somehow, why wouldnt link im unsure been fixed now, guys :d

c# - How to test a DNS connection? Just as the button "Test" in the ODBC Data Source Administrator? -

Image
i wonder how write code in c# simulate button shown in above image. any welcome. check out. can add below code in form application on button click event. string sqlconn = "data source=yourservername;initial catalog=dbname;user id=dbuser;password=dbuserpws;application name=mytestapp;" //for port number //string sqlconn = "data source=yourservername,5432;initial catalog=dbname;user id=dbuser;password=dbuserpws;application name=mytestapp;" sqlconnection myconnection = new sqlconnection(sqlconn); try { myconnection.open(); messagebox.show("connected successfully"); } catch(exception e) { messagebox.show("error. error message:" + ex.message); }

amazon limit resource usage to control billing in case of DDoS or similar -

is possible or typical actions apply prevent being over-billed aws usage or other cloud provider, in case of say, ddos attack or similar? one of example, lets public s3 access. yes, relatively cheap get , other requests $0.0043 per 10,000 requests , ,still having access public endpoint, theoretically can generate traffic , increase billing. aws way prevent this, if any, or techniques applied cloud provider, , not aws. specifically regarding s3, there discussion on topic on stack exchange site here: https://security.stackexchange.com/questions/8583/risks-with-amazon-s3-and-costs in addition, place cdn firewall rules cloudflare , or amazon's own cloudfront in front of s3 bucket in order improve performance , provide ddos mitigation features. this specific s3, seems main concern. if have concerns other aws services might want create separate question.

jquery - how to add both barchart and line graph in single chart -

Image
hi trying attain both bar , line graph in 1 chart able show bar graph(multiple vertical bars), need show line graphs $("#chart1").html(""); var xlabel = 'areas'; var ylabel = 'numbers'; var yinterval=''; var yinterval=''; var s1 = [20, 60, 70, 100]; var s2 = [70, 50, 30, 20]; var s3 = [10, 50, 30, 20]; var ticks = ['na','apac', 'eu','latam']; var yinterval=120; var count=120; $.jqplot('chart1', [s1, s2, s3], { seriescolors:['#5882fa', '#df7401', '#a4a4a4'], seriesdefaults: { renderer:$.jqplot.barrenderer, pointlabels: { show: true }, rendereroptions: { barwidth: 25, bardirection: 've

javascript - What is happening when using the keyword this in lambdas vs functions with Typescript -

this question has answer here: how access correct `this` inside callback? 6 answers i using typescript angular 2 project. notice when use keyword this inside labmda expression vs function, this refers different things. for example, let's have angular component following. export class mycomponet { isactive = true; names = [ "john", "jeff", "jared" ]; dosomethingwithlambda() { names.foreach( (value, index) => { if(this.isactive) { //this.isactive refers mycomponent.isactive //do something... } }); } dosomethingwithfunction() { names.foreach( function(value, index) { if(this.isactive) { //this.isactive undefined, since refers function //do } }); } dosomethingwithfunction2() { let isactive = this.isactive; names.foreach( function(value, index) { if(isactive) { //if change isactive cha

visual studio 2013 - How can I fix PreEmptive Dotfuscator (VS2013)? -

i have visual studio 2013 included "preemptive dotfuscator , analytics". it's worked fine me until recently. not open visual studio, icon or commandline. when manually open it, not show in task manager. it nothing. there's nothing in event viewer logs. visual studio shows no error. basically, can't begin find problem. i tried find download attempt reinstall i've seen on website version it's included in vs2013. there's other sites in search results claim have installer none trust. has had issue in past? it's visual studio 2013 professional on windows 8.1. i'm not sure how address appreciate possible input. thanks in advance! you can try uninstalling, wiping settings, , reinstalling. dotfuscator community edition uninstallable via windows control panel. once uninstalled, delete %localappdata%\preemptive solutions . may able reinstall component via visual studio installer. if not, standalone installer, if have visual

npm - VS Code and tasks with node -

until used gulp building typescript , sass files, due couple of new build steps i'd unify , use node single entry point (also node running gulp tasks via npm run taskname). tasks.json quite simple, task build should run npm run watch : { "version": "0.1.0", "command": "npm", "isshellcommand": true, "tasks": [ { "taskname": "build", "isbuildcommand": true, "showoutput": "always", "iswatching": true, "args": [ "run", "watch" ] } ] } package.json "scripts": { "watch": "gulp default", } and output: gulp default build [14:20:54] using gulpfile path_to/gulpfile.js [14:20:54] task 'build' not in gulpfile [14:20:54] please check documentation proper gulpfile form

python - How to use the return value of the first task in the second task's group for loop? -

i have 2 celery tasks: @app.task def task1(a, b, c, d): # stuff , find return value return r @app.task def task2(a, b, c, d, e, f, g): # other stuff i want first execute task1 , execute group of task2 in parallel: c = chain(task1.s(a, b, c, d), group(task2.si(a, b, c, e, i, j) i, j in enumerate(range(e)))) but, "e" argument above return value of task1, passed task2 , used in loop. how implemented using celery? you may specify base first task , have call second task retval of first. can in on_success method of base. import task celery def setval(): return 1, 2, 3 class followup(task): def on_success(self, retval, task_id, *args, **kwargs): i, j in enumerate(range(retval)): task2.si(a, b, c, retval, i, j) # a, b, c should set before here # use task set here if need collectively verify status of tasks # http://docs.celeryproject.org/en/2.1-archived/reference/celery.task.sets.html @app.task(base=f

asp.net web api2 - Web API 2 Odata V4 PATCH return 404 -

i have controller : using system.web.http; using system.web.odata; public class invrecipientautoinvoicecontroller : odatacontroller { // get: odata/invrecipientautoinvoice [enablequery] public iqueryable<inv_recipientautoinvoice> getinvrecipientautoinvoice() { return db.inv_recipientautoinvoice.where(a=>a.companynumber == companynumber); } [acceptverbs("patch", "merge")] public ihttpactionresult patch([fromodatauri] int recipientnumber , [fromodatauri] int recipienttype, delta<inv_recipientautoinvoice> patch) { // xxxx update code } } the works , result , can sort them. when patch request, 404 error , patch request : request url: http://localhost:61240/odata/invrecipientautoinvoice(recipientnumber%3d443%2crecipienttype%3d400) request method: patch response body : { "error":{ "code":"","

Keras LSTM state -

i run lstm in keras , output plus states. thing in tf with tf.variable_scope("rnn"): time_step in range(num_steps): if time_step > 0: tf.get_variable_scope().reuse_variables() (cell_output, state) = cell(inputs[:, time_step, :], state) outputs.append(cell_output) is there way in keras can last state , feed new inputs when lenght of sequence huge. aware of stateful=true want have access states while training too. know using scan not loop want save states , on next run, make them starting states lstm. in nutshell, both output , states. since lstm layer, layer can have 1 output in keras (correct me if wrong), can not 2 output simultaneously without modifying source code. recently hacking keras implement advance structure, thoughts, might not like, did works. doing override keras layer can access tensor representing hidden states. firstly, can check call() function in keras/layers/recurrent.py how keras did work: def ca

vba - Check a column to see if there is a named range in a column -

i'm dealing on 300 named ranges in spreadsheet each individual cells identify individual columns. (they not column names, there many duplicates) question: if have named range is: myrange = range(cells(2,7).address) and active cell cells(5,7) is there way identify fact can identify column number in active cell, in same column named range, , return named range's name? something like....... function get_rangename(mycolumn) string each nm in thisworkbook.names if ***code coloumn number here*** = mycolumn get_rangename = nm.name end if next nm end function i don't know how column number name you can use intersect() function function get_rangename(mycolumn long) string each nm in thisworkbook.names if not intersect(columns(mycolumn),range(nm)) nothing get_rangename = nm.name exit end if next nm end function

php - CodeIgniter inserting data to database with quotes in string -

data like $data = array ( 'question' => 'how “something” in' 'answer_one' => '1. answer' ... 'correct_answer' => 1 ); i use $this->db->insert('questions',$data); when run $this->db->last_query() i get: insert `questions` (`question`, `answer_one`, ... , `correct_answer`) values ('how “something” in', '1. answer', ... ,'1') and data saved how ?something? in and $data = array ( 'question' => 'my name is…' 'answer_one' => '1. answer' ... 'correct_answer' => 1 ); is run as insert `questions` (`question`, `answer_one`, ... , `correct_answer`) values ('my name is…', '1. name', ... , '1') is inserted "my name is?" $data = array ( 'question' => 'what's name?' 'answer_one' => '1. answer' ... 'correct_answer' => 1 ); is inserted as

Android: Filtering in the Adapter does not working -

Image
i have following class filtering called on onquerytextchange. problem found results not updated in list of found results. example have list (see. image below): and entered query "test 1", updated result should contain 1 found row. but result list still same. i ask should update filtered results in right way. many advice. mainactivity searchview.setonquerytextlistener(new searchview.onquerytextlistener() { @override public boolean onquerytextsubmit(string s) { logger.d("onquerytextsubmit "); return false; } @override public boolean onquerytextchange(string s) { logger.d(s); logger.d("onquerytextchange "); madapter = new wlannetworkadapter(datacontainer.getaccesspointlist(), getparent()).getfilter(); madapter.filter(s.tostring()); //todo: https://coderwall.com/p/zpwrsg/

php - Why can't I access this global variable? -

i of course tried out $globals , still no go. syntax correct. understanding $db_user in global scope. <?php $db_user = 'foo'; class database { // not work private $db_user = $globals['db_user']; private $db_pass = 'foob'; private $db_driver = 'foob_foob'; // ... you calling $db_user inside of class method, means calling variable local scope (within class). fix this, tell php you're looking global variable adding global $db_user inside of methods used (or use constructor add class scope): class database { private $db_user = ''; private $db_pass = 'foob'; private $db_driver = 'foob_foob'; // snip // method 1: add variable class scope constructor public function __construct() { global $db_user; $this->db_user = $db_user; }

email - Need advice: How to share a potentially large report to remote users? -

i asking advice on possibly better solutions part of project i'm working on. i'll first give background , current thoughts. background our clients can use company's products generate potentially large data sets use in industry. when data sets generated, clients file processing request us. we want send clients a summary email contains statistical charts sampling points data sets can initial quality control work. if data sets of bad quality, don't need file request. one problem charts , sampling points can potentially large sent in email . charts , sampling points want include in emails pictures. although can use low-quality format such jpeg save space, cannot control how many data sets included in summary email, total size still exceed normal email size limit. in terms of technologies , developing in python on ubuntu 14.04. goals of solution in general, want present report-like thing clients initial qa. report may contains external links not need int

c# - Using yield in a while loop to return one or many objects -

i have 2 database methods. 1 fetches 1 row based on name , creates object out of it. other identical, fetches rows , creates n objects out of it. hoping use yield return share method process sqllite data, issue have in createfoofromsqlselect telling me the body of createfoofromsqlselect cannot iterator block because foo is not iterator type . wasn't expecting that. public foo getfoo(string name){ string sql = "select age people name = " + name; return createfoofromselect(sql); } public list<foo> getfoos(){ list<foo> foos = new list<foo>(); string sql = "select * people"; foos.add(createfoofromselect(sql)); } private foo createfoofromselect(string sql){ foo foo; sqlitecommand command = new sqlitecommand(sql, sqlconnection); sqlitedatareader reader = command.executereader(); while(reader.read()){ yield return foo = new foo(reader["age"]); } } you can use yield statement on metho

google app engine - How to cleanup the development datastore? -

in google app engine go sdk can fill local datastore bunch of test data. it's tiring delete thousands of records 20 @ time using web interface. there command erases local datastore? simply provide --clear_datastore command line parameter when starting: goapp serve --clear-datastore documented at: the go development server: using datastore . to clear local datastore application, use --clear_datastore=yes option when start web server: note documentation "copied" python section, need use presented above (you error if try execute goapp serve --clear_datastore=yes ).

excel - Named Range error after importing values from a csv -

Image
i have multiple csv workbooks 1 worksheet in it. the worksheet has data in 2 columns: cola colb namedrange1 valueofnamerange1 namedrange2 valueofnamerange2 namedrange3 valueofnamerange3 . . . . . . . . on total of 373 named ranges , values now importing namedranges , values in worksheets has same namedranges , values can different well. want update values of namedranges importing csv. the code below: option explicit sub impdata() dim mycsv workbook dim mycsvpath string dim myrange range dim mycell range dim mynextcell range dim mynamedrange range dim ws worksheet dim finalrow long mycsvpath = getfile if mycsvpath <> "" set mycsv = workbooks.open(mycsvpath) application.screenupdating = false set ws = sheets(1) finalrow = w

How to animate setInterval used to make an Image slider using javascript/Jquery? -

the images changing , want them have slide effect. html <div><img src="1.jpg" id="sliderimage"></div> this script i'm using: var myimage = document.getelementbyid("sliderimage"); var imagearray = ["1.jpg","2.jpg","3.jpg"]; var imageindex = 0; function changeimage() { myimage.setattribute("src",imagearray[imageindex]); imageindex++; if (imageindex >= imagearray.length){imageindex = 0;} } var intervalhandle = setinterval(changeimage,5000); the simplest way achieve put use css transition effect , javascript set timer. helps organize elements inside list. can't see images in code below because of same origin policy. try locally , download images , should work. here simple slider have built https://github.com/rotexhawk/javascript-practice/tree/master/slider-simple

python 3.x - Get public properties from a class -

i of public properties of instance of class in python 3, in dictionary, function public , without of function in class. example, instance of following class : class test: def __init__(self): self.a = 5 self.__b = 2 @property def c(self): return 9 def d(self): return 2 def __e(self): return 2 i following dict : {'a': 5, 'c': 9} thanks in advance responses.

apache spark - Saving empty data frame to parquet -

i have problem saving empty table parquet. in case schema not preserved , table cannot read afterwards. mydf.write.format("parquet").partitionby("part_id").save("aa") my sql queries relying on same set of tables, , in case of table empty , therefor cannot read queries not work. way save empty table metadata ? with best regards, michael i have removed partitionby call , after metadata saved correctly

java - HTTPs Post redirect -

i have transfer information external website on click of button. so, when click on button, new window opens, existing screen should remain is. using below configuration <action name="actionname" class="actionclass" method="executemethod"> <result name="success">../somejsp</result> </action> however, whenever click on button, screen gets refreshed , value on screen changes. there way prevent refresh? i think need prevent default submit , call submit script. refer: http://www.w3schools.com/jquery/event_preventdefault.asp example. whenever need preprocessing before actual form submit method allows that. call javasript function before doing actual submit or if needed prevent form submit.

javascript - Calling geonames to find nearby streets -

i'm trying list of nearby streets given latlng value using geonames web service. can nearby wikopedia articles unable list of street names using findnearbystreetsosm method. have: i'm blind , using screenreader. code indented correctly. //geonames api function //feed in geonames method i.e. findnearbywikipedia, findnearbystreetsosm + long , lat values + name of div want results displayed in function fetchdatafromgeonames(geonamesmethod, latitude, longitude, divtooutputresultsto) { var geonamesapikey = "my_api_key); var apiurl = "http://api.geonames.org/"; var radius = 1; var request = apiurl + geonamesmethod + "json?lat=" + latitude + "&lng=" + longitude + "&username=" + geonamesapikey; if (geonamesmethod == 'findnearbywikipedia') { request += "&radius=" + radius + "&maxrows=5&country=uk"; } request += '&callback=?'; //alert(request); //pass

arrays - Heap's algorithm in Clojure (can it be implemented efficiently?) -

heap's algorithm enumerates permutations of array. wikipedia's article on algorithm says robert sedgewick concluded algorithm ``at time effective algorithm generating permutations computer,'' naturally fun try implement. the algorithm making succession of swaps within mutable array, looking @ implementing in clojure, sequences immutable. put following together, avoiding mutability completely: (defn swap [a j] (assoc j (a i) (a j))) (defn generate-permutations [v n] (if (zero? n) ();(println (apply str a));comment out time code, not print (loop [i 0 v] (if (<= n) (do (generate-permutations (dec n)) (recur (inc i) (swap (if (even? n) 0) n))))))) (if (not= (count *command-line-args*) 1) (do (println "exactly 1 argument required") (system/exit 1)) (let [word (-> *command-line-args* first vec)] (time (generate-permutations word (dec (count word)))))) for 11-character input string, algorithm ru

python - How to apply interp1d to each element of a tensor in Tensorflow -

let say, have interpolation function. def mymap(): x = np.arange(256) y = np.random.rand(x.size)*255.0 return interp1d(x, y) this guy maps number in [0,255] number following profile given x , y (now y random, though). when following, each value in image gets mapped nicely. x = imread('...') x_ = mymap()(x) however, how can in tensorflow? want like img = tf.placeholder(tf.float32, [64, 64, 1], name="img") distorted_image = tf.map_fn(mymap(), img) but results in error saying valueerror: setting array element sequence. for information, checked if function map simple below, works well mymap2 = lambda x: x+10 distorted_image = tf.map_fn(mymap2, img) how can map each number in tensor? help? the function input of tf.map_fn needs function written tensorflow ops. instance, 1 work: def this_will_work(x): return tf.square(x) img = tf.placeholder(tf.float32, [64, 64, 1]) res = tf.map_fn(this_will_work, img) this 1 no

api - Build request for postAction FosRestBundle WebTestCase -

i'm trying make web test case restfull api app. i'm using fosrestbundle , problems don't know how build request. this fos-rest config: fos_rest: disable_csrf_role: role_api param_fetcher_listener: true body_listener: true format_listener: true view: view_response_listener: 'force' formats: xml: true json : true templating_formats: html: true force_redirects: html: true failed_validation: http_bad_request default_engine: twig routing_loader: default_format: json this web test case : public function test_postaction() { $client = static::createclient(); $parameters = [ 'contenttext' => 'lorem ipsum dolor sit amet, consectetur adipiscing elit. mauris lobortis sapien ac magna hendrerit tincidunt. nunc mi dui, rhoncus nec justo et, rutrum lobortis sem. fusce venenat

html - Trying to create a png file from txt input PHP -

i'm learning code , making little project myself. i'm trying project out html5 , php. here want do: i want user input info, name, address, number, ect. want grab info , somehow place .png file can save picture. have code grab text, i'm stuck on next part. here part of code used info: $first = $_request['first']; $last = $_request['last']; $email = $_request['email']; $address = $_request['address']; $city = $_request['city']; i hope question makes sense. this done using php gd library. you need png image start with. can choose example 100 x 100 canvas.png nothing white on (so can read black text on it). also find font write text with. save in same directory script. <?php // fetch text write $first = $_request['first']; $last = $_request['last']; $email = $_request['email']; $address = $_request['address']; $city = $_request['city']; hea