Posts

Showing posts from February, 2015

android - How to Load images from FTP server in ImageView without saving on local storage? -

i'm using ftp server upload images social networking app. due limitations of server shared host. i've no problem uploading, there way download images ftp server, via http ? because downloading each image on local storage first devastatingly slow , inefficient. , suggestion efficiency , memory management appreciated.

ios - IF comparison on CGFloat value - Xcode 7 gives error -

i have following code: @property (nonatomic, assign) cgfloat floatvalue; -- if (floatvalue) { //do } since xcode 7 - compiler error occurs : implicit conversion turns floating-point number integer: 'cgfloat' 'bool' can explain going / suggest code edits rectify it depends how cast cgfloat bool implemented. depend on objective-c's implementation or on actual processor's implementation of ieee floating point spec. either way, should not relying on that. since floats not guaranteed accurate. end incredibly close 0, have if statement fail. you should explicitly test float against value looking so: if (floatvalue != 0.0f) { //we know happen } in swift, compiler wouldn't let because tries keep safe: if (floatvalue) { //might happen, might not. knows } in swift, may use if (variable) syntax if variable of type bool. the objective-c compiler won't force behavior, should abide if want code run predictab...

ruby - ActiveRecord "lower(column_name)" is still case sensitive. (MySql2, Rails) -

i using mysql2 in rails application. trying make activerecord query returns records have specified fields containing string. have read downcasing input , using lower(column_name) 'string' should trick, this not appear work . query follows: search = params[:search].to_s.downcase @current_user.patients.where("lower(last_name) ? or lower(first_name) ? or lower(identifier) ?", "%#{search}%", "%#{search}%", "%#{search}%") let's have record last name "abbott". when search param "abb" or "bot", record returned. however, when search param "abb" or "bot", nothing returned. appears query still case sensitive ?? i have looked on , cannot seem find answer. have read multiple times lower(column_name) should work, not. any appreciated. thanks! i figured out. indeed because fields stored binary values (thanks vincent). casting binary fields chars, able case-insensitively compa...

unity3d - Calculating 2D parabolic trajectory for a projectile to hit a position -

Image
i'm developing tower defense in 2d in unity. i'm trying calculate parabola draw trajectory of projectiles fired tower in game. i've got position of tower , position of enemy - need algorithm calculates parabola hit enemy. is there universal algorithm or kind of calculation? assuming gravity no drag have: where x, y displacement x_0, y_0 initial location u_x, u_y initial velocity g acceleration due gravity t time elapsed

c++ - Error: LNK2001: unresolved external symbol "private: static class -

this forum contains many examples of such situation, in case static variables defined correctly, still error. issue not duplicate of previous , above link not answer question. suggested 21 answers post not have solution simon gave me here, please unmark "duplicate". seems i've declared correctly, check this: .h file: class valuesetsmodelscontainer : public qobject { q_object public: static void dllexport loadallergiesvaluesets(mptdatabase *db); static void dllexport loadproceduresvaluesets(mptdatabase *db); // models access functions static qstandarditemmodel *drugsmodel(); static qstandarditemmodel *substancemodel(); static qstandarditemmodel *reactionsmodel(); private: static qstandarditemmodel *mydrugsmodel, *mysubstancemodel, *myreactionsmodel; }; .cpp: qstandarditemmodel *valuesetsmodelscontainer::mydrugsmodel = 0; qstandarditemmodel *valuesetsmodelscontainer::mysubstancemodel = 0; qstandarditemmodel *valuesetsmodelscontainer::myreac...

xml - TXMLDocument->ChildNodes->Add() creates unwanted empty xmlns attribute -

this driving me crazy. need combine several xml classes 1 final document. defined federal government. after filling out each xml class (created using xml data binding wizard) appropriate values, need insert couple of classes child nodes. unfortunately way i'm doing creates empty (and not federal specifications) xmlns="" attribute. here's gist of code (with non-relevant pieces removed) irsreturn = new txmldocument(getwindow()); irsreturn->domvendor = getdomvendor("msxml"); // not cross platform compatible irsreturnroot = getreturn(irsreturn); irsreturn->version = "1.0"; irsreturn->encoding = "utf-8"; irsreturnroot->returnversion = "2015v3.0"; irsreturnroot->setattribute("xmlns", ereturn_targetnamespace); irsreturnroot->setattribute("xmlns:xsd", ereturn_schema); irsreturnroot->setattribute("xmlns:efile", ereturn_targetnamespace); irsreturnheader = new txmldocument(getwind...

Why is "require 'rails/all'" not installed/required in my config/application.rb? -

this curious irritant, why app not include expected line in config/application.rb, or anywhere else? require 'rails/all' this app generated using rails composer in 2014, if makes difference. also, rails 4.2.1. the issue arose because studying configuring rails applications , the rails initialization process guides have need modify initialization process. both state config/application.rb file expected contain line, mine not. and, yes, app runs fine locally , on heroku, so... why? my file is: require file.expand_path('../boot', __file__) # pick frameworks want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # require gems listed in gemfile, including gems # you've limited :test, :development, or :production. bundler.require(:default, rails.env) module theappname class applicatio...

html - Javascript Callback function malfunction -

i trying implement anonymous callback function. code here wrote janky know. typing intro span, activates .typed animation given parameters. need activate, , isn't, last function remove 2 elements id there. can't figure out how. <!-- executes intro typing text --> <script> document.getelementbyid('intro-button').onclick = function() { $(function() { $("#typing-intro").typed({ strings: ["&emsp;initseg = def_initseg</br>&emsp;sysseg"], typespeed: 0, backdelay: 20, loop: false, loopcount: false, }, function (){ document.getelementbyid("intro-section").remove(); document.getelementbyid("typing-intro").remove(); }); }); } ///script </script> as minusfour points out, typed animation function doesn't take callback function final parameter. instead "c...

ruby on rails - Resolving UsersController#show Couldn't find User with 'id'=1when that id was previously deleted -

i following michael hartl's tutorial. following error: activerecord::recordnotfound in userscontroller#show couldn't find user 'id'=1 extracted source (around line #155) record = s.execute([id], self, connection).first unless record raise recordnotfound, "couldn't find #{name} '#{primary_key}'=#{id}" end record rescue rangeerror already have tried bundle install , restarted server because initial error related bcrypt gemfile (using v 3.1.7). running rails console , inputing user.find(1) yields no user. however, user.all in rails c reveal have 1 user has id: 2 (the first user made deleted during prior test runs). app/controllers/users_controller.rb class userscontroller < applicationcontroller def show @user = user.find(params[:id]) end def new end end app/config/routes.rb rails.application.routes.draw do 'users/new' root 'static_pages#home' 'help' => 's...

html - Keeping all elements aligned to the same grid and spanning multiple columns -

i'm trying out css3's flexbox first time , seems promising, i'm having trouble getting behave. basically, want flexbox behave table order property can tell in css order display elements in grid. possible flexbox? here's test page created: https://jsfiddle.net/lb838dwf/ html: <div id="main"> <div id="div1">div 1</div> <div id="div2">div 2</div> <div>generic</div> <div id="div3">div 3</div> <div>generic</div> <div id="div4">div 4</div> <div>generic</div> <div>generic</div> <div>generic</div> <div>generic</div> <div>generic</div> </div> css: #main { width: 100%; border: 1px solid #c3c3c3; display: -webkit-flex; display: flex; -webkit-flex-wrap: wrap; flex-wrap: wrap; } #main div { min-width: 25%; height: 100px; ...

What can i use instead of toeplitz in Matlab in order to find the mean value of subarray? -

i have array (1,8760) represents hourly loads. loads same each year , wan perform calculations 20 years. tried use repmat, toeplitz , trill in order have matrix latest load each time. main objective calculate moving average using geometricall scheme calculate each f in code below. problem cant use toeplitz such big array. there other way? q=rand(1,8760); qb=repmat(q,1,20); qg=toeplitz(qb); qc=tril(qg); f49=mean(qc(50:175200,49:50),2); f50=mean(qc(54:175200,51:54),2); f51=mean(qb(62:175200,55:62),2); f52=mean(qb(78:175200,63:78),2); f53=mean(qb(110:175200,79:110),2); f54=mean(qb(174:175200,111:174),2); f55=mean(qb(302:175200,175:302),2); f56=mean(qb(558:175200,303:558),2); f57=mean(qb(1070:175200,559:1070),2); f58=mean(qb(2094:175200,1071:2094),2); f59=mean(qb(4142:175200,2095:4142),2); f60=mean(qb(8238:175200,4143:8238),2); f61=mean(qb(16430:175200,8239:16430),2); f62=mean(qb(32814:175200,16431:32814),2); f63=mean(qb(65582:175200,32815:65582),2); f64=mean(qb(131118:175200,6558...

sql - Base WHERE statement with many OR statements -

(insert typical i'm noob comment , million apologies asking noob question) i'm trying simplify query i'm trimming set of data. i've created statement other or statements based off of. issue i'm having not repeating base statement each or condition. what i'm having do: where ((base conditions) , x) or ((base conditions) , y) or etc..... what want do where ((base conditions) or x or y) i'm thinking can set base conditions , query base condition or statements don't know if that's i'm suppose do. thanks in advance! of course can that. need parentheses: where (base conditions) , (x or y or z . . .)

html - CSS Box 2.5D Pop Out Shadow effect -

so i'm trying create div element upon hovering, "pop" out, , appear 2.5d box. basically, person looking for: 3d box shadow effect except animated transition, when not hovered upon, simple 2d box, , when hovered on, appears second image in person's question. here's fiddle have far: http://jsfiddle.net/78m3nzv6/ <div class="cat-box bot-row"> <h4>hello world!</h4> <p>info</p> </div> . .bot-row:hover { transition: 0.3s ease-in-out; transform: translate(10px,10px); } .cat-box { background-color: grey; outline: #ddd8d4 solid 3px; padding: 3px 5px 5px 5px; margin: 10px 30px 10px 30px; transition: 0.3s ease-in-out; } you can in similar way answer linked to, using multiple box-shadow declarations. i took liberty of converting outline border , setting box-sizing: border-box border doesn't stick out effect. here live demo: .bot-row:hover { trans...

repetitive value assignment in a while loop, Python -

please @ following while loop code written in python: x=25 epsilon=0.01 high=max(1.0,x) low=0.0 *ans=(low+high)/2.0* while abs(ans**2-x)>=epsilon: if ans2>x: high=ans else: low=ans *ans = (high + low)/2.0* print("ans:",ans,) this guess loop (exhaustion), should find approx square root of positive number within margin error on 0,01. cant understand why must define ans (ans=(low+high)/2.0) second time, first before loop , again in loop. tell me purpose second definition have since im seeing first 1 being enough? thanks arif it's because need perform calculation on each iteration of loop including first iteration. since while test first part of loop, need once before loop starts. here's way 1 statement: while true: *ans = (high + low)/2.0* if abs(ans**2-x)>=epsilon: break if ans2>x: high=ans else: low=ans

lag - Eclipse Mars running slow -

i running mac os x el capitan. eclipse running slow. scrolling. using macbook's trackpad. macbook retina 13" 2015 8 gb ram, intel i5 (two cores @ 2.7 ghz) this has been driving me nuts! seems there bug in eclipse causes lag when redrawing editors when os x using "automatic scrollbars" (see system settings). i found when changing setting show scroll bars, scrolling performance in eclipse improved. however, automatic scrollbars, came hack: fire terminal write defaults write -app eclipse appleshowscrollbars always , , scrollbars show eclipse, not other applications. i hope can others out there too, until problem receives proper fix :-)

Android Sorting ListView -

i have several arraylists going listview adapter. i'm trying sort 1 of arraylists ... names = new arraylist<string>(); locations = new arraylist<string>(); timedates = new arraylist<string>(); //arraylists populated here adapter = new homeadapter(getactivity(), names, locations, timedates); setlistadapter(adapter); how go sorting entire listview timedates example? appreciate help. thanks! you have use datamodel 1 arrylist. details given bellow: arraylist= new arraylist<datamodel>(); //arraylists populated here adapter = new homeadapter(getactivity(), arraylist); setlistadapter(adapter); datamodel class this: public class datamodel { public string names; public string locations; public string timedates; } finally sorting: collections.sort(arraylist, new sortlist()); public class sortlist implements comparator<datamodel> { public int compare(datamodel arg0, datamodel arg1) { ...

database - Rails Migrate data to mysql workbench GUI -

so trying migrate local database mysql workbench database gui on mac. in rails app: config/database.yml default: &default adapter: mysql pool: 5 timeout: 5000 username: root port: 3306 development: <<: *default database: db/development.sqlite3 my guess need change path database . i've changed adapter sqlite3 mysql but i'm sure there more configuration needed here... what necessary steps connect mysql workbench rails application can manage tables? found needed done. in database.yml , changed database in development environment generic name demo_development : default: &default adapter: mysql pool: 5 timeout: 5000 username: root port: 3306 development: <<: *default database: demo_development dumped existing database in development.sqlite2 ran rake db:create migrated database rake db:migrate , that's it, took @ mysql workbench gui , tables there. easy ;)

C++ basic setup for using openGL -

i have windows 8.1 os. wanted run basic c++ program using opengl downloaded compatible turbo c++ software of 64 bit. when run program got errors because said unable open header file i.e., graphics library . there primary things setting path in environmental variables, url should paste? or let me please know if there's other common things need set in-order use graphics library. thank you. do not use turbo c/c++ , try modern ide (codeblock , codelite , dev-c++ or other). read http://www.codeblocks.org/downloads/26 in ide common header files plus examples , opengl example here . suggest try codeblock. why not use turbo c/c++ ( https://stackoverflow.com/a/1962710/4499919 )

How to rename root and children element XSLT -

how rename root 'channel' , children 'item' 'records' , 'record' respectively? input <?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/atom"> <channel> <item> <title>a</title> <link>/news/view/25857/a.html</link> <guid ispermalink="true">/news/view/25857/a.html</guid> <comments>/news/25857/a.html</comments> <pubdate>sat, 03 oct 2015 00:42:42 gmt</pubdate> <description><![cdata[]]></description> <category>headline,hacker,bank,cybercrime,data loss,fraud</category> </item> </channel> </rss> xslt <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes...

javascript - Angular Datatable ng-click not working -

got problem ng-click on angular datatables. i'm using https://l-lin.github.io/angular-datatables here code $scope.dtoptions = dtoptionsbuilder.fromfnpromise(function(){ return $resource(apiroot + 'categories').query().$promise; }) .withoption('order', [0, "asc"]); $scope.dtcolumns = [ dtcolumnbuilder.newcolumn('id', 'id').withoption('searchable', false), dtcolumnbuilder.newcolumn('name', 'name'), dtcolumnbuilder.newcolumn('', 'actions').renderwith(function (data, type, full, meta) { return '<a class="btn btn-default btn-xs" href="#/edit/' + full.id + '"><i class="fa fa-pencil"></i></a> ' + '<button class="btn btn-danger btn-xs" ng-click="deleteitem(' + full.id + ')"><i class="fa fa-trash">...

ios - TextField text hides when typing -

when typing in textfield.some times textfield internal part moves when typing , text visible when focus removed textfield. occur times when occurs textfield of apps behave this. solution remove bug?. no steps found reproduce bug. occur randomly while using in iphone.

Send Large Files like ISO via Java REST -

i creating rest service send large files such iso image,but getting out of memory error,below code @requestmapping(value = uriconstansts.get_file, produces = { "application/json" }, method = requestmethod.get) public @responsebody responseentity getfile(@requestparam(value="filename", required=false) string filename,httpservletrequest request) throws ioexception{ responseentity respentity = null; byte[] reportbytes = null; file result=new file("/home/xxx/xxx/xxx/dummypath/"+filename); if(result.exists()){ inputstream inputstream = new fileinputstream("/home/xxx/xxx/xxx/dummypath/"+filename); string type=result.tourl().openconnection().guesscontenttypefromname(filename); byte[]out=org.apache.commons.io.ioutils.tobytearray(inputstream); httpheaders responseheaders = new httpheaders(); responseheaders.add("content-disposition", "attachment; filename=" + filename)...

How to check if a string is unique in a file and if it is write to another file in C#? -

i have 2 files f1.txt , f2.txt. f1.txt contains contents like u1,u2 u1,u5 u3,u4 u2,u1 u3,u4 essentially u1,u2 , u2,u1 mean same . want write distinct contents file f2.txt i.e. after writing f2.txt should contain u1,u2 u1,u5 u3,u4 i tried below did not work out. using system; using system.collections.generic; using system.io; using system.linq; using system.text; using system.threading.tasks; namespace stringinfiletechchef { class program { static void main(string[] args) { string line = ""; using (streamreader sr = new streamreader(@"c:\users\chiranjib\desktop\f1.txt")) { while((line=sr.readline()) !=null) { if (!file.readalltext(@"c:\users\chiranjib\desktop\f2.txt").contains(line)) { //char[] array = line.tochararray(); //array.reverse(array); ...

C# Proxy Server: how to send/receive data with sockets? -

i'm trying create simple proxy server in c#. below portion of code created socket host name parsed browser http request. full request in string "header" , sent destination socket. while loop receives response socket , sends client socket. socket destserversocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); destserversocket.connect(host, 80); destserversocket.send(asciiencoding.ascii.getbytes(header)); byte[] response = new byte[1]; while (destserversocket.receive(response) != 0) { client.send(response); } destserversocket.disconnect(false); destserversocket.dispose(); client.disconnect(false); client.dispose(); right proxy works simple html sites. else , endlessly loads without ever displaying content in browser. how alter code allow proxy server work on websites more complex basic html ones?

java - How do i programmatically change file permissions? -

in java, i'm dynamically creating set of files , i'd change file permissions on these files on linux/unix file system. i'd able execute java equivalent of chmod . possible java 5? if so, how? i know in java 6 file object has setreadable()/setwritable() methods. know make system call this, i'd avoid if possible. full control on file attributes available in java 7, part of "new" new io facility ( nio.2 ). example, posix permissions can set setposixfilepermissions() . in earlier versions of java, using native code of own, or exec -ing command-line utilities common approaches.

javascript - HTML section and div fixed size -

i'm trying fix height of div inside section 100px. however, no matter try, height reverts 'auto' , re-sizes depending on amount of content in div. here's html code: <section id="social" class="tab-content active"> <div id = "socialdiv"></div> </section> and here's i've tried far css: social{height:100px; line-height:20px;overflow:hidden;} .socialdiv{height:100px !important; line-height:20px;overflow:hidden;} jquery: $('.socialdiv').css({'height':100+'px'}); $('.socialdiv').height( 100 ); unfortunately none of these work. i'd appreciate , on this. ps. don't know if matter or not, part of chrome extension , section part of popup window displays during execution. you mixing id ( # ) class ( . ) your class tab-content you're trying change id social on both js , css. try: $('.tab-content').css({'height':100+...

html - How to pass hidden values using form in jsp -

my code follows <form method="post" action="answer.jsp"> <input type="submit" value="answer"> <%string q_id=rs.getstring("q_id"); %> <input type="hidden" value="<%out.print(q_id);%>"> </form> i want pass q_id page answer.jsp got value of q_id didn't understand how pass (or using different method) value? in jsp form you'll need <form method="post" action="answer.jsp"> <input type="hidden" name="q_id" value="<%= rs.getstring("q_id") %>"> <input type="submit" value="answer"> </form> then can receive q_id in answer.jsp as <p>question id: <%= request.getparameter("q_id") %></p> or, using jsp el (recommended) <p>question id: ${param.q_id}</p>

Prolog: averages of items in two lists at corresponding indices -

i working on prolog program take 2 lists, calculates average of elements @ corresponding indices , returns averages list. this code. i'm getting is/2: arguments not sufficiently instantiated error. sum(h,t,s) :- s h + t. avelists([],[],_). avelists([head|tail],[head2|tail2],[x|tail3) :- x sum(head,head2,a)/2, avelists(tail,tail2,tail3). for example: ?- avelists([1,4,3],[3,6,5],xs]). xs = [2,5,4]. % expected result why not working , giving me error? looks me should work. if use separate predicate calculate sum, need evaluate before using answer: sum(a, b, sum), mean sum / 2 there problem pointed out in other answer . what want: list1_list2_means([], [], []). list1_list2_means([x|xs], [y|ys], [m|ms]) :- m (x + y) / 2, list1_list2_means(xs, ys, ms). you save typing writing helper predicate finds mean of 2 numbers: x_y_mean(x, y, m) :- m (x + y) / 2. then, can use maplist : ?- maplist(x_y_mean, l1, l2, ...

python - CSRF verification error on GET form method -

i getting error csrf verification failed. request aborted. when trying submit form. have used method, yet getting error. have added {% csrf_token %} token also, sure, error still there. sample html: <body> <form action="/entry/" method="get" name="form1"><br> {% csrf_token %} <select name="date" size="1"> <option>30</option> </select> &nbsp; <select name="month"> <option>09</option> </select> <select name="year"> <option>2015</option> </select> <input id="save" style="height: 50px; width: 100px;" type="submit" value="save"></form> </body> views.py file def getuser(request): return render(request, 'index.html') def putrecord(request)...

codeigniter - Pass data through form by onclick -

this should simple can't it. i want pass particular field value controller function through onclick by form submit <form action="<?php echo base_url();>data/pass" method="post"> <select name="name1" id="name1" onclick="" class="m-wrap" > <option selected="selected" disabled="disabled">select</option> <option value="1">by year</option> </select> <form> please me. change code this <form action="<?php echo base_url();?>data/pass" method="post"> <select name="name1" id="name1" onchange="this.form.submit()" class="m-wrap" > <option selected="selected" disabled="disabled">select</option> <option value="1">by ...

validation - How manage error handling in Controller/Repository and show errors in View in Asp.Net Core MVC -

i have created asp.net core mvc application. i create example form updating user , catch specific exceptions , show them in form. i want catch 2 types of exceptions/errors: 1) form validation 2) repository exceptions i have following code: userrepository public async task<userdto> updateuserasync(userdto user) { var useridentity = await _usermanager.findbyidasync(user.id.tostring()); if (useridentity == null) throw new userfriendlyexception("user not exist"); useridentity.mapto(user); await _usermanager.updateasync(useridentity); var userdto = useridentity.tomodel(); return userdto; } user controller [httppost] public async task<iactionresult> user(userdto user) { //model not valid if (!modelstate.isvalid) { return view(user); } try { ...

Image is not retrieved in controller in laravel -

$this->validate($request,[ 'title'=>'string|required', 'image.*'=>'required|image|mimes:jpeg,png,jpg,gif' ]); $image=$request->image; return response()->json($image); the image not showing file in controller of laravel 5.3

java - Android: Ignoring custom gesture direction (GestureOverlayView) -

i don't know if problem if solvable or if impossible avoid. have application many custom gestures (created me , not user) , there simple gestureoverlayview in layout. want overlayview when recognizing gestures ignores direction of this. example: have diagonal gesture; inserted in application drawing left-bottom angle right-top. can magic trick allows user swipe right-top left-bottom , overlayview recognized anyway gesture? i'd avoid create 2 gestures every gesture (in example 2 gestures of diagonal line 1 bottom , 1 top) same effect because there lot of work because not few. time

html - The select option menu in chrome browser is not aligned similar with the select option -

the select option in chrome browser aligned left while other browser working well. want aligned without moving right. how want solve problem? chrome browser image

c# - Remove item from DropDownList by value using javascript -

i have following dropdownlist. @html.dropdownlist("attractionsavaiableattractions", model.avaiableattractions) i use script access dropdownlist located id td element. how can remove item dropdownlist by value not selected item? $(document).ready(function () { var table = document.getelementbyid('timetableattractions'); var rowlength = table.rows[0].length; var row = table.rows[0]; (var y = 1; y < row.cells.length; y++) { var $td = $(row.cells[y]).closest("td"); var itemtoremove = 'example'; $td.find("[name^='attractionsavaiableattractions']").remove(itemtoremove); } }); please try, var itemtoremove = 'example'; $("[name='attractionsavaiableattractions '] option[value='"+itemtoremove+"']").remove(); where attractionsavaiableattractions name of dr...

algorithm - Custom function failing to convert a decimal to single precision floating point -

here code attempting convert real number approximate single precision floating point representation, educational purposes demonstrate intermediate results: function [ieee] = mydec2ieee (d) % accepts decimal number, d. % returns 1x32 bit array holding closest ieee representation. s = getsign(d); [e, f] = getcharacteristic(d); binarye = binstr2binarr(dec2bin(e)); % convert binary integer array. if numel(binarye) < 8 % extend exponent bits number. binarye = [zeros(1, 8 - numel(binarye)), binarye]; end binaryf = expandfractiontobinary(f); ieee = [s , binarye, binaryf]; end function [b] = binstr2binarr (s) % accepts binary character string, s. % returns binary integer array, b. len = numel(s); b = zeros(1, len); = 1 : len b(i) = s(i) - '0'; end end function [b] = expandfractiontobinary(f) % accepts has remained decimal number % after calculation of exponent, i.e fractional part. % retur...

elasticsearch - Conditional geo-location based search of documents with aggregation -

my document schema looks this: { "store_id": 123, "franchise_id": 1, "name": "test", "location": "1.2,1.3" } my use case revolves around finding stores. store can part of franchise or can independent (franchise_id = store_id). there can multiple different stores part of franchise , using franchise_id field identify store belongs franchise. while searching store name , user location, want de-duplicate results based on franchise id. now given location, distance range , name of store input want find stores grouped franchise_id such either get documents lie within range or if no store present within range franchise_id the store doc minimum distance specified location i've tried out reading aggregations not able figure out. appreciated. you can group/deduplicate stores franchise_id using terms aggregation , within top hits aggregation. see https://www.elastic.co/guide/en/elasticsearc...

matlab - How to remove the loop. (Vectorization) -

i trying remove "for" loop following matlab code. know not necessary in case, think if understand case, in future able apply same concept more complex case in necessary. clear all; close all; clc; u = @(n) (n>=0)*1.0; % step function n = -5:25; x_a = zeros(size(n)); m = 0:10 % loop want remove x_a = x_a + (((-1)^m)*u(-n+(2*m)))-(((-0.5)^(m+1))*(u(n-(2*m)))); end figure(1); stem(n,x_a); grid; xlabel('sample number'); ylabel('amplitude x_a[n]'); thanks attention. reshape m 3d matrix. apply same formula , results each m in 3d slices. sum on third dimension. m = reshape(0:10,1,1,[]); x_a = sum((((-1).^m).*u(-n+(2.*m)))-(((-0.5).^(m+1)).*(u(n-(2.*m)))),3);

sql server - How to avoid going throw (select case when)- cases that takes a lot of time -

i must work bank-statements means have work big string , cut small parts able order every line bills belongs. far good. problem patindex , charindex , substring take lot of time when has work "big data". example, have 100 (string) lines in bank statement have able order every line right bill. 100 lines, there 90% simple cases not take time because simple substring work. rest of 10%, there lot of work takes time. problem if select case when sql-code takes same time in case have 100% of lines complicated or 5% of them. means each line whole code evaluated , right decision taken problem. how can avoid this? select case when @var = 'bla' do-something takes 10 min evaluated when @var = 'john' do-something takes 5 min evaluated when @var = 'sarah' do-something takes short time else do-somethig takes 10 min evaulated. now when data 4000 lines 'sarah' in of them takes same time if data 'bla' takes lot of time. means cases every ti...

python - Unable to disable CSRF check in django 1.10 -

i using django-1.10 project , want o disable csrf check in project. did created csrfdiable middleware , added in middlewares after commonmiddleware . same process worked me in django 1.8 in django 1.10 not working. tried removing django.middleware.csrf.csrfviewmiddleware doesn't work me. middleware class below class disablecsrf(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): setattr(request, '_dont_enforce_csrf_checks', true) middleware = [ 'django.middleware.security.securitymiddleware', 'django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'common.middlewares.disablecsrf', # 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', ...

ios - How to create custom MDCTabBarViewController programatically? -

i'm using mdctabbarviewcontroller subclass custom mdctabbar implementation, however, tabs in tabbar not showing selection indicator. when tabs selected, image icon of tab shifts in vertical direction. here link of demo project: custom mdctabbarviewcontroller project

ios - Swift 3 Instance member type -

i have func savenotes() sub-class of nsobject note.swift file func savenotes() { var adictionaries:[nsdictionary] = [] i:int in 0 ..< allnotes.count { adictionaries.append(allnotes[i].dictionary()) } userdefaults.standard.set(adictionaries, forkey: kallnotes) } when try run project error "instance member 'savenotes' cannot used on type 'note'; did mean use value of type instead. code masterviewcontroler.swift import uikit import foundation class masterviewcontroller: uitableviewcontroller { var objects = nsmutablearray() override func viewdidload() { note.loadnotes() print("allnotes: \(allnotes)") var n:note = note() note.savenotes() not sure i'm doing wrong here. help. the error of: instance member 'savenotes' cannot used on type 'note'; did mean use value of type instead. is shown compiler because tryin...

android - Ionic vibration not working -

that question old i've found no working answer in of similar questions. basically, have code in app.js: angular.module('starter', ['ionic', 'ngcordova']) .run(function($ionicplatform) { $ionicplatform.ready(function() { if(window.cordova && window.cordova.plugins.keyboard) { cordova.plugins.keyboard.hidekeyboardaccessorybar(true); cordova.plugins.keyboard.disablescroll(true); } if(window.statusbar) { statusbar.styledefault(); } }); }) .controller('testctrl', function($scope, $cordovavibration){ $scope.test = function(){ $cordovavibration.vibrate(1000); }; }); i'm trying make phone vibrate pressing button using function test on controller. function being called correctly, phone doesn't vibrate. the project builds without errors, , apparently cordova plugin fine. phone not muted. idea of doing wrong?

html - CSS - Position an element in percent from its own width -

Image
i position center of element (regardless of height) on bottom of parent. thought i'd go absolute nothing makes sense. see picture below : <div id="red"> <div id="blue"></div> </div> how can have result ? edit : @gaby aka g. petrioli found solution : #red{ width: 300px; height: 200px; background: red; position:relative; } #blue{ width: 100px; height: 50px; background: blue; right:3%; /* here magic solution*/ position:absolute; bottom: 0; transform: translatey(50%); } <div id="red"> <div id="blue"></div> </div> you should use absolute position place @ bottom, , use transform translate move 50% upward since work in regard own height. so .red{position:relative} .blue{ position:absolute; top:100%; right:50px; transform:translatey(-50%); }

apache spark - Combine output of parallel operations using Scala -

the following snippet of code processes filters in parallel , write out individual files output directory.is there way 1 large output file? array( (filter1, outputpathbase + filename), (filter2, outputpathbase + filename), (filter3, outputpathbase + filename) ).par.foreach { case (extract, path) => extract.coalesce(1).write.mode("append").csv(path) } thank you. you can reduce array single rdd union them, parallelize execution of each filter* spark val rdd = array( filter1 filter2, filter3).reduce(_.union(_)) rdd.write.mode("append").csv(path) there no need in case convert array pararray i assuming filter1 , filter2 , filter3 of same type rdd[t]

javascript - Refer to primitive DOM element class -

👋 for example, want this: const dynamiccomponent = condition ? mycomponent : react.div; const useddynamiccomponent = <dynamiccomponent> how cool? </dynamiccomponent>; what use there instead of react.div , thing made up? const dynamiccomponent = condition ? mycomponent : <div>{this.children}</div>; const useddynamiccomponent = <dynamiccomponent> how cool? </dynamiccomponent>;

php - Laravel task scheduler not working for specified time range -

i have laravel 5 task scheduling run between specified time range every day: $schedule->call(function () { // task omitted })->daily()->timezone('europe/london')->between('14:00', '15:00'); this not work, if change run every minute using everyminute(); run successfully: $schedule->call(function () { // task omitted })->everyminute(); my cron on server set run every half hour it's shared hosting can't run less half hour: 0,30 * * * * /usr/local/bin/php -q /home/username/public_html/bookings/artisan schedule:run >> /dev/null 2>&1 anyone know why first cron job: daily()->timezone('europe/london')->between('14:00', '15:00'); not running? you have conflicting rule. https://laravel.com/docs/5.5/scheduling daily() sets task run daily @ midnight. between() limits task run between hours (basically secondary ...

Python ~ffmpeg 5_second_video.mp3: No such file or directory Conversion failed -

here python code : call(['ffmpeg', '-loop', '1', '-y', '-i', '5_second_video.jpg', '-i','5_second_video.mp3' , '-acodec', 'copy', '-vcodec', 'libx264', '-shortest', song +'.mp4'], shell=false) there file called 5_second_video.mp3 in desktop returning me error 5_second_video.mp3: no such file or directory conversion failed! the problem solved changing '-o '+song2file(song)+'.%(ext)s' '-o'+song2file(song)+'.%(ext)s' . space problem.

ios - I set "Allow Arbitrary Loads" with "YES" , But getting HTTP load failed (kCFStreamErrorDomainSSL, -9806) -

i have following setting in project info.plist: <key>nsapptransportsecurity</key> <dict> <key>nsallowsarbitraryloads</key> <true/> </dict> but still getting following error vodafone mobile data: nsurlsession/nsurlconnection http load failed (kcfstreamerrordomainssl, -9806) error details: error domain=nsurlerrordomain code=-1200 "an ssl error has occurred , secure connection server cannot made." userinfo={_kcfstreamerrorcodekey=-9806, nslocalizedrecoverysuggestion=would connect server anyway?, nsunderlyingerror=0x17004dfb0 {error domain=kcferrordomaincfnetwork code=-1200 "(null)" userinfo={_kcfstreampropertysslclientcertificatestate=0, _kcfnetworkcfstreamsslerrororiginalvalue=-9806, _kcfstreamerrordomainkey=3, _kcfstreamerrorcodekey=-9806}}, nslocalizeddescription=an ssl error has occurred , secure connection server cannot made., nserrorfailingurlkey= https://v1.xyz.net:8080/signup/ , nserrorfaili...

ajax - php response is not sent before the script ends -

i issue ajax post method send commands php backend. 1 one these "reboot". i'm trying answer before script ends: <?php set_time_limit(0); $json = file_get_contents('php://input'); $obj = json_decode($json); switch ($obj->{'action'}) { case "reboot": $data = '{"success" : true}'; ob_start(); header('content-type: application/json'); echo json_encode($data); ob_end_flush(); ob_flush(); flush(); exec("sudo reboot"); break; default: $data = '{"success": "fail"}'; break; } the ajax call (on client side) times out , never receives answer. of course can add small delay reboot command, want understand why code not working. i'm running on rpi lighttpd , fast-cgi. you can define cron job run on every second , check setting, reboot or of like. if that's true, reboot issued. script issued ajax call set setting ...

pandas - Python: how to pick specific entries in the data as the columns -

Image
this code: df= pd.read_csv("mort2015.csv", usecols=['sex', 'placdth', 'ager52','ucr130', 'ranum','record_1','record_2','record_3','record_4','record_5', 'record_6','record_7','record_8','record_9','record_10','record_11']) bothsex=(df[(df).ager52<12]).drop(['ucr130', 'ager52', 'ranum','placdth', 'sex'], axis=1) then tried with: pivotrows=(bothsex.apply((pd.value_counts), axis=1)) gives me count. as picture shows below, trying pick specific entries create new columns. example 'g039', 'p529' , 'q798' columns. in addition, trying use "table" run ols regression find/show correlation between diseases (ex. g039, p529)and gender. problem don't understand how go ahead results want. picture of table

python - Application closes when it's hidden and I close a modal dialog -

this question has answer here: pyqt system tray icon exit when click menu item 1 answer i'm developing application "run in tray" of time, , displays dialogs user (these dialogs modal) the problem i've run when user closes dialog (using accept() or reject() ) while main window (the parent of modal dialog) hidden whole application closed! there no problem modeless dialogs the workaround i'm using call show() on parent (the main window) first , after close modal dialog is there better way solve or avoid problem? or approach i'm using way deal issue? i'm using pyqt 5.7.1 (same qt version) , running on lubuntu 16.04 64-bit grateful help! you need set quitonlastwindowclosed property on qapplication object false , show below:: if __name__ == '__main__': import sys app = qapplication(sys.argv) i...

android - Crash getting many data from firebase -

i'm populating recyclerview (not firebaserecyclerview) data coming firebasedatabase. data receive many, users, , can reach many thousands. when receive data app lagges , crashes. know there many data , it's hard work. there way optimize all? i have errore in logcat the application may doing work on main thread i'm not impressed, ask for possible solutions! thank you recyclerview = (recyclerview) findviewbyid(r.id.friend_list2); //recyclerview.setlayoutmanager(new linearlayoutmanager(getapplicationcontext())); recyclerview.setlayoutmanager(new gridlayoutmanager(this, 2)); final databasereference mpostreference = firebasedatabase.getinstance().getreference().child("user-profile"); mpostreference.addlistenerforsinglevalueevent(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { username = new arraylist<>(); uid = new arraylist<string>(); ...

linux - How to track erros listed in ppd files? -

i've found in ppd file listed lot more errors can access using cups console interface. example part of kyocera ecosys p2135dn 3.5 printer ppd file *% status (format: %%[ status: <one of these> ]%% ) *status: "warming up"/warming *status: "idle"/idle *status: "busy"/busy *status: "waiting"/waiting *status: "printing"/printing *status: "initializing"/initializing *status: "printing test page"/printing test page *% printer error (format: %%[ printererror: <one of these> ]%% ) *printererror: "paper entry misfeed" *printererror: "cover open" *printererror: "no paper tray" *printererror: "out of paper" *printererror: "toner low (halt)" *printererror: "warming up" *printererror: "other reason" *printererror: "video interface mode" *printererror: "offline" *printererror: "toner low (warning)...

android - On clicking button the selected RadioButton state in RadioGroup should saved in SharedPreferences using Fragments -

fragment activity contains radiogroup having 5 radiobuttons , button.radiobutton5 have edittext it. public void oncreate(bundle savedinstancestate) { radio1 = preferencemanager.getdefaultsharedpreferences(getactivity()).getboolean("radio1", false); radio2 = preferencemanager.getdefaultsharedpreferences(getactivity()).getboolean("radio2", false); radio3 = preferencemanager.getdefaultsharedpreferences(getactivity()).getboolean("radio3", false); radio4 = preferencemanager.getdefaultsharedpreferences(getactivity()).getboolean("radio4", false); radio5 = preferencemanager.getdefaultsharedpreferences(getactivity()).getboolean("radio5", false); str_rbtext = preferencemanager.getdefaultsharedpreferences(getactivity()).getstring("selected_rb_msg", "nomi"); msgtosend = preferencemanager.getdefaultsharedpreferences(getactivity()).getstring("msgtosend", ""); super.oncreat...