Text
Simple DataTables flask
I have no experience in web development, and I would like to add data for a table of specified fields with flask, this is my app
from flask import *from flask import jsonifyapp = Flask(__name__)@app.route('/page_test') def page_test(): meas = {"MeanCurrent": 0.05933, "Temperature": 15.095, "YawAngle": 0.0, "MeanVoltage": 0.67367, "VoltageDC": 3.18309, "PowerSec": 0.06923, "FurlingAngle": -0.2266828184, "WindSpeed": 1.884, "VapourPressure": 1649.25948, "Humidity": 0.4266, "WindSector": 0, "AirDensity": 1.23051, "BarPressure": 1020.259, "time": "2015-04-22 20:58:28", "RPM": 0.0, "ID": 1357} return jsonify(meas)if __name__ == "__main__": app.run(debug=True)
and this is my html (templates/view.html)
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-1.12.4.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js"></script><script type="text/javascript" charset="utf8" src="https://editor.datatables.net/extensions/Editor/js/dataTables.editor.min.js"></script><table id="myTable" class="table table-striped" style="width:100%" > <thead> <tr> <th>Time</th> <th>Mean Current</th> <th>Vapour Pressure</th> <th>Mean Voltage</th> <th>Temperature</th> <th>Humidity</th> <th>Bar Pressure</th> <th>RPM</th> <th>Wind Sector</th> <th>Wind Speed</th> <th>Air Density</th> <th>DC Voltage</th> <th>Power Sector</th> <th>Furling Angle</th> <th>Yaw angle</th> </tr> </thead> </table> <script>$(document).ready(function() { $('#myTable').DataTable( { "processing": true, "ajax": "/page_test", // add column definitions to map your json to the table "columns": [ {data: "time"}, {data: "MeanCurrent"}, {data: "VapourPressure"}, {data: "MeanVoltage"}, {data: "Temperature"}, {data: "Humidity"}, {data: "BarPressure"}, {data: "RPM"}, {data: "WindSector"}, {data: "AirDensity"}, {data: "VoltageDC"}, {data: "PowerSec"}, {data: "FurlingAngle"}, {data: "YawAngle"} ] } );});</script>
accessing the url http://127.0.0.1:5000/page_test only have the json file is displayed.
How can I make the script read the data and display the table?
https://codehunter.cc/a/flask/simple-datatables-flask
0 notes
Text
How does Bluebird's util.toFastProperties function make an object's properties "fast"?
In Bluebird's util.js file, it has the following function:
function toFastProperties(obj) { /*jshint -W027*/ function f() {} f.prototype = obj; ASSERT("%HasFastProperties", true, obj); return f; eval(obj);}
For some reason, there's a statement after the return function, which I'm not sure why it's there.
As well, it seems that it is deliberate, as the author had silenced the JSHint warning about this:
Unreachable 'eval' after 'return'. (W027)
What exactly does this function do? Does util.toFastProperties really make an object's properties "faster"?
I've searched through Bluebird's GitHub repository for any comments in the source code or an explanation in their list of issues, but I couldn't find any.
https://codehunter.cc/a/javascript/how-does-bluebirds-util-tofastproperties-function-make-an-objects-properties-fast
0 notes
Text
Using react-router and express with authentication via Passport.js - possible?
So I'm working on a project that incorporates React, Express.js+Passport and Webpack. I understand the concept of pushing everything to a 'master' React component via react-router, then letting it hash out what gets displayed for the given route. That would work great here, I think. To be upfront, I am new to React.
My concerns are:
1) Can I/how can I still use Passport to authenticate my routes? If I understand react-router correctly, I'll have one route in my express app.js file, pointing to, say, a React component named <Application/>. However, Passport needs router.get('/myroute', isAuthenticated, callback) to check the session. Is it still possible to do so with react-router?
2) Furthermore, if this is possible, how do I pass values from the route in Express into my views, in React? I know in a typical view, I could use <%= user %> or {{user}} if I passed that from my route. Is that possible here?
https://codehunter.cc/a/reactjs/using-react-router-and-express-with-authentication-via-passport-js-possible
0 notes
Text
How to Handle Refresh Token When Multiple Requests are going out?
I am using reactjs, mbox and axios and ran into a problem. I have a api that gives out an access token and a refresh token. The access token dies every 20mins and when this happens the server sends a 401 back and my code will automatically send the refresh token out to get a new access token.
Once a new access token is granted that same rejected request will be sent again. Now my code works great until I throw multiple rejects that pretty much could fire all at the same time.
So first request goes off, a 401 is sent back and it gets a new refresh token, well all the other requests will be trying to do the same thing but the other requests will now fail because the refresh token will be used and a new one will be issued to the first request.
This will kick off my code to redirect the user to the login page.
So essentially I am stuck of only have 1 request at a time.
export const axiosInstance = axios.create({ baseURL: getBaseUrl(), timeout: 5000, contentType: "application/json", Authorization: getAuthToken() }); export function updateAuthInstant() { axiosInstance.defaults.headers.common["Authorization"] = getAuthToken(); }function getAuthToken() { if (localStorage.getItem("authentication")) { const auth = JSON.parse(localStorage.getItem("authentication")); return `Bearer ${auth.accessToken}`; } }axiosInstance.interceptors.response.use( function(response) { return response; }, function(error) { const originalRequest = error.config; if (error.code != "ECONNABORTED" && error.response.status === 401) { if (!originalRequest._retry) { originalRequest._retry = true; return axiosInstance .post("/tokens/auth", { refreshToken: getRefreshToken(), grantType: "refresh_token", clientId : "myclient" }) .then(response => { uiStores.authenticaionUiStore.setAuthentication(JSON.stringify(response.data)) updateAuthInstant(); return axiosInstance(originalRequest); }); } else { uiStores.authenticaionUiStore.logout(); browserHistory.push({ pathname: '/login',}); } } return Promise.reject(error); });
Edit
I am having problem that the code I Need to check to resetup authentication is not working when a user copies in a direct url
app.js
<React.Fragment> <Switch> <Route path="/members" component={MemberAreaComponent} /> </Switch> </React.Fragment >
In memberAreaComponent
<Route path="/members/home" component={MembersHomeComponent} />
When I type in http://www.mywebsite/members/home
MembersHomeComponent - componentDidMount runs firstMemberAreaComponent - componentDidMount runs secondAppCoontainer = componentDidMount runs last.
https://codehunter.cc/a/reactjs/how-to-handle-refresh-token-when-multiple-requests-are-going-out
0 notes
Text
How to unnest (explode) a column in a pandas DataFrame?
I have the following DataFrame where one of the columns is an object (list type cell):
df=pd.DataFrame({'A':[1,2],'B':[[1,2],[1,2]]})dfOut[458]: A B0 1 [1, 2]1 2 [1, 2]
My expected output is:
A B0 1 11 1 23 2 14 2 2
What should I do to achieve this?
Related question
pandas: When cell contents are lists, create a row for each element in the list
Good question and answer but only handle one column with list(In my answer the self-def function will work for multiple columns, also the accepted answer is use the most time consuming apply , which is not recommended, check more info When should I ever want to use pandas apply() in my code?)
https://codehunter.cc/a/python/how-to-unnest-explode-a-column-in-a-pandas-dataframe
0 notes
Text
Controlling fps with requestAnimationFrame?
It seems like requestAnimationFrame is the de facto way to animate things now. It worked pretty well for me for the most part, but right now I'm trying to do some canvas animations and I was wondering: Is there any way to make sure it runs at a certain fps? I understand that the purpose of rAF is for consistently smooth animations, and I might run the risk of making my animation choppy, but right now it seems to run at drastically different speeds pretty arbitrarily, and I'm wondering if there's a way to combat that somehow.
I'd use setInterval but I want the optimizations that rAF offers (especially automatically stopping when the tab is in focus).
In case someone wants to look at my code, it's pretty much:
animateFlash: function() { ctx_fg.clearRect(0,0,canvasWidth,canvasHeight); ctx_fg.fillStyle = 'rgba(177,39,116,1)'; ctx_fg.strokeStyle = 'none'; ctx_fg.beginPath(); for(var i in nodes) { nodes[i].drawFlash(); } ctx_fg.fill(); ctx_fg.closePath(); var instance = this; var rafID = requestAnimationFrame(function(){ instance.animateFlash(); }) var unfinishedNodes = nodes.filter(function(elem){ return elem.timer < timerMax; }); if(unfinishedNodes.length === 0) { console.log("done"); cancelAnimationFrame(rafID); instance.animate(); }}
Where Node.drawFlash() is just some code that determines radius based off a counter variable and then draws a circle.
https://codehunter.cc/a/javascript/controlling-fps-with-requestanimationframe
0 notes
Text
Nesting a container component in a presentational component
I'm trying to refactor my app to separate presentational and container components. My container components are just the presentational components wrapped in connect() calls from react-redux, which map state and action creators to the presentational components' props.
todo-list.container.js
import React, {Component} from 'react';import {connect} from 'react-redux';import {fetchTodos} from '../actions/todo.actions';import TodoList from '../components/todo-list.component';export default connect(({todo}) => ({state: {todo}}), {fetchTodos})(TodoList);
todo-list.component.jsx
import React, {Component} from 'react';import TodoContainer from '../containers/todo.container';export default class TodoList extends Component { componentDidMount () { this.props.fetchTodos(); } render () { const todoState = this.props.state.todo; return ( <ul className="list-unstyled todo-list"> {todoState.order.map(id => { const todo = todoState.todos[id]; return <li key={todo.id}><TodoContainer todo={todo} /></li>; })} </ul> ); }};
todo.container.js
import React, {Component} from 'react';import {connect} from 'react-redux';import {createTodo, updateTodo, deleteTodo} from '../actions/todo.actions';import Todo from '../components/todo.component';export default connect(null, {createTodo, updateTodo, deleteTodo})(Todo);
todo.component.jsx
import React, {Component} from 'react';import '../styles/todo.component.css';export default class Todo extends Component { render () { return ( <div className="todo"> {todo.description} </div> ); }};
What I'm trying to figure out is this: I know I should not be embedding the <TodoContainer /> element inside of TodoList because TodoList is a presentational component and it should only nest other presentational components inside of it. But if I replace it with just a <Todo /> presentational component, then I have to map every state prop and action creator prop in TodoListContainer that the Todo component would need and pass them all down the chain manually as props. This is something I want to avoid of course, especially if I start nesting more levels or start depending on more props coming from Redux.
Am I approaching this correctly? It seems that I shouldn't be trying to embed a container component inside of a presentational component in general, because if I can decouple presentational components from Redux, they become more reusable. At the same time, I don't know how else to embed a component that requires access to Redux state/dispatch inside of any other component that has markup.
https://codehunter.cc/a/reactjs/nesting-a-container-component-in-a-presentational-component
0 notes
Text
Django: check whether an object already exists before adding
How do I check whether an object already exists, and only add it if it does not already exist?
Here's the code - I don't want to add the follow_role twice in the database if it already exists. How do I check first? Use get() maybe - but then will Django complain if get() doesn't return anything?
current_user = request.userfollow_role = UserToUserRole(from_user=current_user, to_user=user, role='follow')follow_role.save()
https://codehunter.cc/a/django/django-check-whether-an-object-already-exists-before-adding
0 notes
Text
Django model naming convention
What is the preferred naming convention for Django model classes?
https://codehunter.cc/a/django/django-model-naming-convention
0 notes
Text
Adding resources with jwt_required?
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.
However if I add a resource that has a jwt_required decorator I get this error.
File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])KeyError: 'JWT_DEFAULT_REALM'
Example resource:
class Endpoint(Resource): @jwt_required() def get(self): return {"State": "Success"}
Initialising the app:
app = Flask(__name__)api = Api(app)
Adding the resource:
api.add_resource(resource_class, "/myEndpoint")
The only way I can get it to work is to define the Endpoint class in the same file as the API.
I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.
https://codehunter.cc/a/flask/adding-resources-with-jwt-required
0 notes
Text
How to create list field in django
How do I create a ListField in Django (Python) like the ListProperty property in Google App Engine (Python)? My data is a list like this : 3,4,5,6,7,8.
What property do I have to define and how would I fetch values from it?
https://codehunter.cc/a/django/how-to-create-list-field-in-django
0 notes
Text
How to change the Content of a <textarea> with JavaScript
How would I change the content of a <textarea> element with JavaScript?
I want to make it empty.
https://codehunter.cc/a/javascript/how-to-change-the-content-of-a-textarea-with-javascript
0 notes
Text
Django bulk_create function example
I'm trying to understand bulk_create in Django
This was my original query I'm trying to convert:
for e in q: msg = Message.objects.create( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, billee=batch.user, sender_name=batch.sender_name )
Does that mean doing the following (below) will loop and create all the entries first then hit the database? Is this right?
msg = Message.objects.bulk_create({ Message ( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, billee=batch.user, sender_name=batch.sender_name ),})
https://codehunter.cc/a/django/django-bulk-create-function-example
0 notes
Text
Zoom in on a point (using scale and translate)
I want to be able to zoom in on the point under the mouse in an HTML 5 canvas, like zooming on Google Maps. How can I achieve that?
https://codehunter.cc/a/javascript/zoom-in-on-a-point-using-scale-and-translate
0 notes
Text
changing source on html5 video tag
I'm trying to build a video player that works everywhere. so far I'd be going with:
<video> <source src="video.mp4"></source> <source src="video.ogv"></source> <object data="flowplayer.swf" type="application/x-shockwave-flash"> <param name="movie" value="flowplayer.swf" /> <param name="flashvars" value='config={"clip":"video.mp4"}' /> </object></video>
(as seen on several sites, for example video for everybody)so far, so good.
But now I also want some kind of playlist/menu along with the video player, from which I can select other videos. Those should be opened within my player right away. So I will have to "dynamically change the source of the video" (as seen on dev.opera.com/articles/everything-you-need-to-know-html5-video-audio/ - section "Let's look at another movie") with Javascript. Let's forget about the Flash player (and thus IE) part for the time being, I will try to deal with that later.
So my JS to change the <source> tags should be something like:
<script>function loadAnotherVideo() { var video = document.getElementsByTagName('video')[0]; var sources = video.getElementsByTagName('source'); sources[0].src = 'video2.mp4'; sources[1].src = 'video2.ogv'; video.load();}</script>
The problem is, this doesn't work in all browsers. Namely, in Firefox there is a nice page where you can observe the problem I'm having: http://www.w3.org/2010/05/video/mediaevents.html
As soon as I trigger the load() method (in Firefox, mind you), the video player dies.
Now I have found out that when I don't use multiple <source> tags, but instead just one src attribute within the <video> tag, the whole thing does work in Firefox.
So my plan is to just use that src attribute and determine the appropriate file using the canPlayType() function.
Am I doing it wrong somehow or complicating things?
https://codehunter.cc/a/javascript/changing-source-on-html5-video-tag
0 notes
Text
Rolling or sliding window iterator?
I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length is 1. I'm currently using the following code. Does anyone have a more Pythonic, less verbose, or more efficient method for doing this?
def rolling_window(seq, window_size): it = iter(seq) win = [it.next() for cnt in xrange(window_size)] # First window yield win for e in it: # Subsequent windows win[:-1] = win[1:] win[-1] = e yield winif __name__=="__main__": for w in rolling_window(xrange(6), 3): print w"""Example output: [0, 1, 2] [1, 2, 3] [2, 3, 4] [3, 4, 5]"""
https://codehunter.cc/a/python/rolling-or-sliding-window-iterator
0 notes