Sunday, October 1, 2017

How to lock UISearchBar in place to superview

Leave a Comment

I am using the UISearchController alongside its UISearchBar. The UISearchController alongside its UITableView is placed inside a subview in my main view.

My goal is to lock the UISearchBar in its place so when its active, it does not move. Right now the following is happening:

enter image description here enter image description here

I have searched this issue extensively and have tried the following such as:

  1. self.searchController.hidesNavigationBarDuringPresentation = false, which just abruptly moves the search bar to the middle of the screen.

  2. definesPresentationContext = true, which does not change behavior

  3. self.extendedLayoutIncludesOpaqueBars = true, which does not change behavior

  4. Using the UIBarPositioningDelegate method mentioned here, which strangely cannot be translated to Swift because I cannot insert the AnyObject<UIBarPositioning> as it is in the Objective C version and still have it recognized as the override function

Any suggestion is appreciated.

Edit:

Here is the setup for the search items:

    searchController.searchResultsUpdater = self     searchController.dimsBackgroundDuringPresentation = false     definesPresentationContext = true     searchTableView.tableHeaderView = searchController.searchBar 

1 Answers

Answers 1

Set your TableView's Style property to Plain in the Storyboard and use the SearchBar as the section header view. Along with the following code, I commented out tableView.tableHeaderView = searchController.searchBar in Apple's "Table Search with UISearchController" example and it worked fine.

override func numberOfSections(in tableView: UITableView) -> Int {     return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {     return searchController.searchBar.frame.size.height } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {     return searchController.searchBar } 
Read More

How can I keep a row of a button and text from wrapping using multicol?

Leave a Comment

I have a series of rows consisting of a button and text, like so:

[Button] [Text] [Button] [Text] [Button] [Text] ... 

When I apply the multicol class, they eventually wrap around, like so:

[Button] [Text]   [Button] [Text] [Button] [Text]   .... 

Unfortunately, in many cases, the button or the text gets broken in half when going into the next column. Using "display: inline-block" makes my buttons and text vary in size on different screen resolutions, and makes them spaced strangely.

What is the best way to keep the [Button] [Text] combination from breaking in the column, while keeping each [Button] [Text] combination equally spaced, and looking the same?

.multicol {    column-count:2;    -moz-column-count:2;    -webkit-column-count:2;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">    <!-- Imagine 20-25 of these in a row -->    <div class='multicol'>       <div class='row'>           <div class='col-xs-5'>                <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>            </div>            <div class='col-xs-7'>                 <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>             </div>        </div>    </div>

1 Answers

Answers 1

First of all, added white-space: normal to the button to override the default nowrap from bootstrap's btn class.

Unfortunately, in many cases, the button or the text gets broken in half when going into the next column. Using "display: inline-block" makes my buttons and text vary in size on different screen resolutions, and makes them spaced strangely.

Well, you can avoid the breaking to the next column by using:

-webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */ page-break-inside: avoid; /* Firefox */ break-inside: avoid; /* IE 10+ */ 

and makes them spaced strangely

Add column-gap: 0 to remove the default column gaps.

.multicol {    column-count: 2;    -moz-column-count: 2;    -webkit-column-count: 2;    column-gap: 0;  }    .multicol button {    white-space: normal;  }    .multicol>.row {    -webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */    page-break-inside: avoid; /* Firefox */    break-inside: avoid; /* IE 10+ */  }    /*for illustration*/  .multicol>.row>* {    border: 1px solid;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  <!-- Imagine 20-25 of these in a row -->  <div class='multicol'>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>  </div>

Now you can add in some flexboxes here to suit your case - see demo below:

.multicol {    column-count: 2;    -moz-column-count: 2;    -webkit-column-count: 2;    column-gap: 0;  }    .multicol button {    white-space: normal;  }    .multicol>.row {    display: flex; /*NEW*/    margin: 0; /*NEW*/    -webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */    page-break-inside: avoid; /* Firefox */    break-inside: avoid; /* IE 10+ */  }    .multicol p { /*NEW*/    height: 100%;  }    /*for illustration*/  .multicol>.row>* {    border: 1px solid;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">  <!-- Imagine 20-25 of these in a row -->  <div class='multicol'>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>    <div class='row'>      <div class='col-xs-5'>        <button class='btn btn-block' style='min-width: 100px;'>  (VARYING-LENGTH BUTTON NAMES HERE) </button>      </div>      <div class='col-xs-7'>        <p> (VARYING-LENGTH DESCRIPTIONS HERE) </p>      </div>    </div>  </div>

Read More

Using scatter_nd_add op inside a while loop?

Leave a Comment

I'm trying to do a tf.scatter_nd_add inside a tf.while loop. It gives me an error message though.

TypeError: 'ScatterNdAdd' Op requires that input 'ref' be a mutable tensor (e.g.: a tf.Variable) 

It seems like the way that while loops work is that it changes the input variable from being of type tf.Variable to having some other type. Is it possible to do a scatter_nd_add op inside a while loop?

Here's a code excerpt:

self.hough = tf.Variable(tf.zeros((num_points, num_points), dtype=tf.float32),                              name='hough') self.i = tf.constant(0) c = lambda i, hough: tf.less(i, tf.squeeze(tf.shape(self.img_x))) b = lambda i, hough: self.ProcessPixel(i, hough) self.r = tf.while_loop(c, b, [self.i, self.hough], back_prop=False) 

This is the body of the loop:

def ProcessPixel(self, i, hough):         pixel_x, pixel_y = self.img_x[self.i], self.img_y[self.i]         result = self.GetLinesThroughPixel(pixel_x, pixel_y)         idx = tf.stack([tf.range(num_points, dtype=tf.int64), result])         pixel_val = self.img[tf.to_int32(pixel_x), tf.to_int32(pixel_y)]          print type(hough)         updated_hough = tf.scatter_nd_add(hough, tf.transpose(idx),                                           updates=pixel_val * tf.ones(num_points))          return tf.add(i, 1), updated_hough 

0 Answers

Read More

Node JS Passport - 400 Bad request for register

Leave a Comment

I try to implement a register on my web app, using Node JS and Passport.js for local authentication, but I have this error when I Post the request on Insomnia (Like Postman) :

Bad Request 

I don't understand because I have follow a tutorial that I find on Google to do this. Here is the route (auth.js):

const passport = require('passport'); const router = require('express').Router(); //const UserController = require('../controller/UserController');  router     // login     .post("/login", passport.authenticate("local", function(req, res, next) {         console.log(req);     }))     // logout     .get('/logout', (req, res, next) => {         req.session.destroy((err) => {             res.redirect('/login')         })     })     // signup     .post("/signup", passport.authenticate("local-register"), (req, res) => {         var userInfo = req.body;     })  module.exports = router;  

Here is Passport.js file :

const bcrypt = require('bcrypt-nodejs'); const db = require("./queries"); const passport = require('passport'); const LocalStrategy = require("passport-local").Strategy  passport.use(new LocalStrategy(authenticate)) passport.use("local-register", new LocalStrategy({passReqToCallback: false}, register))  function authenticate(email, password, done) {     db.one('select * from users where email = $1', email)         .then((user) => {             if(!user || !bcrypt.compareSync(password, user.password)) {                 return done(null, false, {message: "invalid user and password combination"});             }             done(null, user)         }, done); }  function register(email, password, done) {     db.one('select * from users where email = $1', email)         .then((user) => {             if(user) {                 return done(null, false, {message: "An user with this address have already been created."});             }             const newUser = {                 email: email,                 password: bcrypt.hashSync(password),              };             db.none('insert into users(email, password) values($1, $2)', [newUser.email, newUser.password])                 .then((ids) => {                     newUser.id = ids[0]                     done(null, newUser)                 })         }) }  passport.serializeUser(function(user, done) {     done(null, user.id); });  passport.deserializeUser(function(id, done) {     db.one('select * from users where id = $1', id)         .then((user) => {             done(null, user)         }, done); }); 

I'm using Postgresql as DB for this project, with pg-promise package.

And this is the app.js file :

var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var session = require('express-session'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var passport = require('passport') require('./passport');  var index = require('./routes/index'); var usersRoutes = require('./routes/users'); var authRoutes = require('./routes/auth');  var app = express();  // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');  // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(passport.initialize()) app.use(passport.session())  app.use('/', index); app.use(usersRoutes); app.use(authRoutes);  // catch 404 and forward to error handler app.use(function(req, res, next) {   var err = new Error('Not Found');   err.status = 404;   next(err); });  // error handler app.use(function(err, req, res, next) {   // set locals, only providing error in development   res.locals.message = err.message;   res.locals.error = req.app.get('env') === 'development' ? err : {};    // render the error page   res.status(err.status || 500);   res.render('error'); });  module.exports = app; 

Doest anyone know why I have this response ? I try with a post method using email and password on Insomnia,

Thank you !

2 Answers

Answers 1

By default, LocalStrategy expects to find credentials in parameters named username and password. (passport-local on Github).

So you need to edit this line and set usernameField to email

passport.use("local-register", new LocalStrategy({passReqToCallback: false, usernameField: 'email'}, register)) 

Answers 2

In your passport.js file on line 4, ensure you end your line ;

const LocalStrategy = require('passport-local');

You can authenticate your details individually as well

passport.use(new LocalStrategy((email, password, done) => {  User.getUserByEmail(email, (err, email) => {   if(err) throw err;   if(!email){     return done(null, false, {message: 'Incorrect Username/Email'});   }    User.comparePassword(password, user.password, (err, isMatch)=>{     if(err) return done(err);     if(isMatch){       return done(null, email);     } else {       return done(null, false, {message: 'Invalid Password'});     }   }); }) })); 

Try to stick to one way of writing your code, either ES6 or ES5. And when using ES6, I will advise you use 'use strict' to help you thoroughly check your codes for error.

Read More

How to log stack trace on node.js process error event

Leave a Comment

My node process is dying and I can't seem to log to a file when the process exits. It is a long running process invoked directly with node index.js:

// index.js const fs = require('fs');  exports.getAllCars = (process => {     if (require.main === module) {         console.log(`Running process: ${process.getgid()}.`);         let out = fs.createWriteStream(`${__dirname}/process.log`);          // trying to handle process events here:         process.on('exit', code => out.write(`Exit: ${code}`));          return require('./lib/cars').getAllCars();     } else {         return require('./lib/cars').getAllCars;     } })(process); 

Also tried creating event handlers for error, uncaughtException. Nothing works when killing my process manually (with kill {pid}). The file process.log is created but nothing is there. Do writeable streams require a stream.end() to be called on completion?

2 Answers

Answers 1

According to Node.js documentation:

The 'exit' event is emitted when the Node.js process is about to exit as a result of either:

  • The process.exit() method being called explicitly.
  • The Node.js event loop no longer having any additional work to perform.

So, if you start a process that should never end, it will never trigger.

Also, writable streams do not require to be closed:

If autoClose(an option from createWriteStream) is set to true (default behavior) on error or end the file descriptor will be closed automatically.

however, the createWriteStream function opens the file with flag 'w' by default, which means that the file will be overwritten every time (maybe this is the reason why you always see it empty). I suggest to use

fs.appendFileSync(file, data) 

Here are the events that want to listen:

//catches ctrl+c event //NOTE: //If SIGINT has a listener installed, its default behavior will be removed (Node.js will no longer exit). process.on('SIGINT', () => {     fs.appendFileSync(`${__dirname}/process.log`, `Received SIGINT\n`);     process.exit() });  //emitted when an uncaught JavaScript exception bubbles process.on('uncaughtException', 'uncaughtException', (err) => {     fs.appendFileSync(`${__dirname}/process.log`, `Caught exception: ${err}\n`); });  //emitted whenever a Promise is rejected and no error handler is attached to it process.on('unhandledRejection', (reason, p) => {     fs.appendFileSync(`${__dirname}/process.log`, `Unhandled Rejection at: ${p}, reason: ${reason}\n`); }); 

Answers 2

I suggest you put the code in a try catch block to find out whether its the code or some external cause which results in program termination. and then check the log after the event...

try {   //your code  }catch(e) {   console.log(e.stack); } 
Read More

How to query places sorted by distance with lat, lng coordinates in MySQL with bookshelf.js or knex?

Leave a Comment

Is it possible to search nearest places in mysql by using Bookshelf.js, or Knex? And, if yes, how to do it correct?

UPD: I'm not strong with raw mysql queries, and can't find how to search with lat, lng in Bookshelf and knex.

For example, i have places table with:

  • title
  • address
  • lat
  • lng.

What query i should use to get all places in 10 miles radius from Point(lat, lng)?

thanks.

3 Answers

Answers 1

Demo

http://rextester.com/NDOR4479

SQL

SELECT *,        ACOS(SIN(RADIANS(:lat)) * SIN(RADIANS(lat)) + COS(RADIANS(:lat)) * COS(RADIANS(lat))        * COS(RADIANS(lng - :lng))) * 3959 AS distance FROM places WHERE  ACOS(SIN(RADIANS(:lat)) * SIN(RADIANS(lat)) + COS(RADIANS(:lat)) * COS(RADIANS(lat))        * COS(RADIANS(lng - :lng))) * 3959 <= 10 ORDER BY distance; 

Notes

The above uses the Spherical Law of Cosines where :lat and :lng are the latitude and longitude values from Point and 3959 is the Earth radius in miles.

Answers 2

After some research i found working solution:

const {lat, lng} = req.params;  const X1 = +lat - 10,       Y1 = +lng - 10,       X2 = +lat + 10,       Y2 = +lng + 10;   const distanceInMilesSql = `( 3959 * acos( cos( radians(${+lat}) )            * cos( radians( place.lat ) )            * cos( radians( place.lng ) - radians(${+lng}) )            + sin( radians(${+lat}) )            * sin( radians( place.lat ) ) ) ) AS distance          `;  const places = await new Place().query(qb => {     qb.whereBetween('lat', [X1, X2]);     qb.whereBetween('lng', [Y1, Y2]);     qb.column(['*', Bookshelf.knex.raw(distanceInMilesSql)]);     qb.having('distance', '<', 10); }).fetchAll({withRelated: [     'place_specific_fields',     'state',     'media' ]}); 

Answers 3

You don't make it clear in your question, but I believe that the Bookshelf.js library works as a layer above PostgreSQL, which means that you have access to geometric data types. These can make use of these special operations. The search could be entirely SQL based, so without further context I can simply offer the following:

Combine the latitude and longitude into a single data piece of type point (using the decimal form of the latitude and longitude). Here I will refer to that as coord.

With the proper data in order, you can do a query of:

SELECT p.*, (point'(@origin_long,$origin_lat)' <-> `coord`) distance FROM `places` p WHERE circle '((@origin_long, @origin_lat),@radius)' @> `coord` ORDER BY distance; 

If the data structures are set right, this should return a list, ordered by distance, of all pairs of coordinates within a given radius. You can set the coordinates at the top of this function, or maybe even wrap it in a stored procedure (if you don't mind the overhead).

For further reading, I know that PostgreSQL has an "Earth Distance" function as well, so if you are looking to include the calculation of true distance traveled between points, it might be useful!

Read More

Valid numpy arrays produces IndexError:

Leave a Comment

I am working on gfs weather data to plot certain parameters using python and matplotlib. Since it is a grib2 file, I am using wgrib2 for extracting data from file (even though I am aware of pygrib). These extracted variables (lat, lon and temp) are convered in to numpy arrary successfully. I am attaching these lat, lon and data values for your review. Portion of the code I am using for plotting is:-

lat = # load from attached lat file lon = # load from attached lon file data = # load data from data file plt.figure() m = Basemap(projection='mill', lat_ts=10, llcrnrlon=lon.min(), urcrnrlon=lon.max(), llcrnrlat=lat.min(), urcrnrlat=lat.max(),             resolution='c') x, y = m(lat, lon) cs = m.contourf(x, y, data) m.drawcoastlines() m.fillcontinents() m.drawmapboundary() plt.show() 

Now, when I use matplotlib countorf function for plotting, it produces the following error:-

File "wgrib2.py", line 145, in <module>     cs = m.contourf(x, y, data)   File "/usr/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 521, in with_transform     return plotfunc(self,x,y,data,*args,**kwargs)   File "/usr/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 3644, in contourf     xx = x[x.shape[0]/2,:] IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices 

Can someone help me to solve this issue?

Here is the minimal example as requested (actual files are uploaded in above link):-

#!/usr/bin/python2 # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division import os import subprocess import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap  lat = np.loadtxt("lat.txt") lon = np.loadtxt("lon.txt") data = np.loadtxt("data.txt") plt.figure() m = Basemap(projection='mill', lat_ts=10, llcrnrlon=lon.min(), urcrnrlon=lon.max(), llcrnrlat=lat.min(), urcrnrlat=lat.max(),             resolution='c') x, y = m(lat, lon) cs = m.contourf(x, y, data) m.drawcoastlines() m.fillcontinents() m.drawmapboundary() plt.show() 

Edit 1

Uploaded files again.

It appears to be an issue with dimension of the data. The output generate by wgrib2 to numpy array is a single dimension with value of (259920,) for lat, lon and data. I have checked with pygrib and it produces the shape of (720, 361) which leads to 720 x 361 = 259920. Therefore, it seems that I have an issue with the data being converted in to numpy.

1 Answers

Answers 1

Your code does not produce an error on Python 3.5 with basemap 1.1.0, so this should be fixed if you upgrade your basemap. If you are actually running Python 2 (which is suggested by your minimal example), then it may be sufficient to remove division from your __future__ imports.

In particular, this MCVE does not produce an error:

from __future__ import print_function, unicode_literals, division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap  lat = np.linspace(-90, 90, 180) lon = np.linspace(-180, 180, 360) lat, lon = np.meshgrid(lat, lon) data = np.random.randn(360, 180) plt.figure() m = Basemap(projection='mill', lat_ts=10, llcrnrlon=lon.min(), urcrnrlon=lon.max(), llcrnrlat=lat.min(), urcrnrlat=lat.max(),             resolution='c') x, y = m(lon, lat) cs = m.contourf(x, y, data) m.drawcoastlines() m.fillcontinents() m.drawmapboundary() plt.show() 

If for some reason that doesn't work and you want to patch the issue erroring right here, you can go into the basemap source code and change xx = x[x.shape[0]/2,:] to xx = x[int(x.shape[0]/2),:]. What I heard from Ben suggests that if you do this, you're likely to continue to run in to other compatibility problems (possibly right after you make that fix), but it might get this code working for now.

Keep in mind that basemap does not support Python 3, and is deprecated. The core developer of Basemap (Ben Root) is urging users to stop using it, because it's been abandoned and will not be ported to Python 3, even when Python 2 stops receiving security updates in 2020. He suggests using cartopy instead. All this was said by Ben Root at Scipy 2017.

Read More