text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix options callback passing not existing element in firefox
var CurrentAppID, GetCurrentAppID = function() { if( !CurrentAppID ) { CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ ); if( CurrentAppID ) { CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 ); } else { CurrentAppID = -1; } } return CurrentAppID; }, GetHomepage = function() { return 'https://steamdb.info/'; }, GetOption = function( items, callback ) { if( typeof chrome !== 'undefined' ) { chrome.storage.local.get( items, callback ); } else if( typeof self.options.firefox !== 'undefined' ) { for( var item in items ) { items[ item ] = self.options.preferences[ item ]; } callback( items ); } }, GetLocalResource = function( res ) { if( typeof chrome !== 'undefined' ) { return chrome.extension.getURL( res ); } else if( typeof self.options.firefox !== 'undefined' ) { return self.options[ res ]; } return res; };
var CurrentAppID, GetCurrentAppID = function() { if( !CurrentAppID ) { CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ ); if( CurrentAppID ) { CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 ); } else { CurrentAppID = -1; } } return CurrentAppID; }, GetHomepage = function() { return 'https://steamdb.info/'; }, GetOption = function( items, callback ) { if( typeof chrome !== 'undefined' ) { chrome.storage.local.get( items, callback ); } else if( typeof self.options.firefox !== 'undefined' ) { for( var item in items ) { items[ item ] = self.options.preferences[ item ]; } callback( data ); } }, GetLocalResource = function( res ) { if( typeof chrome !== 'undefined' ) { return chrome.extension.getURL( res ); } else if( typeof self.options.firefox !== 'undefined' ) { return self.options[ res ]; } return res; };
Fix the test dimensions class to register a test dimension for our basic mod dimension type
package info.u_team.u_team_test.init; import info.u_team.u_team_test.TestMod; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.event.world.RegisterDimensionsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE) public class TestDimensions { @SuppressWarnings("deprecation") @SubscribeEvent public static void on(RegisterDimensionsEvent event) { if (!DimensionManager.getRegistry().keySet().contains(TestModDimensions.BASIC.getId())) { // How do we know when the dimension needs to be registered?? DimensionManager.registerDimension(TestModDimensions.BASIC.getId(), TestModDimensions.BASIC.get(), null, true); } } }
package info.u_team.u_team_test.init; import info.u_team.u_team_test.TestMod; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.event.world.RegisterDimensionsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE) public class TestDimensions { @SuppressWarnings("deprecation") @SubscribeEvent public static void on(RegisterDimensionsEvent event) { if (!DimensionManager.getRegistry().keySet().contains(TestModDimensions.BASIC.getRegistryName())) { // How do we know when the dimension needs to be registered?? DimensionManager.registerDimension(TestModDimensions.BASIC.getRegistryName(), TestModDimensions.BASIC, null, true); } } }
Use single import of lodash
import { isFunction, isObject, assign, assignWith, pick, pickBy, flatten } from 'lodash'; import compose from './compose'; export const isDescriptor = isObject; export const isStamp = obj => isFunction(obj) && isFunction(obj.compose) && isDescriptor(obj.compose); export const isComposable = obj => isDescriptor(obj) || isStamp(obj); export const init = (...functions) => compose({ initializers: flatten(functions) }); export const overrides = (...keys) => { const flattenKeys = flatten(keys); return compose({ initializers: [function (opt) { assign(this, flattenKeys.length === 0 ? opt : pick(opt, flattenKeys)); }] }); }; export const namespaced = (keyStampMap) => { const keyStampMapClone = pickBy(keyStampMap, isStamp); return compose({ initializers: [function (opt) { const optClone = pickBy(opt, (value, key) => keyStampMapClone[key]); assignWith(optClone, keyStampMapClone, (innerOpt, stamp) => stamp(innerOpt)); assign(this, optClone); }] }); };
import isFunction from 'lodash/isFunction'; import isObject from 'lodash/isObject'; import assign from 'lodash/assign'; import pick from 'lodash/pick'; import flatten from 'lodash/flatten'; import pickBy from 'lodash/pickBy'; import assignWith from 'lodash/assignWith'; import compose from './compose'; export const isDescriptor = isObject; export const isStamp = obj => isFunction(obj) && isFunction(obj.compose) && isDescriptor(obj.compose); export const isComposable = obj => isDescriptor(obj) || isStamp(obj); export const init = (...functions) => compose({ initializers: flatten(functions) }); export const overrides = (...keys) => { const flattenKeys = flatten(keys); return compose({ initializers: [function (opt) { assign(this, flattenKeys.length === 0 ? opt : pick(opt, flattenKeys)); }] }); }; export const namespaced = (keyStampMap) => { const keyStampMapClone = pickBy(keyStampMap, isStamp); return compose({ initializers: [function (opt) { const optClone = pickBy(opt, (value, key) => keyStampMapClone[key]); assignWith(optClone, keyStampMapClone, (innerOpt, stamp) => stamp(innerOpt)); assign(this, optClone); }] }); };
Refactor Javascript now concepts are understood
var columns = 3 var itemPadding = 10 function numberOfColumns() { var buildStatusCount = $('li').size() return Math.min(columns, $('li').size()) } function numberOfRows() { var buildStatusCount = $('li').size() return Math.ceil(buildStatusCount / columns) } function buildStatusWidth() { return window.innerWidth / numberOfColumns() - itemPadding } function buildStatusHeight() { return window.innerHeight / numberOfRows() - itemPadding } function styleListItems() { $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth()) scaleFontToContainerSize() } function scaleFontToContainerSize() { $(".outerContainer").fitText(1.75) } function addBuildStatusToScreen(project) { var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } } function addListItems(data) { $('#projects').empty() data.body.forEach(addBuildStatusToScreen) } function updateBuildMonitor() { $.getJSON("/projects").then(function(data){ addListItems(data) styleListItems() }) } updateBuildMonitor() // run immediately setInterval(updateBuildMonitor, 5000)
var columns = 3 var itemPadding = 10 function widthGiven(itemCount) { return window.innerWidth / Math.min(columns, itemCount) - itemPadding } function heightGiven(itemCount) { return window.innerHeight / Math.ceil(itemCount / columns) - itemPadding } function styleListItems() { var itemCount = $('li').size() $('.outerContainer') .height(heightGiven(itemCount)) .width(widthGiven(itemCount)) scaleFontToContainerSize() } function scaleFontToContainerSize() { $(".outerContainer").fitText(1.75) } function grabLatestData() { $.getJSON("/projects").then(function(data){ $('#projects').empty() data.body.forEach(function(project){ var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } }) styleListItems() }) } grabLatestData(); // run immediately setInterval(grabLatestData, 5000);
Make blogpost summary and content nullable
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBlogpostsTable extends Migration { /** * Run the migrations. * * @return void */ private $table_name = 'blogposts'; public function up() { if (Schema::hasTable($this->table_name)) { return; } Schema::create($this->table_name, function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('slug'); $table->string('summary')->nullable(); $table->text('text')->nullable(); $table->integer('category_id'); $table->integer('comments_enabled'); $table->integer('author_id'); $table->string('image')->nullable(); $table->timestamps(); $table->boolean('active')->default(true); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop($this->table_name); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBlogpostsTable extends Migration { /** * Run the migrations. * * @return void */ private $table_name = 'blogposts'; public function up() { if (Schema::hasTable($this->table_name)) { return; } Schema::create($this->table_name, function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('slug'); $table->string('summary'); $table->text('text'); $table->integer('category_id'); $table->integer('comments_enabled'); $table->integer('author_id'); $table->string('image')->nullable(); $table->timestamps(); $table->boolean('active')->default(true); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop($this->table_name); } }
TEst adding test server to allowed hosts
# Local from .base import * # Heroku Settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True ALLOWED_HOSTS = [ 'testserver', '.barberscore.com', '.herokuapp.com', ] DATABASES['default']['TEST'] = { 'NAME': DATABASES['default']['NAME'], } # Email EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = get_env_variable("SENDGRID_USERNAME") EMAIL_HOST_PASSWORD = get_env_variable("SENDGRID_PASSWORD") EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_SUBJECT_PREFIX = "[Barberscore] " # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, }
# Local from .base import * # Heroku Settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True ALLOWED_HOSTS = [ '.barberscore.com', '.herokuapp.com', ] DATABASES['default']['TEST'] = { 'NAME': DATABASES['default']['NAME'], } # Email EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = get_env_variable("SENDGRID_USERNAME") EMAIL_HOST_PASSWORD = get_env_variable("SENDGRID_PASSWORD") EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_SUBJECT_PREFIX = "[Barberscore] " # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, }
Add basic system error logging to exception handler
<?php namespace Bolt; class Handler { public static function error($level, $message, $file, $line, $context) { throw new Exceptions\Error($message, 0, $level, $file, $line); } public static function exception($exception) { $response = new Api\Response(); $className = get_class($exception); error_log($exception->getMessage()); if (DEPLOYMENT == "production") { $data = $className; } else { $data = array( "type" => $className, "message" => $exception->getMessage(), "code" => $exception->getCode(), "line" => $exception->getLine(), "file" => $exception->getFile(), "trace" => $exception->getTrace() ); } $response->status(500, $data); } } ?>
<?php namespace Bolt; class Handler { public static function error($level, $message, $file, $line, $context) { throw new Exceptions\Error($message, 0, $level, $file, $line); } public static function exception($exception) { $response = new Api\Response(); $className = get_class($exception); if (DEPLOYMENT == "production") { $data = $className; } else { $data = array( "type" => $className, "message" => $exception->getMessage(), "code" => $exception->getCode(), "line" => $exception->getLine(), "file" => $exception->getFile(), "trace" => $exception->getTrace() ); } $response->status(500, $data); } } ?>
Use atomic operation to increment the execution stats values
package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private final AtomicInteger submitted; private final AtomicInteger completed; private final AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { submitted.getAndAdd(value); } public void incrementCompleted(int value) { completed.getAndAdd(value); } public void incrementError(int value) { error.getAndAdd(value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } }
package uk.ac.ebi.biosamples.model.util; import java.util.concurrent.atomic.AtomicInteger; public class ExecutionInfo { private AtomicInteger submitted; private AtomicInteger completed; private AtomicInteger error; public ExecutionInfo() { submitted = new AtomicInteger(0); completed = new AtomicInteger(0); error = new AtomicInteger(0); } public void incrementSubmitted(int value) { int oldValue = submitted.get(); submitted.set(oldValue + value); } public void incrementCompleted(int value) { int oldValue = completed.get(); completed.set(oldValue + value); } public void incrementError(int value) { int oldValue = error.get(); error.set(oldValue + value); } public int getCompleted() { return completed.get(); } public int getSubmitted() { return submitted.get(); } public int getErrors() { return error.get(); } }
Fix the proper footer based on cartodb_com_hosted.
var cdb = require('cartodb.js-v3'); var DEFAULT_LIGHT_ACTIVE = false; module.exports = cdb.core.View.extend({ initialize: function () { this._initModels(); this.template = this.isHosted ? cdb.templates.getTemplate('common/views/footer_static') : cdb.templates.getTemplate('public/views/public_footer'); }, render: function () { this.$el.html( this.template({ isHosted: this.isHosted, light: this.light, onpremiseVersion: this.onpremiseVersion }) ); return this; }, _initModels: function () { this.isHosted = cdb.config.get('cartodb_com_hosted'); this.onpremiseVersion = cdb.config.get('onpremise_version'); this.light = !!this.options.light || DEFAULT_LIGHT_ACTIVE; } });
var cdb = require('cartodb.js-v3'); var DEFAULT_LIGHT_ACTIVE = false; module.exports = cdb.core.View.extend({ initialize: function () { this._initModels(); this.template = this.isHosted ? cdb.templates.getTemplate('public/views/public_footer') : cdb.templates.getTemplate('common/views/footer_static'); }, render: function () { this.$el.html( this.template({ isHosted: this.isHosted, light: this.light, onpremiseVersion: this.onpremiseVersion }) ); return this; }, _initModels: function () { this.isHosted = cdb.config.get('cartodb_com_hosted'); this.onpremiseVersion = cdb.config.get('onpremise_version'); this.light = !!this.options.light || DEFAULT_LIGHT_ACTIVE; } });
Fix console warning about history import
import React from 'react'; import { applyMiddleware, createStore } from 'redux'; import { Provider as ReduxProvider } from 'react-redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import { createBrowserHistory } from 'history'; import { ConnectedRouter, routerMiddleware } from 'react-router-redux'; import reducers from 'interface/reducers'; import RootErrorBoundary from 'interface/RootErrorBoundary'; import App from 'interface/App'; import RootLocalizationProvider from 'interface/RootLocalizationProvider'; import { Provider } from 'interface/LocationContext'; const history = createBrowserHistory(); // Build the middleware for intercepting and dispatching navigation actions const middleware = routerMiddleware(history); const store = createStore( reducers, composeWithDevTools( applyMiddleware(thunk, middleware) ) ); const Root = () => ( <ReduxProvider store={store}> <RootErrorBoundary> <RootLocalizationProvider> <ConnectedRouter history={history}> <Provider> <App /> </Provider> </ConnectedRouter> </RootLocalizationProvider> </RootErrorBoundary> </ReduxProvider> ); export default Root;
import React from 'react'; import { applyMiddleware, createStore } from 'redux'; import { Provider as ReduxProvider } from 'react-redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import createHistory from 'history/createBrowserHistory'; import { ConnectedRouter, routerMiddleware } from 'react-router-redux'; import reducers from 'interface/reducers'; import RootErrorBoundary from 'interface/RootErrorBoundary'; import App from 'interface/App'; import RootLocalizationProvider from 'interface/RootLocalizationProvider'; import { Provider } from 'interface/LocationContext'; // Create a history of your choosing (we're using a browser history in this case) const history = createHistory(); // Build the middleware for intercepting and dispatching navigation actions const middleware = routerMiddleware(history); const store = createStore( reducers, composeWithDevTools( applyMiddleware(thunk, middleware) ) ); const Root = () => ( <ReduxProvider store={store}> <RootErrorBoundary> <RootLocalizationProvider> <ConnectedRouter history={history}> <Provider> <App /> </Provider> </ConnectedRouter> </RootLocalizationProvider> </RootErrorBoundary> </ReduxProvider> ); export default Root;
Patch for an xss vulnerability where it was possible to inject js by closing and then opening a new script tag eg. ?q="xxxx'yyyy</script><script>confirm('hello')</script>&sa=Search
var React = require('react'); var ReactDOM = require('react-dom'); var ServersideWrapper = React.createClass({ propTypes: { element: React.PropTypes.string.isRequired, properties: React.PropTypes.object.isRequired }, render: function() { var json = JSON.stringify(this.props.properties); return React.createElement('script', { type: 'application/json', id: this.props.element + '_props', dangerouslySetInnerHTML: { __html: json.replace(/\//g, '\\/') } }); } }); // This method is used to create the initial dom node that react attaches itself to ServersideWrapper.createDomElement = function(opts) { if (typeof window !== 'undefined' && document.getElementById(opts.domElement + '_props') !== null) { var componentProperties = JSON.parse( document.getElementById(opts.domElement + '_props').innerHTML ); ReactDOM.render(React.createElement(opts.component, componentProperties), document.getElementById(opts.domElement)); } }; module.exports = ServersideWrapper;
var React = require('react'); var ReactDOM = require('react-dom'); var ServersideWrapper = React.createClass({ propTypes: { element: React.PropTypes.string.isRequired, properties: React.PropTypes.object.isRequired }, render: function() { var json = JSON.stringify(this.props.properties); return React.createElement('script', { type: 'application/json', id: this.props.element + '_props', dangerouslySetInnerHTML: { __html: json } }); } }); // This method is used to create the initial dom node that react attaches itself to ServersideWrapper.createDomElement = function(opts) { if (typeof window !== 'undefined' && document.getElementById(opts.domElement + '_props') !== null) { var componentProperties = JSON.parse( document.getElementById(opts.domElement + '_props').innerHTML ); ReactDOM.render(React.createElement(opts.component, componentProperties), document.getElementById(opts.domElement)); } }; module.exports = ServersideWrapper;
Add router logger for developing
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import store from './lib/redux/store' import { hashHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer' import App from './App' const isDev = process.env.NODE_ENV !== 'production' if (isDev) { installExtension(REACT_DEVELOPER_TOOLS) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)) } document.addEventListener('drop', function (e) { e.preventDefault() e.stopPropagation() }) document.addEventListener('dragover', function (e) { e.preventDefault() e.stopPropagation() }) const history = syncHistoryWithStore(hashHistory, store) if (isDev) { history.listen((location) => { if (location.action === 'PUSH') { console.info('PUSHING...', location.pathname + location.search) } }) } const render = () => { ReactDOM.render( <AppContainer> <App store={store} history={history} /> </AppContainer>, document.getElementById('content') ) } render() // Hot Module Replacement API if (module.hot) { module.hot.accept('./App', render) }
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import store from './lib/redux/store' import { hashHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer' import App from './App' if (process.env.NODE_ENV !== 'production') { installExtension(REACT_DEVELOPER_TOOLS) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)) } document.addEventListener('drop', function (e) { e.preventDefault() e.stopPropagation() }) document.addEventListener('dragover', function (e) { e.preventDefault() e.stopPropagation() }) const history = syncHistoryWithStore(hashHistory, store) const render = () => { ReactDOM.render( <AppContainer> <App store={store} history={history} /> </AppContainer>, document.getElementById('content') ) } render() // Hot Module Replacement API if (module.hot) { module.hot.accept('./App', render) }
Add link to User on UserHeader
<div class="col-lg-6"> <div class="profilepic"><img class="profilepicsize" src="../{{ $contact->avatar }}" /></div> <h1><a href="{{ route('users.show', $contact->id) }}">{{ $contact->name }}</a></h1> <!--MAIL--> <p><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> <a href="mailto:{{ $contact->email }}">{{ $contact->email }}</a></p> <!--Work Phone--> <!-- cuongnv <p><span class="glyphicon glyphicon-headphones" aria-hidden="true"></span> <a href="tel:{{ $contact->work_number }}">{{ $contact->work_number }}</a></p> --> <!--Personal Phone--> <p><span class="glyphicon glyphicon-phone" aria-hidden="true"></span> <a href="tel:{{ $contact->personal_number }}">{{ $contact->personal_number }}</a></p> <!--Code--> <p><span class="glyphicon glyphicon-barcode" aria-hidden="true"></span> {{ $contact->code }}</p> <!--Address--> <p><span class="glyphicon glyphicon-globe" aria-hidden="true"></span> {{ $contact->locale->first()->name }} </p> </div>
<div class="col-lg-6"> <div class="profilepic"><img class="profilepicsize" src="../{{ $contact->avatar }}" /></div> <h1>{{ $contact->name }} </h1> <!--MAIL--> <p><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> <a href="mailto:{{ $contact->email }}">{{ $contact->email }}</a></p> <!--Work Phone--> <!-- cuongnv <p><span class="glyphicon glyphicon-headphones" aria-hidden="true"></span> <a href="tel:{{ $contact->work_number }}">{{ $contact->work_number }}</a></p> --> <!--Personal Phone--> <p><span class="glyphicon glyphicon-phone" aria-hidden="true"></span> <a href="tel:{{ $contact->personal_number }}">{{ $contact->personal_number }}</a></p> <!--Code--> <p><span class="glyphicon glyphicon-barcode" aria-hidden="true"></span> {{ $contact->code }}</p> <!--Address--> <p><span class="glyphicon glyphicon-globe" aria-hidden="true"></span> {{ $contact->locale->first()->name }} </p> </div>
Use an instance variable for match tracking. When accessing state along context, something is up with setState enqueued updates not dispatching. It might have to do with ReactNoopUpdateQueue being used on the server side, but I'm not 100% sure. For now, this non-idiomatic workaround gets the job done...
import React, { PropTypes } from 'react' import { matchContext as matchContextType } from './PropTypes' class MatchProvider extends React.Component { static propTypes = { match: PropTypes.any, children: PropTypes.node } static childContextTypes = { match: matchContextType.isRequired } constructor(props) { super(props) this.state = { parent: props.match } // When accessing state along this.context, it appears any enqueued setState // calls don't get dispatched on the server (renderToString) and something // like Miss will never work. This works around that by using a simple // instance variable. Sorry it's not idiomatic React! this.matches = [] } addMatch = match => { this.matches = this.matches.concat([match]) } removeMatch = match => { this.matches = this.matches.splice(this.matches.indexOf(match), 1) } getChildContext() { return { match: { addMatch: this.addMatch, removeMatch: this.removeMatch, parent: this.state.parent, matches: this.matches, matchFound: () => this.matches.length > 0 } } } render() { return this.props.children } } export default MatchProvider
import React, { PropTypes } from 'react' import { matchContext as matchContextType } from './PropTypes' class MatchProvider extends React.Component { static propTypes = { match: PropTypes.any, children: PropTypes.node } static childContextTypes = { match: matchContextType.isRequired } constructor(props) { super(props) this.state = { parent: props.match, matches: [] } } addMatch = match => { const { matches } = this.state this.setState({ matches: matches.concat([match]) }) } removeMatch = match => { const { matches } = this.state this.setState({ matches: matches.splice(matches.indexOf(match), 1) }) } getChildContext() { return { match: { addMatch: this.addMatch, removeMatch: this.removeMatch, parent: this.state.parent, matches: this.state.matches, matchFound: () => this.state.matches.length > 0 } } } render() { return this.props.children } } export default MatchProvider
Add an option to redirect user to a page if the key is already expired.
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.shortcuts import get_object_or_404 from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def login(request, key, redirect_expired_to=None): data = get_object_or_404(Key, key=key) expired = False if data.usage_left is not None and data.usage_left == 0: expired = True if data.expires is not None and data.expires < datetime.now(): expired = True if expired: if redirect_expired_to is not None: return HttpResponseRedirect(redirect_expired_to) else: return HttpResponseGone() if data.usage_left is not None: data.usage_left -= 1 data.save() login(request, data.user) next = request.GET.get('next', None) if data.next is not None: next = data.next if next is None: next = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(next)
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.shortcuts import get_object_or_404 from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def login(request, key): data = get_object_or_404(Key, key=key) if data.usage_left is not None and data.usage_left == 0: return HttpResponseGone() if data.expires is not None and data.expires < datetime.now(): return HttpResponseGone() if data.usage_left is not None: data.usage_left -= 1 data.save() login(request, data.user) next = request.GET.get('next', None) if data.next is not None: next = data.next if next is None: next = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(next)
Return artwork node instead of fields
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { ArtworkType } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: { artwork: { type: ArtworkType, resolve: ({ artwork_id }) => gravity(`artwork/${artwork_id}`), }, }, mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => ({ artwork_id })); }, });
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { artworkFields } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: artworkFields(), mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => gravity(`artwork/${artwork_id}`)); }, });
Raise exceptions for common errors rather than returning invalid data.
from werkzeug.exceptions import NotFound, InternalServerError import mechanize import re def fetchLatest(): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") latestDate = br["txt_ReportDate"] return latestDate def fetchReport(reportDate): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") br["txt_ReportDate"] = reportDate response2 = br.submit(name="btn_SearchTop") print response2.geturl() if not response2.geturl().startswith("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/rpt.aspx"): raise InternalServerError() data = response2.get_data() if re.search("There were no results for the search criteria you entered", data): raise NotFound() data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""", "<!-- viewstate field stripped -->", data) return data_filtered.decode("utf-8")
import mechanize import re def fetchLatest(): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") latestDate = br["txt_ReportDate"] return latestDate def fetchReport(reportDate): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") br["txt_ReportDate"] = reportDate response2 = br.submit(name="btn_SearchTop") data = response2.get_data() data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""", "<!-- viewstate field stripped -->", data) return data_filtered.decode("utf-8")
Add fields to driller list serializer
from rest_framework import serializers from registries.models import Organization from gwells.models import ProvinceState class DrillerListSerializer(serializers.ModelSerializer): """ Serializer for Driller model "list" view. """ province_state = serializers.ReadOnlyField(source="province_state.code") class Meta: model = Organization # Using all fields for now fields = ( #'who_created', #'when_created', #'who_updated', #'when_updated', 'org_guid', 'name', 'street_address', 'city', 'province_state', 'postal_code', 'main_tel', #'fax_tel', #'website_url', #'certificate_authority', )
from rest_framework import serializers from registries.models import Organization from gwells.models import ProvinceState class DrillerListSerializer(serializers.ModelSerializer): province_state = serializers.ReadOnlyField() class Meta: model = Organization # Using all fields for now fields = ( #'who_created', #'when_created', #'who_updated', #'when_updated', 'name', 'street_address', 'city', 'province_state', 'postal_code', 'main_tel', 'fax_tel', 'website_url', 'certificate_authority', )
Return 404 NOT FOUND if no match could be found
#!/usr/bin/env python from flask import Flask, abort, make_response, request from pigeon import PigeonStore from socket import inet_aton, error as socket_error app = Flask(__name__) @app.before_first_request def open_store(): global p p = PigeonStore() @app.route('/lookup') def lookup(): ip = request.args['ip'] try: k = inet_aton(ip) except socket_error: abort(400) info_as_json = p.lookup(k) if info_as_json is None: abort(404) response = make_response(info_as_json) response.headers['Content-type'] = 'application/json' return response if __name__ == '__main__': import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=5555, type=int) parser.add_argument('--debug', default=False, action='store_true') args = parser.parse_args() try: app.run(**vars(args)) except KeyboardInterrupt: sys.stderr.write("Aborting...\n")
#!/usr/bin/env python from flask import Flask, abort, make_response, request from pigeon import PigeonStore from socket import inet_aton, error as socket_error app = Flask(__name__) @app.before_first_request def open_store(): global p p = PigeonStore() @app.route('/lookup') def lookup(): ip = request.args['ip'] try: k = inet_aton(ip) except socket_error: abort(400) response = make_response(p.lookup(k)) response.headers['Content-type'] = 'application/json' return response if __name__ == '__main__': import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=5555, type=int) parser.add_argument('--debug', default=False, action='store_true') args = parser.parse_args() try: app.run(**vars(args)) except KeyboardInterrupt: sys.stderr.write("Aborting...\n")
FIX - remove inconsistent dependence
# -*- coding: utf-8 -*- # © 2016 Coninckx David (Open Net Sarl) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Attendance - Calendar', 'summary': 'Compute extra hours based on attendances', 'category': 'Human Resources', 'author': "CompassionCH, Open Net Sàrl", 'depends': [ 'hr', 'hr_attendance', 'hr_holidays', 'hr_public_holidays' ], 'version': '10.0.1.0.0', 'auto_install': False, 'website': 'http://open-net.ch', 'license': 'AGPL-3', 'images': [], 'data': [ 'security/ir.model.access.csv', 'views/hr_attendance_calendar_view.xml', 'views/hr_attendance_day_view.xml', 'views/hr_attendance_view.xml', 'views/hr_employee.xml', 'views/hr_holidays_status_views.xml', 'wizard/create_hr_attendance_day_view.xml', 'data/attendance_computation_cron.xml' ], 'installable': True }
# -*- coding: utf-8 -*- # © 2016 Coninckx David (Open Net Sarl) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Attendance - Calendar', 'summary': 'Compute extra hours based on attendances', 'category': 'Human Resources', 'author': "CompassionCH, Open Net Sàrl", 'depends': [ 'hr', 'hr_employee', 'hr_attendance', 'hr_holidays', 'hr_public_holidays' ], 'version': '10.0.1.0.0', 'auto_install': False, 'website': 'http://open-net.ch', 'license': 'AGPL-3', 'images': [], 'data': [ 'security/ir.model.access.csv', 'views/hr_attendance_calendar_view.xml', 'views/hr_attendance_day_view.xml', 'views/hr_attendance_view.xml', 'views/hr_employee.xml', 'views/hr_holidays_status_views.xml', 'wizard/create_hr_attendance_day_view.xml', 'data/attendance_computation_cron.xml' ], 'installable': True }
Fix issue of blank responses for web ethic parsing.
module.exports = function(question, callback) { var apiai = require('apiai'); var app = apiai("76ccb7c7acea4a6884834f6687475222", "8b3e68f16ac6430cb8c40d49c315aa7a"); var request = app.textRequest(question); request.on('response', function(response) { var kantSucks = require('./deontologyYo')(response); if(kantSucks == 0) if(response.result.metadata.speech) callback(response.result.metadata.speech) else callback("Unfortunately, I'm not smart enough to answer that question yet.") else if(kantSucks == 1) if(response.result.metadata.speech) callback("I'll check with that after I pass through my utility ethic function. Heres what I would say otherwise: " + response.result.metadata.speech); else callback(kantSucks) }); request.on('error', function(error) { callback(error); }); request.end() };
module.exports = function(question, callback) { var apiai = require('apiai'); var app = apiai("76ccb7c7acea4a6884834f6687475222", "8b3e68f16ac6430cb8c40d49c315aa7a"); var request = app.textRequest(question); request.on('response', function(response) { var kantSucks = require('./deontologyYo')(response); if(kantSucks == 0) if(response.result.metadata.speech) callback(response.result.metadata.speech) else callback("Unfortunately, I'm not smart enough to answer that question yet.") else if(kantSucks == 1) callback("I'll check with that after I pass through my utility ethic function. Heres what I would say otherwise: " + response.result.metadata.speech); else callback(kantSucks) }); request.on('error', function(error) { callback(error); }); request.end() };
Remove h5, h6 from tocify configuration parameters
/** * User: powerumc * Date: 2014. 5. 18. */ $(function() { $(function () { $.ajax({ url: "Requirements.md", type: "GET", success: function (data) { var html = marked(data); $("#preview").html(html); var toc = $("#toc").tocify({ context: "#preview", selectors: "h1, h2, h3, h4", showEffect: "slideDown", hideEffect: "slideUp", scrollTo: 55, theme: "jqueryui", hashGenerator: "pretty", highlightOffset: 40}); $("code").addClass("prettyprint"); prettyPrint(); $(document).ready(function () { $('[data-toggle=offcanvas]').click(function () { $('.row-offcanvas').toggleClass('active'); }); }); $("#title").text($("#preview h1:first").text()); } }); }); });
/** * User: powerumc * Date: 2014. 5. 18. */ $(function() { $(function () { $.ajax({ url: "Requirements.md", type: "GET", success: function (data) { var html = marked(data); $("#preview").html(html); var toc = $("#toc").tocify({ context: "#preview", selectors: "h1, h2, h3, h4, h5, h6", showEffect: "slideDown", hideEffect: "slideUp", scrollTo: 55, theme: "jqueryui", hashGenerator: "pretty", highlightOffset: 40}); $("code").addClass("prettyprint"); prettyPrint(); $(document).ready(function () { $('[data-toggle=offcanvas]').click(function () { $('.row-offcanvas').toggleClass('active'); }); }); $("#title").text($("#preview h1:first").text()); } }); }); });
Rewrite promises with async-await in controllers
const dotenv = require('dotenv'); dotenv.config(); module.exports = { development: { username: 'Newman', password: 'andela2017', database: 'postit-db-dev', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, test: { // username: 'Newman', // password: 'andela2017', // database: 'postit-db-test', username: 'postgres', password: '', database: 'postit_db_test', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, production: { use_env_variable: 'PROD_DB_URL', username: '?', password: '?', database: '?', host: '?', dialect: '?' } };
const dotenv = require('dotenv'); dotenv.config(); module.exports = { development: { username: 'Newman', password: 'andela2017', database: 'postit-db-dev', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, test: { username: 'Newman', password: 'andela2017', database: 'postit-db-test', // username: 'postgres', // password: '', // database: 'postit_db_test', host: '127.0.0.1', port: 5432, secret_key: process.env.SECRET_KEY, dialect: 'postgres' }, production: { use_env_variable: 'PROD_DB_URL', username: '?', password: '?', database: '?', host: '?', dialect: '?' } };
Fix syntax error for PHP 5.3
<?php require '../src/Curl.class.php'; define('MAILCHIMP_API_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXX'); $parts = explode('-', MAILCHIMP_API_KEY); define('MAILCHIMP_BASE_URL', 'https://' . $parts['1'] . '.api.mailchimp.com/2.0/'); $curl = new Curl(); $curl->get(MAILCHIMP_BASE_URL . '/lists/list.json', array( 'apikey' => MAILCHIMP_API_KEY, )); if ($curl->response->total === 0) { echo 'No lists found'; exit; } $lists = $curl->response->data; $list = $lists['0']; $curl->post(MAILCHIMP_BASE_URL . '/lists/subscribe.format', array( 'apikey' => MAILCHIMP_API_KEY, 'id' => $list->id, 'email' => array( 'email' => 'user@example.com', ), )); if ($curl->error) { echo $curl->response->name . ': ' . $curl->response->error . "\n"; } else { echo 'Subscribed ' . $curl->response->email . '.' . "\n"; }
<?php require '../src/Curl.class.php'; define('MAILCHIMP_API_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXX'); define('MAILCHIMP_BASE_URL', 'https://' . explode('-', MAILCHIMP_API_KEY)['1'] . '.api.mailchimp.com/2.0/'); $curl = new Curl(); $curl->get(MAILCHIMP_BASE_URL . '/lists/list.json', array( 'apikey' => MAILCHIMP_API_KEY, )); if ($curl->response->total === 0) { echo 'No lists found'; exit; } $lists = $curl->response->data; $list = $lists['0']; $curl->post(MAILCHIMP_BASE_URL . '/lists/subscribe.format', array( 'apikey' => MAILCHIMP_API_KEY, 'id' => $list->id, 'email' => array( 'email' => 'user@example.com', ), )); if ($curl->error) { echo $curl->response->name . ': ' . $curl->response->error . "\n"; } else { echo 'Subscribed ' . $curl->response->email . '.' . "\n"; }
Add reminder to myself to to importlib fallback.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Remove useLintTree ember-cli-mocha build configuration
/* eslint-env node */ /* global require, module */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, 'ember-cli-babel': { includePolyfill: true }, sassOptions: { includePaths: [ 'addon/styles' ] }, snippetPaths: [ 'code-snippets' ], snippetSearchPaths: [ 'tests/dummy' ] }) app.import('bower_components/highlightjs/styles/github.css') app.import(app.project.addonPackages['ember-source'] ? 'vendor/ember/ember-template-compiler.js' : 'bower_components/ember/ember-template-compiler.js') return app.toTree() }
/* eslint-env node */ /* global require, module */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, 'ember-cli-babel': { includePolyfill: true }, 'ember-cli-mocha': { useLintTree: false }, sassOptions: { includePaths: [ 'addon/styles' ] }, snippetPaths: [ 'code-snippets' ], snippetSearchPaths: [ 'tests/dummy' ] }) app.import('bower_components/highlightjs/styles/github.css') app.import(app.project.addonPackages['ember-source'] ? 'vendor/ember/ember-template-compiler.js' : 'bower_components/ember/ember-template-compiler.js') return app.toTree() }
Remove variable declaration for service and just return the object.
Application.Services.factory('tags', ["mcapi", function tags(mcapi) { return { tags: [], createTag: function (tag, item_id) { mcapi('/tags/item/%', item_id) .success(function (tag) { return tag; }).post(tag); }, removeTag: function (tag_id, item_id) { mcapi('/tags/%/item/%', tag_id, item_id) .success(function (tag) { return tag; }).delete(); } }; }]);
Application.Services.factory('tags', ["mcapi", function tags(mcapi) { var service = { tags: [], createTag: function (tag, item_id) { mcapi('/tags/item/%', item_id) .success(function (tag) { return tag; }).post(tag); }, removeTag: function (tag_id, item_id) { mcapi('/tags/%/item/%', tag_id, item_id) .success(function (tag) { return tag; }).delete(); } }; return service; }]);
Convert select list to list view mode
import declare from 'dojo/_base/declare'; import lang from 'dojo/_base/lang'; import Memory from 'dojo/store/Memory'; import List from 'argos/List'; /** * @class crm.Views.SelectList * * * @extends argos.List * */ const __class = declare('crm.Views.SelectList', [List], { // Templates itemTemplate: new Simplate([ '<p class="listview-heading">{%: $.$descriptor %}</p>', ]), // View Properties id: 'select_list', expose: false, enablePullToRefresh: false, isCardView: false, refreshRequiredFor: function refreshRequiredFor(options) { if (this.options) { return options ? (this.options.data !== options.data) : false; } return true; }, hasMoreData: function hasMoreData() { return false; }, requestData: function requestData() { this.store = null; this.inherited(arguments); }, createStore: function createStore() { // caller is responsible for passing in a well-structured feed object. const data = this.expandExpression(this.options && this.options.data && this.options.data.$resources); const store = new Memory({ data, }); store.idProperty = '$key'; return store; }, }); lang.setObject('Mobile.SalesLogix.Views.SelectList', __class); export default __class;
import declare from 'dojo/_base/declare'; import lang from 'dojo/_base/lang'; import Memory from 'dojo/store/Memory'; import List from 'argos/List'; /** * @class crm.Views.SelectList * * * @extends argos.List * */ const __class = declare('crm.Views.SelectList', [List], { // Templates itemTemplate: new Simplate([ '<p class="listview-heading">{%: $.$descriptor %}</p>', ]), // View Properties id: 'select_list', expose: false, enablePullToRefresh: false, refreshRequiredFor: function refreshRequiredFor(options) { if (this.options) { return options ? (this.options.data !== options.data) : false; } return true; }, hasMoreData: function hasMoreData() { return false; }, requestData: function requestData() { this.store = null; this.inherited(arguments); }, createStore: function createStore() { // caller is responsible for passing in a well-structured feed object. const data = this.expandExpression(this.options && this.options.data && this.options.data.$resources); const store = new Memory({ data, }); store.idProperty = '$key'; return store; }, }); lang.setObject('Mobile.SalesLogix.Views.SelectList', __class); export default __class;
Add SaveName to Regex, but just return an error message
package storage import ( "fmt" "regexp" ) func init() { SupportedStorageTypes["Regex"] = new(interface{}) } type remap struct { Regex *regexp.Regexp Replacement string } type Regex struct { remaps []remap } func NewRegexFromList(redirects map[string]string) (*Regex, error) { remaps := make([]remap, 0, len(redirects)) for regexString, redirect := range redirects { r, err := regexp.Compile(regexString) if err != nil { return nil, err } remaps = append(remaps, remap{ Regex: r, Replacement: redirect, }) } return &Regex{ remaps: remaps, }, nil } func (r Regex) Load(short string) (string, error) { // Regex intentionally doesn't do sanitization, each regex can have whatever flexability it wants for _, remap := range r.remaps { if remap.Regex.MatchString(short) { return remap.Regex.ReplaceAllString(short, remap.Replacement), nil } } return "", ErrShortNotSet } func (r Regex) SaveName(short string, long string) (string, error) { // Regex intentionally doesn't do sanitization, each regex can have whatever flexability it wants return "", fmt.Errorf("regex doesn't yet support saving after creation") }
package storage import "regexp" func init() { SupportedStorageTypes["Regex"] = new(interface{}) } type remap struct { Regex *regexp.Regexp Replacement string } type Regex struct { remaps []remap } func NewRegexFromList(redirects map[string]string) (*Regex, error) { remaps := make([]remap, 0, len(redirects)) for regexString, redirect := range redirects { r, err := regexp.Compile(regexString) if err != nil { return nil, err } remaps = append(remaps, remap{ Regex: r, Replacement: redirect, }) } return &Regex{ remaps: remaps, }, nil } func (r Regex) Load(short string) (string, error) { // Regex intentionally doesn't do sanitization, each regex can have whatever flexability it wants for _, remap := range r.remaps { if remap.Regex.MatchString(short) { return remap.Regex.ReplaceAllString(short, remap.Replacement), nil } } return "", ErrShortNotSet }
Fix condition, when no placeholder for empty value
// @flow export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { return placeholder === false ? '' : '—'; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
// @flow export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { return placeholder ? '—' : ''; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
Fix NPE on bungeecord lazy loading
package com.github.games647.changeskin.bungee.listener; import com.github.games647.changeskin.bungee.ChangeSkinBungee; import com.github.games647.changeskin.core.SkinData; import com.github.games647.changeskin.core.UserPreference; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; public class JoinListener extends AbstractSkinListener { public JoinListener(ChangeSkinBungee plugin) { super(plugin); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerLogin(PostLoginEvent postLoginEvent) { ProxiedPlayer player = postLoginEvent.getPlayer(); //updates to the chosen one UserPreference preferences = plugin.getLoginSession(player.getPendingConnection()); if (preferences == null) { return; } SkinData targetSkin = preferences.getTargetSkin(); if (targetSkin == null) { setRandomSkin(preferences, player); } else { plugin.applySkin(player, targetSkin); } } }
package com.github.games647.changeskin.bungee.listener; import com.github.games647.changeskin.bungee.ChangeSkinBungee; import com.github.games647.changeskin.core.SkinData; import com.github.games647.changeskin.core.UserPreference; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; public class JoinListener extends AbstractSkinListener { public JoinListener(ChangeSkinBungee plugin) { super(plugin); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerLogin(PostLoginEvent postLoginEvent) { ProxiedPlayer player = postLoginEvent.getPlayer(); //updates to the chosen one UserPreference preferences = plugin.getLoginSession(player.getPendingConnection()); SkinData targetSkin = preferences.getTargetSkin(); if (targetSkin == null) { setRandomSkin(preferences, player); } else { plugin.applySkin(player, targetSkin); } } }
Fix problem with context load
package com.jmb.springfactory.service.productionschedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jmb.springfactory.dao.GenericMySQLService; import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService; import com.jmb.springfactory.model.bo.BusinessObjectBase; import com.jmb.springfactory.model.dto.ProductionScheduleDto; import com.jmb.springfactory.model.entity.ProductionSchedule; import com.jmb.springfactory.service.GenericServiceImpl; @Service public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto, BusinessObjectBase, Integer> implements ProductionScheduleService { @Autowired private ProductionScheduleMySQLService productionScheduleMySQLService; @Override public GenericMySQLService<ProductionSchedule, Integer> genericDao() { return productionScheduleMySQLService; } @Override public Class<? extends ProductionSchedule> getClazz() { return ProductionSchedule.class; } @Override public Class<? extends ProductionScheduleDto> getDtoClazz() { return ProductionScheduleDto.class; } @Override public Class<? extends BusinessObjectBase> getBoClazz() { return BusinessObjectBase.class; } }
package com.jmb.springfactory.service.productionschedule; import org.springframework.beans.factory.annotation.Autowired; import com.jmb.springfactory.dao.GenericMySQLService; import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService; import com.jmb.springfactory.model.bo.BusinessObjectBase; import com.jmb.springfactory.model.dto.ProductionScheduleDto; import com.jmb.springfactory.model.entity.ProductionSchedule; import com.jmb.springfactory.service.GenericServiceImpl; public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto, BusinessObjectBase, Integer> implements ProductionScheduleService { @Autowired private ProductionScheduleMySQLService productionScheduleMySQLService; @Override public GenericMySQLService<ProductionSchedule, Integer> genericDao() { return productionScheduleMySQLService; } @Override public Class<? extends ProductionSchedule> getClazz() { return ProductionSchedule.class; } @Override public Class<? extends ProductionScheduleDto> getDtoClazz() { return ProductionScheduleDto.class; } @Override public Class<? extends BusinessObjectBase> getBoClazz() { return BusinessObjectBase.class; } }
Implement city model behavior in existing city model
<?php namespace Octommerce\Octommerce\Models; use Model; /** * City Model */ class City extends Model { /** * @var string The database table used by the model. */ public $table = 'octommerce_octommerce_cities'; /** * Implement the CityModel behavior. */ public $implement = ['Octommerce.Octommerce.Behaviors.CityModel']; public $timestamps = false; /** * @var array Guarded fields */ protected $guarded = ['*']; /** * @var array Fillable fields */ protected $fillable = []; /** * @var array Relations */ public $hasOne = []; public $hasMany = []; public $belongsTo = [ 'state' => 'RainLab\Location\Models\State', ]; public $belongsToMany = []; public $morphTo = []; public $morphOne = []; public $morphMany = []; public $attachOne = []; public $attachMany = []; }
<?php namespace Octommerce\Octommerce\Models; use Model; /** * City Model */ class City extends Model { /** * @var string The database table used by the model. */ public $table = 'octommerce_octommerce_cities'; public $timestamps = false; /** * @var array Guarded fields */ protected $guarded = ['*']; /** * @var array Fillable fields */ protected $fillable = []; /** * @var array Relations */ public $hasOne = []; public $hasMany = []; public $belongsTo = [ 'state' => 'RainLab\Location\Models\State', ]; public $belongsToMany = []; public $morphTo = []; public $morphOne = []; public $morphMany = []; public $attachOne = []; public $attachMany = []; }
Remove cookie support from tornado until it works in all situations
from tornado.web import RequestHandler import bugsnag class BugsnagRequestHandler(RequestHandler): def _handle_request_exception(self, e): # Set the request info bugsnag.configure_request( user_id = self.request.remote_ip, context = "%s %s" % (self.request.method, self.request.uri.split('?')[0]), request_data = { "url": self.request.full_url(), "method": self.request.method, "arguments": self.request.arguments, }, ) # Notify bugsnag bugsnag.notify(e) # Call the parent handler RequestHandler._handle_request_exception(self, e)
from tornado.web import RequestHandler import bugsnag class BugsnagRequestHandler(RequestHandler): def _handle_request_exception(self, e): # Set the request info bugsnag.configure_request( user_id = self.request.remote_ip, context = "%s %s" % (self.request.method, self.request.uri.split('?')[0]), request_data = { "url": self.request.full_url(), "method": self.request.method, "arguments": self.request.arguments, "cookies": self.cookies, }, ) # Notify bugsnag bugsnag.notify(e) # Call the parent handler RequestHandler._handle_request_exception(self, e)
Revert "Fix openweather unit tests" This reverts commit 36e100e649f0a337228a6d7375358d23afd544ff. Open Weather Map has reverted back to their old api or something like that...
# -*- coding: utf-8 -*- import bot_mock from pyfibot.modules import module_openweather from utils import check_re bot = bot_mock.BotMock() def test_weather(): regex = u'Lappeenranta, FI: Temperature: \d+.\d\xb0C, feels like: \d+.\d\xb0C, wind: \d+.\d m/s, humidity: \d+%, pressure: \d+ hPa, cloudiness: \d+%' check_re(regex, module_openweather.command_weather(bot, None, "#channel", 'lappeenranta')[1]) def test_forecast(): regex = u'Lappeenranta, FI: tomorrow: \d+.\d-\d+.\d \xb0C \(.*?\), in 2 days: \d+.\d-\d+.\d \xb0C \(.*?\), in 3 days: \d+.\d-\d+.\d \xb0C \(.*?\)' check_re(regex, module_openweather.command_forecast(bot, None, "#channel", 'lappeenranta')[1])
# -*- coding: utf-8 -*- import bot_mock from pyfibot.modules import module_openweather from utils import check_re bot = bot_mock.BotMock() def test_weather(): regex = u'Lappeenranta, FI: Temperature: \d+.\d\xb0C, feels like: \d+.\d\xb0C, wind: \d+.\d m/s, humidity: \d+%, pressure: \d+ hPa, cloudiness: \d+%' check_re(regex, module_openweather.command_weather(bot, None, "#channel", 'lappeenranta')[1]) def test_forecast(): regex = u'Lappeenranta, Finland: tomorrow: \d+.\d-\d+.\d \xb0C \(.*?\), in 2 days: \d+.\d-\d+.\d \xb0C \(.*?\), in 3 days: \d+.\d-\d+.\d \xb0C \(.*?\)' check_re(regex, module_openweather.command_forecast(bot, None, "#channel", 'lappeenranta')[1])
Make ButtonIconText button proptypes explicit
import React, { Component, PropTypes } from 'react'; import IconText from '../IconText'; import css from './ButtonIconText.css'; class ButtonIconText extends Component { constructor(props) { super(props); this.state = { hovering: false, }; } hover(hovering) { this.setState({ hovering, }); } render() { const { onClick, ...other } = this.props; const { hovering } = this.state; return ( <button className={css.button} onClick={onClick} onMouseEnter={() => this.hover(true)} onMouseLeave={() => this.hover(false)} > <IconText hovering={hovering} {...other} /> </button> ); } } ButtonIconText.defaultProps = { disabled: false, }; ButtonIconText.propTypes = { onClick: PropTypes.func.isRequired, disabled: PropTypes.bool, }; export default ButtonIconText;
import React, { Component, PropTypes } from 'react'; import IconText from '../IconText'; import css from './ButtonIconText.css'; class ButtonIconText extends Component { constructor(props) { super(props); this.state = { hovering: false, }; } hover(hovering) { this.setState({ hovering, }); } render() { const { onClick, ...other } = this.props; const { hovering } = this.state; return ( <button className={css.button} onClick={onClick} onMouseEnter={() => this.hover(true)} onMouseLeave={() => this.hover(false)} {...other} > <IconText hovering={hovering} {...other} /> </button> ); } } ButtonIconText.propTypes = { onClick: PropTypes.func.isRequired, }; export default ButtonIconText;
Fix place labels on space cards
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Link from '../../Link/Link'; import css from './SpaceListingCard.css'; const SpaceListingCard = (props) => { const { placeLabel, placeHref, location, size, onPlaceLabelClick, ...rest, } = props; return ( <DestinationListingCard carouselOverlay={ placeLabel && ( <Link onClick={ onPlaceLabelClick } href={ placeHref } className={ css.placeLink } iconClassName={ css.placeLinkIcon } > { placeLabel } </Link> ) } information={ [location, size] } { ...rest } /> ); }; SpaceListingCard.propTypes = { placeLabel: PropTypes.node, placeHref: PropTypes.string, location: PropTypes.node, size: PropTypes.node, price: PropTypes.node, priceUnit: PropTypes.node, onPlaceLabelClick: PropTypes.func, }; export default SpaceListingCard;
import React, { PropTypes } from 'react'; import DestinationListingCard from '../DestinationListingCard/DestinationListingCard'; import Link from '../../Link/Link'; import css from './SpaceListingCard.css'; const SpaceListingCard = (props) => { const { placeLabel, placeHref, location, size, onPlaceLabelClick, ...rest, } = props; return ( <DestinationListingCard carouselOverlay={ placeLabel && placeHref && ( <Link onPlaceLabelClick={ onPlaceLabelClick } href={ placeHref } className={ css.placeLink } iconClassName={ css.placeLinkIcon } > { placeLabel } </Link> ) } information={ [location, size] } { ...rest } /> ); }; SpaceListingCard.propTypes = { placeLabel: PropTypes.node, placeHref: PropTypes.string, location: PropTypes.node, size: PropTypes.node, price: PropTypes.node, priceUnit: PropTypes.node, onPlaceLabelClick: PropTypes.func, }; export default SpaceListingCard;
Fix 404 of trained data vgg16_rotation_translation_brightness_372000...
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf', ) download_data( pkg_name=PKG, path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vamZrczFqb3JoVnM', md5='58a0e819ba141a34b1d68cc5e972615b', ) download_data( pkg_name=PKG, path='trained_data/fcn32s_6000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vd0JUMFZKeVQxaG8', md5='d063161d18129946f6c2878afb5f9067', ) if __name__ == '__main__': main()
#!/usr/bin/env python from jsk_data import download_data def main(): PKG = 'jsk_apc2016_common' download_data( pkg_name=PKG, path='trained_data/vgg16_96000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00', md5='3c993d333cf554684b5162c9f69b20cf', ) download_data( pkg_name=PKG, path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ', md5='58a0e819ba141a34b1d68cc5e972615b', ) download_data( pkg_name=PKG, path='trained_data/fcn32s_6000.chainermodel', url='https://drive.google.com/uc?id=0B9P1L--7Wd2vd0JUMFZKeVQxaG8', md5='d063161d18129946f6c2878afb5f9067', ) if __name__ == '__main__': main()
Update the example proxy list
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.179.12.86:3128", # (Example) - set your own proxy here "example2": "socks4://50.197.210.138:32100", # (Example) "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.179.12.86:3128", # (Example) - set your own proxy here "example2": "176.9.79.126:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Refactor code to match sass preset
import postCSSModulesValues from 'postcss-modules-values' import ExtractTextPlugin from 'extract-text-webpack-plugin' export default { name: 'css-modules', configure ({ pages = [], buildTarget }) { const extractCSS = new ExtractTextPlugin('[name]-[hash].css') const enabled = pages.length > 0 && buildTarget === 'production' const localIdentName = enabled ? '[hash]' : '[path][local]' // importLoaders: use the following postcss-loader in @import statements // modules: enable css-modules const loaders = [ `css?modules&sourceMap&importLoaders=1&localIdentName=${localIdentName}`, 'postcss-loader' ] return { postcss: [ // allow importing values (variables) between css modules // see: https://github.com/css-modules/postcss-modules-values#usage postCSSModulesValues ], module: { loaders: [ { test: /\.css$/, loader: enabled ? extractCSS.extract(...loaders) : ['style', ...loaders].join('!') } ] }, plugins: enabled ? [extractCSS] : [] } } }
import postCSSModulesValues from 'postcss-modules-values' import ExtractTextPlugin from 'extract-text-webpack-plugin' export default { name: 'css-modules', configure ({ pages = [], buildTarget }) { const extractCSS = new ExtractTextPlugin('[name]-[hash]-[ext].css') const enabled = pages.length > 0 && buildTarget === 'production' // importLoaders: use the following postcss-loader in @import statements // modules: enable css-mobules const baseLoader = 'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]-[hash]!postcss-loader' return { postcss: [ // allow importing values (variables) between css modules // see: https://github.com/css-modules/postcss-modules-values#usage postCSSModulesValues ], module: { loaders: [ { test: /\.css$/, loader: enabled ? extractCSS.extract(baseLoader) : `style!${baseLoader}` } ] }, plugins: enabled ? [extractCSS] : [] } } }
Print statements added for profiling
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()
Move `jest.setTimeout` to module scope It didn't work inside the `describe` block.
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; jest.setTimeout(10000); // 10 second timeout describe('example', () => { it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; describe('example', () => { jest.setTimeout(10000); // 10 second timeout it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
Add constant for an edit note request
package com.simplenote.android; public class Constants { /** Name of stored preferences */ public static final String PREFS_NAME = "SimpleNotePrefs"; /** Logging tag prefix */ public static final String TAG = "SimpleNote:"; // Message Codes public static final int MESSAGE_UPDATE_NOTE = 12398; // Activity for result request Codes public static final int REQUEST_LOGIN = 32568; public static final int REQUEST_EDIT = 9138171; // API Base URL public static final String API_BASE_URL = "https://simple-note.appspot.com/api"; public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET }
package com.simplenote.android; public class Constants { /** Name of stored preferences */ public static final String PREFS_NAME = "SimpleNotePrefs"; /** Logging tag prefix */ public static final String TAG = "SimpleNote:"; // Message Codes public static final int MESSAGE_UPDATE_NOTE = 12398; // Activity for result request Codes public static final int REQUEST_LOGIN = 32568; // API Base URL public static final String API_BASE_URL = "https://simple-note.appspot.com/api"; public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET }
Fix an url and use a callable instead of a string
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url import documents.views urlpatterns = [ url(r"^upload/(?P<slug>[^/]*)$", documents.views.upload_file, name="document_put"), url(r"^multiple_upload/(?P<slug>[^/]*)$", documents.views.upload_multiple_files, name="document_put_multiple"), url(r"^(?P<pk>[^/]*)/edit$", documents.views.document_edit, name="document_edit"), url(r"^(?P<pk>[^/]*)/reupload$", documents.views.document_reupload, name="document_reupload"), url(r"^(?P<pk>[^/]*)/download$", documents.views.document_download, name="document_download"), url(r"^(?P<pk>[^/]*)/original$", documents.views.document_download_original, name="document_download_original"), url(r"^(?P<pk>[^/]*)$", documents.views.document_show, name="document_show"), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url import documents.views urlpatterns = [ url(r"^upload/(?P<slug>[^/]*)$", documents.views.upload_file, name="document_put"), url(r"^multiple_upload/(?P<slug>[^/]*)$", documents.views.upload_multiple_files, name="document_put_multiple"), url(r"^(?P<pk>[^/]*)/edit$", documents.views.document_edit, name="document_edit"), url(r"^(?P<pk>[^/]*)/reupload$", 'documents.views.document_reupload', name="document_reupload"), url(r"^(?P<pk>[^/]*)/download$", documents.views.document_download, name="document_download"), url(r"^(?P<pk>[^/]*)/original$", documents.views.document_download_original, name="document_download_original"), url(r"^(?P<pk>[^/]*)$", documents.views.document_show, name="document_show"), ]
Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
Add user-name as parameter, rather than hardcoding TODO check for user-name before attempting to issue request
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/' + process.argv[2] + '/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } });
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/jm-janzen/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } });
Disable inline source map when optimization enabled
'use strict' let sass = require('node-sass') /* * Transform SASS to CSS. * @public * @param {string} folderPath - Path to the folder containing the SASS file. * @param {string} str - SASS. * @param {Object} opts - Options for the task. * @param {function} next - The callback that handles the response. Receives the following properties: err, css. */ module.exports = function(folderPath, str, opts, next) { // Dismiss sourceMap when output should be optimized let map = (opts.optimize===true ? false : true) sass.render({ data : str, includePaths : [ folderPath ], sourceMap : sourceMap, sourceMapEmbed : sourceMap, sourceMapContents : sourceMap }, (err, result) => { if (err!=null) { next(err, null) return false } next(null, result.css.toString()) }) }
'use strict' let sass = require('node-sass') /* * Transform SASS to CSS. * @public * @param {string} folderPath - Path to the folder containing the SASS file. * @param {string} str - SASS. * @param {Object} opts - Options for the task. * @param {function} next - The callback that handles the response. Receives the following properties: err, css. */ module.exports = function(folderPath, str, opts, next) { // Dismiss sourceMap when output should be optimized let map = (opts.optimize===true ? false : true) sass.render({ data : str, includePaths : [ folderPath ], sourceMap : map, sourceMapEmbed : true, sourceMapContents : true }, (err, result) => { if (err!=null) { next(err, null) return false } next(null, result.css.toString()) }) }
Use historic PublicBody in data migration
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification # Use treebeard API # Classification = apps.get_model('publicbody', 'Classification') PublicBody = apps.get_model('publicbody', 'PublicBody') classifications = {} for pb in PublicBody.objects.exclude(classification_slug=''): if pb.classification_slug in classifications: pb.classification = classifications[pb.classification_slug] else: root = Classification.add_root( name=pb.classification_name, slug=pb.classification_slug ) pb.classification = root classifications[pb.classification_slug] = root pb.save() class Migration(migrations.Migration): dependencies = [ ('publicbody', '0006_auto_20171224_0732'), ] operations = [ migrations.RunPython(create_classifications), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-12-24 06:44 from __future__ import unicode_literals from django.db import migrations def create_classifications(apps, schema_editor): from ..models import Classification, PublicBody # Use treebeard API # Classification = apps.get_model('publicbody', 'Classification') # PublicBody = apps.get_model('publicbody', 'PublicBody') classifications = {} for pb in PublicBody.objects.exclude(classification_slug=''): if pb.classification_slug in classifications: pb.classification = classifications[pb.classification_slug] else: root = Classification.add_root( name=pb.classification_name, slug=pb.classification_slug ) pb.classification = root classifications[pb.classification_slug] = root pb.save() class Migration(migrations.Migration): dependencies = [ ('publicbody', '0006_auto_20171224_0732'), ] operations = [ migrations.RunPython(create_classifications), ]
Add comments explaining Foo tags
package magicsql import ( "strings" "testing" "./assert" ) type Foo struct { // ONE turns into "one" for field name, as we auto-lowercase anything not tagged ONE string // TwO is the primary key, but not explicitly given a field name, so it'll be "two" TwO int `sql:",primary"` // Three is explicitly set to "tree" Three bool `sql:"tree"` // Four is just lowercased to "four" Four int // Five is explicitly skipped Five int `sql:"-"` six string } func newFoo() interface{} { return &Foo{} } func TestQueryFields(t *testing.T) { var table = NewMagicTable("foos", newFoo) assert.Equal("one,two,tree,four", strings.Join(table.FieldNames(), ","), "Full field list", t) assert.Equal(4, len(table.sqlFields), "THERE ARE FOUR LIGHTS! Er, fields....", t) } func TestScanStruct(t *testing.T) { var table = NewMagicTable("foos", newFoo) var foo = &Foo{ONE: "blargh"} var ptr = table.ScanStruct(foo)[0].(*NullableField).Value.(*string) assert.Equal(foo.ONE, *ptr, "scanStruct properly pokes into the underlying data", t) *ptr = "foo" assert.Equal("foo", foo.ONE, "yes, this really is a proper pointer", t) }
package magicsql import ( "strings" "testing" "./assert" ) type Foo struct { ONE string TwO int `sql:",primary"` Three bool `sql:"tree"` Four int Five int `sql:"-"` six string } func newFoo() interface{} { return &Foo{} } func TestQueryFields(t *testing.T) { var table = NewMagicTable("foos", newFoo) assert.Equal("one,two,tree,four", strings.Join(table.FieldNames(), ","), "Full field list", t) assert.Equal(4, len(table.sqlFields), "THERE ARE FOUR LIGHTS! Er, fields....", t) } func TestScanStruct(t *testing.T) { var table = NewMagicTable("foos", newFoo) var foo = &Foo{ONE: "blargh"} var ptr = table.ScanStruct(foo)[0].(*NullableField).Value.(*string) assert.Equal(foo.ONE, *ptr, "scanStruct properly pokes into the underlying data", t) *ptr = "foo" assert.Equal("foo", foo.ONE, "yes, this really is a proper pointer", t) }
Remove excessive newlines at the end of file
'use strict'; require('./cookie-functions.js'); require('govuk_publishing_components/components/cookie-banner.js'); window.GOVUK.DEFAULT_COOKIE_CONSENT = { 'essential': true, 'usage': false, 'brexit': false } window.GOVUK.setDefaultConsentCookie = function () { var defaultConsent = { 'essential': true, 'usage': false, 'brexit': false } window.GOVUK.setCookie('cookie_policy', JSON.stringify(defaultConsent), { days: 365 }) } window.GOVUK.approveAllCookieTypes = function () { var approvedConsent = { 'essential': true, 'usage': true, 'brexit': true } window.GOVUK.setCookie('cookie_policy', JSON.stringify(approvedConsent), { days: 365 }) } window.GOVUK.Modules.CookieBanner.prototype.isInCookiesPage = function () { return window.location.pathname === '/cookie-settings' }
'use strict'; require('./cookie-functions.js'); require('govuk_publishing_components/components/cookie-banner.js'); window.GOVUK.DEFAULT_COOKIE_CONSENT = { 'essential': true, 'usage': false, 'brexit': false } window.GOVUK.setDefaultConsentCookie = function () { var defaultConsent = { 'essential': true, 'usage': false, 'brexit': false } window.GOVUK.setCookie('cookie_policy', JSON.stringify(defaultConsent), { days: 365 }) } window.GOVUK.approveAllCookieTypes = function () { var approvedConsent = { 'essential': true, 'usage': true, 'brexit': true } window.GOVUK.setCookie('cookie_policy', JSON.stringify(approvedConsent), { days: 365 }) } window.GOVUK.Modules.CookieBanner.prototype.isInCookiesPage = function () { return window.location.pathname === '/cookie-settings' }
Fix GetCommitContent to actually get commit content The method was accidentally duplicating GetBranchContent.
package gerrit import ( "fmt" "net/url" ) // GetCommit retrieves a commit of a project. // The commit must be visible to the caller. // // Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit func (s *ProjectsService) GetCommit(projectName, commitID string) (*CommitInfo, *Response, error) { u := fmt.Sprintf("projects/%s/commits/%s", url.QueryEscape(projectName), commitID) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(CommitInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err } // GetCommitContent gets the content of a file from a certain commit. // The content is returned as base64 encoded string. // // Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html##get-content-from-commit func (s *ProjectsService) GetCommitContent(projectName, commitID, fileID string) (string, *Response, error) { u := fmt.Sprintf("projects/%s/commits/%s/files/%s/content", url.QueryEscape(projectName), commitID, fileID) return getStringResponseWithoutOptions(s.client, u) }
package gerrit import ( "fmt" "net/url" ) // GetCommit retrieves a commit of a project. // The commit must be visible to the caller. // // Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit func (s *ProjectsService) GetCommit(projectName, commitID string) (*CommitInfo, *Response, error) { u := fmt.Sprintf("projects/%s/commits/%s", url.QueryEscape(projectName), commitID) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } v := new(CommitInfo) resp, err := s.client.Do(req, v) if err != nil { return nil, resp, err } return v, resp, err } // GetCommitContent gets the content of a file from the HEAD revision of a certain branch. // The content is returned as base64 encoded string. // // Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content func (s *ProjectsService) GetCommitContent(projectName, branchID, fileID string) (string, *Response, error) { u := fmt.Sprintf("projects/%s/branches/%s/files/%s/content", url.QueryEscape(projectName), branchID, fileID) return getStringResponseWithoutOptions(s.client, u) }
Fix minor bug in broctl plugin.
import BroControl.plugin import BroControl.config class Napatech(BroControl.plugin.Plugin): def __init__(self): super(Napatech, self).__init__(apiversion=1) def name(self): return 'napatech' def pluginVersion(self): return 1 def init(self): # Use this plugin only if there is a Napatech interface in use for nn in self.nodes(): if nn.type == 'worker' and nn.interface.startswith('napatech::'): return True return False def nodeKeys(self): return ['dedupe_lru_size', 'host_buffer_allowance'] def options(self): return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'), ('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')] def broctl_config(self): script = '' script += '# Settings for configuring Napatech interractions' script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size')) script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance')) return script
import BroControl.plugin import BroControl.config class Napatech(BroControl.plugin.Plugin): def __init__(self): super(Napatech, self).__init__(apiversion=1) def name(self): return 'napatech' def pluginVersion(self): return 1 def init(self): # Use this plugin only if there is a Napatech interface in use for nn in self.nodes(): if nn.type == 'worker' and nn.interface.startswith('napatech::'): return True return False def nodeKeys(self): return ['dedupe_lru_size', 'host_buffer_allowance'] def options(self): return [('dedupe_lru_size', 'int', 1024, 'Size of deduplication lru.'), ('host_buffer_allowance', 'int', 100, 'Host buffer allowance.')] def broctl_config(self): script += '# Settings for configuring Napatech interractions' script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size')) script += '\nredef Napatech::host_buffer_allowance = {0};'.format(self.getOption('host_buffer_allowance')) return script
Fix tests for clear command
//@@author A0142102E package guitests; import seedu.tasklist.testutil.TypicalTestTasks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class ClearCommandTest extends TaskListGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertClearCommandSuccess(); //verify other commands can work after a clear command commandBox.runCommand(TypicalTestTasks.task8.getAddCommand()); commandBox.runCommand("delete 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(); } private void assertClearCommandSuccess() { commandBox.runCommand("clear"); assertListSize(0); assertResultMessage("Your Smart Scheduler has been cleared!"); } }
//@@author A0142102E package guitests; import seedu.tasklist.testutil.TypicalTestTasks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class ClearCommandTest extends TaskListGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertTrue(taskListPanel.isListMatching(td.getTypicalTasks())); assertClearCommandSuccess(); //verify other commands can work after a clear command commandBox.runCommand(TypicalTestTasks.task8.getAddCommand()); assertTrue(taskListPanel.isListMatching(TypicalTestTasks.task8)); commandBox.runCommand("delete 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(); } private void assertClearCommandSuccess() { commandBox.runCommand("clear"); assertListSize(0); assertResultMessage("Your Smart Scheduler has been cleared!"); } }
Remove File Creation Command for UnitTesting
import os.path import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '../')) sys.path.append(os.path.join(os.path.dirname(__file__), '../vCenterShell')) from vCenterShell.pycommon.logging_service import LoggingService class TestLoggingService(unittest.TestCase): def test_logging_service_01(self): log_file_name = "test_log.log" LoggingService("CRITICAL", "DEBUG", None) self.assertFalse(os.path.isfile(log_file_name)) # LoggingService("CRITICAL", "DEBUG", log_file_name) # self.assertTrue(os.path.isfile(log_file_name)) # os.unlink(log_file_name) def test_logging_service_02(self): log_file_name = "test_log.log" LoggingService("DEBUG", "CRITICAL", None) self.assertFalse(os.path.isfile(log_file_name)) # LoggingService("DEBUG", "CRITICAL", log_file_name) # self.assertTrue(os.path.isfile(log_file_name)) # self.assertEquals(os.path.getsize(log_file_name), 0) # os.unlink(log_file_name)
import os.path import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '../')) sys.path.append(os.path.join(os.path.dirname(__file__), '../vCenterShell')) from vCenterShell.pycommon.logging_service import LoggingService class TestLoggingService(unittest.TestCase): def test_logging_service_01(self): log_file_name = "test_log.log" LoggingService("CRITICAL", "DEBUG", log_file_name) self.assertTrue(os.path.isfile(log_file_name)) os.unlink(log_file_name) def test_logging_service_02(self): log_file_name = "test_log.log" LoggingService("DEBUG", "CRITICAL", log_file_name) self.assertTrue(os.path.isfile(log_file_name)) self.assertEquals(os.path.getsize(log_file_name), 0) os.unlink(log_file_name)
Add wrapped raw file copy function that use BufferedReader. And add logic to make directory if target directory isn't exist.
##-*- coding: utf-8 -*- #!/usr/bin/python """ Utilities related to Files. """ import os from io import FileIO, BufferedReader, BufferedWriter __author__ = 'SeomGi, Han' __credits__ = ['SeomGi, Han'] __copyright__ = 'Copyright 2015, Python Utils Project' __license__ = 'MIT' __version__ = '1.0.0' __maintainer__ = 'SeomGi, Han' __email__ = 'iandmyhand@gmail.com' __status__ = 'Production' class FileUtils: def copy_file_stream_to_file(self, file, to_path): self.copy_buffered_io_to_file(BufferedReader(file), to_path) def copy_buffered_io_to_file(self, buffered_io, file_path): os.makedirs(file_path[:file_path.rfind('/') + 1], exist_ok=True) with FileIO(file_path, mode='wb') as raw_output_io: with BufferedWriter(raw_output_io) as writer: while 1: line = buffered_io.readline() if not line: break writer.write(line) buffered_io.close()
##-*- coding: utf-8 -*- #!/usr/bin/python """ Utilities related to Files. """ from io import FileIO, BufferedWriter __author__ = 'SeomGi, Han' __credits__ = ['SeomGi, Han'] __copyright__ = 'Copyright 2015, Python Utils Project' __license__ = 'MIT' __version__ = '1.0.0' __maintainer__ = 'SeomGi, Han' __email__ = 'iandmyhand@gmail.com' __status__ = 'Production' class FileUtils: def copy_buffered_io_to_file(self, buffered_io, file_path): with FileIO(file_path, mode='wb') as raw_output_io: with BufferedWriter(raw_output_io) as writer: while 1: line = buffered_io.readline() if not line: break writer.write(line) buffered_io.close()
Change function calls to field accesses instead In details-for-tree-entry.js, there are several calls to functions of an IndexEntry. However, those are actually fields on an object instead of prototype functions so referring to them as functions will cause a ReferenceError to be thrown. The fix is to not refer to them as functions but to simply refer to them as fields instead. Signed-off-by: Remy Suen <553f7e7fc51e9ff47ae89d5a0ebd06651241b998@gmail.com>
var nodegit = require("../"); var path = require("path"); /** * This shows how to get details from a tree entry or a blob **/ nodegit.Repository.open(path.resolve(__dirname, "../.git")) .then(function(repo) { return repo.getTree("e1b0c7ea57bfc5e30ec279402a98168a27838ac9") .then(function(tree) { var treeEntry = tree.entryByIndex(0); // Tree entry doesn't have any data associated with the actual entry // To get that we need to get the index entry that this points to return repo.refreshIndex().then(function(index) { var indexEntry = index.getByPath(treeEntry.path()); // With the index entry we can now view the details for the tree entry console.log("Entry path: " + indexEntry.path); console.log("Entry time in seconds: " + indexEntry.mtime.seconds()); console.log("Entry oid: " + indexEntry.id.toString()); console.log("Entry size: " + indexEntry.fileSize); }); }); }) .done(function() { console.log("Done!"); });
var nodegit = require("../"); var path = require("path"); /** * This shows how to get details from a tree entry or a blob **/ nodegit.Repository.open(path.resolve(__dirname, "../.git")) .then(function(repo) { return repo.getTree("e1b0c7ea57bfc5e30ec279402a98168a27838ac9") .then(function(tree) { var treeEntry = tree.entryByIndex(0); // Tree entry doesn't have any data associated with the actual entry // To get that we need to get the index entry that this points to return repo.refreshIndex().then(function(index) { var indexEntry = index.getByPath(treeEntry.path()); // With the index entry we can now view the details for the tree entry console.log("Entry path: " + indexEntry.path()); console.log("Entry time in seconds: " + indexEntry.mtime().seconds()); console.log("Entry oid: " + indexEntry.id().toString()); console.log("Entry size: " + indexEntry.fileSize()); }); }); }) .done(function() { console.log("Done!"); });
Add automatic running of info script
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('info', shell.task([ './bin/info homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
Update social account registration text for clarity
@extends('front.layouts.master') @section('title', 'Create Account') @section('description', "") @section('contents') <div class="card"> <div class="card__body card__body--padded"> <h1>Create an Account</h1> <p> There is currently no PCB account registered to this social account. Would you like to create a PCB account with these details? </p> <p> If you wish to associate this social account with an existing PCB account, please log-in to PCB first then log-in to your social account from the settings page. </p> <div class="register__social-details"> <h2>{{ $social['name'] }}</h2> {{ $social['email'] }}<br><br> <a href="{{ $url }}" class="button button--large button--fill button--primary"> <i class="fas fa-check"></i> Create & Proceed </a> </div> </div> </div> @endsection
@extends('front.layouts.master') @section('title', 'Create Account') @section('description', "") @section('contents') <div class="card"> <div class="card__body card__body--padded"> <h1>Create an Account</h1> <p> There is currently no PCB account registered to your social account. Would you like to create a PCB account with these details? </p> <div class="register__social-details"> <h2>{{ $social['name'] }}</h2> {{ $social['email'] }}<br><br> <a href="{{ $url }}" class="button button--large button--fill button--primary"> <i class="fas fa-check"></i> Create & Proceed </a> </div> </div> </div> @endsection
Comment for a slick little trick.
print "Let's practice everything." print "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs." poem = """ \t the lovely world wtih logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 6 print "This should be five: %s" % five def secret_formula(started): """ This is not the Krabby Patty Secret Formula (tm) """ jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 # Notice how 'beans' here was called 'jelly_beans' in the function beans, jars, crates = secret_formula(start_point) print "With a starting point of %d" % start_point print "We'd have %d beans %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" # This part is pretty darn cool. \/ print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
print "Let's practice everything." print "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs." poem = """ \t the lovely world wtih logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 6 print "This should be five: %s" % five def secret_formula(started): """ This is not the Krabby Patty Secret Formula (tm) """ jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) print "With a starting point of %d" % start_point print "We'd have %d beans %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" # This part is pretty darn cool. \/ print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
Add test of mongodb package version
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB package is installed def test_mongodb_is_installed(host): package = host.package('mongodb-org') assert package.is_installed assert package.version.startswith('3.4.7') # check if MongoDB is enabled and running def test_mongod_is_running(host): mongo = host.service('mongod') assert mongo.is_running assert mongo.is_enabled # check if configuration file contains the required line def test_mongod_config_file(File): config_file = File('/etc/mongod.conf') assert config_file.contains('port: 27017') assert config_file.contains('bindIp: 127.0.0.1') assert config_file.is_file # check if mongod process is listening on localhost def test_mongod_is_listening(host): port = host.socket('tcp://127.0.0.1:27017') assert port.is_listening
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB package is installed def test_mongodb_is_installed(host): package = host.package('mongodb-org') assert package.is_installed # check if MongoDB is enabled and running def test_mongod_is_running(host): mongo = host.service('mongod') assert mongo.is_running assert mongo.is_enabled # check if configuration file contains the required line def test_mongod_config_file(File): config_file = File('/etc/mongod.conf') assert config_file.contains('port: 27017') assert config_file.contains('bindIp: 127.0.0.1') assert config_file.is_file # check if mongod process is listening on localhost def test_mongod_is_listening(host): port = host.socket('tcp://127.0.0.1:27017') assert port.is_listening
Make sure we're not blocking secp256k1 tests
<?php namespace BitWasp\Bitcoin\Tests; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc; use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1; class AbstractTestCase extends \PHPUnit_Framework_TestCase { /** * @return array */ public function getEcAdapters() { $math = Bitcoin::getMath(); $generator = Bitcoin::getGenerator(); $adapters = [ [new PhpEcc($math, $generator)] ]; if (getenv('TRAVIS_PHP_VERSION') !== 'hhvm' && extension_loaded('secp256k1')) { $adapters[] = [new Secp256k1($math, $generator)]; } return $adapters; } }
<?php namespace BitWasp\Bitcoin\Tests; use BitWasp\Bitcoin\Bitcoin; use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc; use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1; class AbstractTestCase extends \PHPUnit_Framework_TestCase { /** * @return array */ public function getEcAdapters() { $math = Bitcoin::getMath(); $generator = Bitcoin::getGenerator(); $adapters = [ [new PhpEcc($math, $generator)] ]; if (!defined('HHVM_VERSION') && extension_loaded('secp256k1')) { $adapters[] = [new Secp256k1($math, $generator)]; } return $adapters; } }
Test case test_connect_remote() has been passing consistently for some times. Let's remove the @expectedFailure marker from it. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@133294 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test lldb 'process connect' command. """ import os import unittest2 import lldb import pexpect from lldbtest import * class ConnectRemoteTestCase(TestBase): mydir = "connect_remote" def test_connect_remote(self): """Test "process connect connect:://localhost:12345".""" # First, we'll start a fake debugserver (a simple echo server). fakeserver = pexpect.spawn('./EchoServer.py') # Turn on logging for what the child sends back. if self.TraceOn(): fakeserver.logfile_read = sys.stdout # Schedule the fake debugserver to be shutting down during teardown. def shutdown_fakeserver(): fakeserver.close() self.addTearDownHook(shutdown_fakeserver) # Wait until we receive the server ready message before continuing. fakeserver.expect_exact('Listening on localhost:12345') # Connect to the fake server.... self.runCmd("process connect connect://localhost:12345") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" Test lldb 'process connect' command. """ import os import unittest2 import lldb import pexpect from lldbtest import * class ConnectRemoteTestCase(TestBase): mydir = "connect_remote" @unittest2.expectedFailure def test_connect_remote(self): """Test "process connect connect:://localhost:12345".""" # First, we'll start a fake debugserver (a simple echo server). fakeserver = pexpect.spawn('./EchoServer.py') # Turn on logging for what the child sends back. if self.TraceOn(): fakeserver.logfile_read = sys.stdout # Schedule the fake debugserver to be shutting down during teardown. def shutdown_fakeserver(): fakeserver.close() self.addTearDownHook(shutdown_fakeserver) # Wait until we receive the server ready message before continuing. fakeserver.expect_exact('Listening on localhost:12345') # Connect to the fake server.... self.runCmd("process connect connect://localhost:12345") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Rename internal structures to shorter names. Change return type of ParseString() to Document instead of *Document
package dom /* * Implements a very small, very non-compliant subset of the DOM Core Level 2 */ // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247 type Node interface { NodeName() string; } // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614 type Element interface { Node; TagName() string; // GetAttribute(name string) string; // SetAttribute(name string, value string); } // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document type Document interface { Node; DocumentElement() Element; } // internal structures that implement the above public interfaces type elem struct {} func (e *elem) NodeName() string { return "elem.NodeName() not implemented"; } func (e *elem) TagName() string { return e.NodeName(); } type doc struct {} func (d *doc) NodeName() string { return ""; } func (d *doc) DocumentElement() Element { return new(elem); } func ParseString(s string) Document { var d = new(doc); return d; }
package dom /* * Implements a very small, very non-compliant subset of the DOM Core Level 2 */ // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247 type Node interface { NodeName() string; } // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614 type Element interface { Node; TagName() string; // GetAttribute(name string) string; // SetAttribute(name string, value string); } // DOM2: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document type Document interface { Node; DocumentElement() Element; } // internal structures that implements the above public interfaces type elementImpl struct {} func (e *elementImpl) NodeName() string { return ""; } func (e *elementImpl) TagName() string { return e.NodeName(); } type documentImpl struct {} func (d *documentImpl) NodeName() string { return ""; } func (d *documentImpl) DocumentElement() Element { return new(elementImpl); } func ParseString(s string) *documentImpl { var d = new(documentImpl); return d; }
Use exception handling with decorator
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) @monads.handle_exception def wrapper(*args, **kwargs): if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError('Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) return wrapper
''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) def wrapper(*args, **kwargs): try: if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError( 'Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) except Exception as e: return monads.NoneMonad(e) return wrapper
Increase intent-listeners coverage on LinkDeletedImpl. Change-Id: Ibddecf61379ef34f2d2fd90adc1a512188583fbd Signed-off-by: Victor Mota <a399842758ce81a1b2704ada69a36369cee4aa4d@atlantico.com.br>
/* * Copyright (c) 2015 Hewlett Packard Enterprise Development LP. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.nic.listeners.impl; import org.junit.Before; import org.junit.Test; import org.powermock.api.mockito.PowerMockito; import static org.junit.Assert.assertNotNull; /** * Created by yrineu on 12/01/16. */ public class LinkDeletedImplTest { private LinkDeletedImpl linkDeletedMock; @Before public void setUp() { linkDeletedMock = PowerMockito.spy(new LinkDeletedImpl()); } @Test public void testTimestampNotNull() { assertNotNull(linkDeletedMock.getTimeStamp()); } }
/* * Copyright (c) 2015 Hewlett Packard Enterprise Development LP. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.nic.listeners.impl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertNotNull; @PrepareForTest({LinkDeletedImpl.class}) @RunWith(PowerMockRunner.class) /** * Created by yrineu on 12/01/16. */ public class LinkDeletedImplTest { private LinkDeletedImpl linkDeletedMock; @Before public void setUp() { linkDeletedMock = PowerMockito.spy(new LinkDeletedImpl()); } @Test public void testTimestampNotNull() { assertNotNull(linkDeletedMock.getTimeStamp()); } }
Return Promise.reject if agent not found
'use strict'; var Promise = require('promise'); var Connection = require('../Connection'); /** * A local connection. * @param {LocalTransport} transport * @param {string | number} id * @param {function} receive * @constructor */ function LocalConnection(transport, id, receive) { this.transport = transport; this.id = id; // register the agents receive function if (this.id in this.transport.agents) { throw new Error('Agent with id ' + id + ' already exists'); } this.transport.agents[this.id] = receive; // ready state this.ready = Promise.resolve(this); } /** * Send a message to an agent. * @param {string} to * @param {*} message * @return {Promise} returns a promise which resolves when the message has been sent */ LocalConnection.prototype.send = function (to, message) { var callback = this.transport.agents[to]; if (!callback) { return Promise.reject(new Error('Agent with id ' + to + ' not found')); } // invoke the agents receiver as callback(from, message) callback(this.id, message); return Promise.resolve(); }; /** * Close the connection */ LocalConnection.prototype.close = function () { delete this.transport.agents[this.id]; }; module.exports = LocalConnection;
'use strict'; var Promise = require('promise'); var Connection = require('../Connection'); /** * A local connection. * @param {LocalTransport} transport * @param {string | number} id * @param {function} receive * @constructor */ function LocalConnection(transport, id, receive) { this.transport = transport; this.id = id; // register the agents receive function if (this.id in this.transport.agents) { throw new Error('Agent with id ' + id + ' already exists'); } this.transport.agents[this.id] = receive; // ready state this.ready = Promise.resolve(this); } /** * Send a message to an agent. * @param {string} to * @param {*} message * @return {Promise} returns a promise which resolves when the message has been sent */ LocalConnection.prototype.send = function (to, message) { var callback = this.transport.agents[to]; if (!callback) { throw new Error('Agent with id ' + to + ' not found'); } // invoke the agents receiver as callback(from, message) callback(this.id, message); return Promise.resolve(); }; /** * Close the connection */ LocalConnection.prototype.close = function () { delete this.transport.agents[this.id]; }; module.exports = LocalConnection;
Fix for automatically changing due dates.
/** Convert a date/time to a nice Date object. Example: 2014-08-21 14:38:00 UTC -> [Date object] */ function convert_date_time(date) { var arr_date = date.split(' '); var iso_date = arr_date[0] + 'T' + arr_date[1] + 'Z'; return moment(iso_date); } /** Localize the date with a specified locale format string. */ function localize_date(actual_date_div, date_div, format) { if (actual_date_div.value !== '') { var date = moment(actual_date_div.value); date_div.value = date.format(format); } } /** Localize the date/time with a specified locale format string. */ function localize_datetime(actual_date_div, date_div, format) { if (actual_date_div.value.indexOf(' ') > -1) { var date = convert_date_time(actual_date_div.value); date_div.value = date.format(format); // The actual_date_div needs to be updated too, for some reason. actual_date_div.value = date.format('YYYY-MM-DD HH:mm:ss'); } }
/** Convert a date/time to a nice Date object. Example: 2014-08-21 14:38:00 UTC -> [Date object] */ function convert_date_time(date) { var arr_date = date.split(' '); var iso_date = arr_date[0] + 'T' + arr_date[1] + 'Z'; return moment(iso_date); } /** Localize the date with a specified locale format string. */ function localize_date(actual_date_div, date_div, format) { if (actual_date_div.value !== '') { var date = moment(actual_date_div.value); date_div.value = date.format(format); } } /** Localize the date/time with a specified locale format string. */ function localize_datetime(actual_date_div, date_div, format) { if (actual_date_div.value.indexOf(' ') > -1) { var date = convert_date_time(actual_date_div.value); date_div.value = date.format(format); } }
Fix method signature in DocBlock
<?php namespace Illuminate\Support\Facades; /** * @method static string current() * @method static string full() * @method static string previous($fallback = false) * @method static string to(string $path, $extra = [], bool $secure = null) * @method static string secure(string $path, array $parameters = []) * @method static string asset(string $path, bool $secure = null) * @method static string route(string $name, $parameters = [], bool $absolute = true) * @method static string action(string $action, $parameters = [], bool $absolute = true) * @method static \Illuminate\Contracts\Routing\UrlGenerator setRootControllerNamespace(string $rootNamespace) * @method static string signedRoute(string $name, array $parameters = [], \DateTimeInterface|\DateInterval|int $expiration = null) * @method static string temporarySignedRoute(string $name, \DateTimeInterface|\DateInterval|int $expiration, array $parameters = []) * @method static string hasValidSignature(\Illuminate\Http\Request $request, bool $absolute) * @method static void defaults(array $defaults) * * @see \Illuminate\Routing\UrlGenerator */ class URL extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'url'; } }
<?php namespace Illuminate\Support\Facades; /** * @method static string current() * @method static string full() * @method static string previous($fallback = false) * @method static string to(string $path, $extra = [], bool $secure = null) * @method static string secure(string $path, array $parameters = []) * @method static string asset(string $path, bool $secure = null) * @method static string route(string $name, $parameters = [], bool $absolute = true) * @method static string action(string $action, $parameters = [], bool $absolute = true) * @method static \Illuminate\Contracts\Routing\UrlGenerator setRootControllerNamespace(string $rootNamespace) * @method static string signedRoute(string $name, array $parameters = [], \DateTimeInterface|int $expiration = null) * @method static string temporarySignedRoute(string $name, \DateTimeInterface|int $expiration, array $parameters = []) * @method static string hasValidSignature(\Illuminate\Http\Request $request, bool $absolute) * @method static void defaults(array $defaults) * * @see \Illuminate\Routing\UrlGenerator */ class URL extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'url'; } }
Make the error goes away
<div class="wrapper"> <div class="container"> <h1>Welcome</h1> <?php if(isset($_SESSION['error'])) { if ($_SESSION['error'] > 1) { foreach ($_SESSION['error'] as $item) { ?> <p> <?php echo $item; ?> </p> <?php echo '<br /><br />'; } } else { ?> <p> <?php echo $_SESSION['error']; ?> </p> <?php } } else { } unset($_SESSION['error']); ?> <form class="form" autocomplete="off" method="post" action="<?php echo base_url("user/doLogin") ?>"> <input type="text" name='username' placeholder="Username" placeholder="Email Address" required="" autofocus="" > <input type="password" name="password" placeholder="Password" required=""> <button type="submit" id="login-button">Login</button> </form> </div> </div>
<div class="wrapper"> <div class="container"> <h1>Welcome</h1> <?php if(isset($_SESSION['error'])) { if ($_SESSION['error'] > 1) { foreach ($_SESSION['error'] as $item) { ?> <p> <?php echo $item; ?> </p> <?php echo '<br /><br />'; } } else { ?> <p> <?php echo $_SESSION['error']; ?> </p> <?php } } else { } ?> <form class="form" autocomplete="off" method="post" action="<?php echo base_url("user/doLogin") ?>"> <input type="text" name='username' placeholder="Username" placeholder="Email Address" required="" autofocus="" > <input type="password" name="password" placeholder="Password" required=""> <button type="submit" id="login-button">Login</button> </form> </div> </div>
Add fuel-download to installed scripts
"""Installation script.""" from os import path from setuptools import find_packages, setup HERE = path.abspath(path.dirname(__file__)) with open(path.join(HERE, 'README.rst')) as f: LONG_DESCRIPTION = f.read().strip() setup( name='fuel', version='0.1a1', # PEP 440 compliant description='Data pipeline framework for machine learning', long_description=LONG_DESCRIPTION, url='https://github.com/bartvm/fuel.git', author='Universite de Montreal', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Utilities', 'Topic :: Scientific/Engineering', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], keywords='dataset data iteration pipeline processing', packages=find_packages(exclude=['tests']), install_requires=['six', 'picklable_itertools', 'toolz', 'pyyaml', 'h5py', 'tables'], scripts=['bin/fuel-convert', 'bin/fuel-download'] )
"""Installation script.""" from os import path from setuptools import find_packages, setup HERE = path.abspath(path.dirname(__file__)) with open(path.join(HERE, 'README.rst')) as f: LONG_DESCRIPTION = f.read().strip() setup( name='fuel', version='0.1a1', # PEP 440 compliant description='Data pipeline framework for machine learning', long_description=LONG_DESCRIPTION, url='https://github.com/bartvm/fuel.git', author='Universite de Montreal', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Utilities', 'Topic :: Scientific/Engineering', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], keywords='dataset data iteration pipeline processing', packages=find_packages(exclude=['tests']), install_requires=['six', 'picklable_itertools', 'toolz', 'pyyaml', 'h5py', 'tables'], scripts=['bin/fuel-convert'] )
Update comment to point to node library install
// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
// Download the helper library from https://www.twilio.com/docs/python/install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
Check that pushState and replaceState exist on window before trying to use it
const Intent = require('./intent'); const LocationFactory = function(_window) { _window = _window || {}; const history = _window.history; const ChangeLocation = new Intent((path) => { return path; }); const Location = {}; Location.Navigate = function(path) { if (history && history.pushState) { history.pushState({path: path}, null, path); } ChangeLocation(path); }; Location.Redirect = function(path) { if (history && history.replaceState) { history.replaceState({path: path}, null, path); } ChangeLocation(path); }; Location.subscribe = function(...args) { ChangeLocation.subscribe(...args); }; if (_window) { _window.onpopstate = function(event) { if (event.state && event.state.path) { ChangeLocation(event.state.path); } }; } return Location; }; module.exports = LocationFactory;
const Intent = require('./intent'); const LocationFactory = function(_window) { _window = _window || {}; const history = _window.history; const ChangeLocation = new Intent((path) => { return path; }); const Location = {}; Location.Navigate = function(path) { if (history) { history.pushState({path: path}, null, path); } ChangeLocation(path); }; Location.Redirect = function(path) { if (history) { history.replaceState({path: path}, null, path); } ChangeLocation(path); }; Location.subscribe = function(...args) { ChangeLocation.subscribe(...args); }; if (_window) { _window.onpopstate = function(event) { if (event.state && event.state.path) { ChangeLocation(event.state.path); } }; } return Location; }; module.exports = LocationFactory;
fix: Rename prop key -> sitekey key is reserved attribute.
import recaptcha from './recaptcha.js'; let widgetId = null; export default { props: { sitekey: { type: String, required: true }, options: { type: Object, default() { return {}; } } }, created() { recaptcha.checkRecaptchaLoad(); }, mounted() { const self = this; const opts = Object.assign({}, this.options, { callback: this.emitVerify, 'expired-callback': this.emitExpired }); recaptcha.render(this.$refs.container, this.key, opts) .then((id) => { widgetId = id; self.$emit('render', widgetId); }); }, methods: { reset() { recaptcha.reset(widgetId); }, emitVerify(response) { this.$emit('verify', response); }, emitExpired() { this.$emit('expired'); } }, events: { recaptchaReset() { this.reset(); } }, render(h) { return ( <div ref="container"></div> ); } };
import recaptcha from './recaptcha.js'; let widgetId = null; export default { props: { key: { type: String, required: true }, options: { type: Object, default() { return {}; } } }, created() { recaptcha.checkRecaptchaLoad(); }, mounted() { const self = this; const opts = Object.assign({}, this.options, { callback: this.emitVerify, 'expired-callback': this.emitExpired }); recaptcha.render(this.$refs.container, this.key, opts) .then((id) => { widgetId = id; self.$emit('render', widgetId); }); }, methods: { reset() { recaptcha.reset(widgetId); }, emitVerify(response) { this.$emit('verify', response); }, emitExpired() { this.$emit('expired'); } }, events: { recaptchaReset() { this.reset(); } }, render(h) { return ( <div ref="container"></div> ); } };
Remove stray character breaking scripts.
/** * Latvian translation for foundation-datepicker * Artis Avotins <artis@apit.lv> */ ;(function($){ $.fn.fdatepicker.dates['lv'] = { days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"], daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"], daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"], months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."], today: "Šodien", weekStart: 1 }; }(jQuery));
w/** * Latvian translation for foundation-datepicker * Artis Avotins <artis@apit.lv> */ ;(function($){ $.fn.fdatepicker.dates['lv'] = { days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"], daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"], daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"], months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."], today: "Šodien", weekStart: 1 }; }(jQuery));
Define frames per second in floating point. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1163 542714f4-19e9-0310-aa3c-eee0fc999fb1
// // $Id: ActionSequence.java,v 1.3 2002/03/27 21:51:33 mdb Exp $ package com.threerings.cast; import java.awt.Point; import java.io.Serializable; /** * The action sequence class describes a particular character animation * sequence. An animation sequence consists of one or more frames of * animation, renders at a particular frame rate, and has an origin point * that specifies the location of the base of the character in relation to * the bounds of the animation images. */ public class ActionSequence implements Serializable { /** The action sequence name. */ public String name; /** The number of frames per second to show when animating. */ public float framesPerSecond; /** The position of the character's base for this sequence. */ public Point origin = new Point(); /** * Returns a string representation of this action sequence. */ public String toString () { return "[name=" + name + ", framesPerSecond=" + framesPerSecond + ", origin=" + origin + "]"; } }
// // $Id: ActionSequence.java,v 1.2 2001/11/27 08:09:34 mdb Exp $ package com.threerings.cast; import java.awt.Point; import java.io.Serializable; /** * The action sequence class describes a particular character animation * sequence. An animation sequence consists of one or more frames of * animation, renders at a particular frame rate, and has an origin point * that specifies the location of the base of the character in relation to * the bounds of the animation images. */ public class ActionSequence implements Serializable { /** The action sequence name. */ public String name; /** The number of frames per second to show when animating. */ public int framesPerSecond; /** The position of the character's base for this sequence. */ public Point origin = new Point(); /** * Returns a string representation of this action sequence. */ public String toString () { return "[name=" + name + ", framesPerSecond=" + framesPerSecond + ", origin=" + origin + "]"; } }
Change retention policy of Required Parameter to runtime.
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openlmis.report.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface RequiredParam { }
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openlmis.report.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target(ElementType.FIELD) public @interface RequiredParam { }
Add a test to check for regular object reference count https://bugzilla.gnome.org/show_bug.cgi?id=639949
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') class TestReferenceCounting(unittest.TestCase): def testRegularObject(self): obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(gobject.GObject) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') self.assertEquals(obj.__grefcount__, 1) class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
Add exit statement in script
// Messages sent on a regular schedule var config = require('./config'); var services = require('./services'); var bot = require('./bot'); var bots = {}; config.bots.forEach(function (bot) { bots[bot.groupLocalID] = bot; }); var send = function (msg) { bot.postMessage(bots['1'].botID, msg); //bot.postMessage(bots['2'].botID, msg); }; var sendRandomDesignerExcuse = function () { services.getRandomDesignerExcuse(function (excuse) { if (excuse) { send('Designer excuse: ' + excuse); } }); }; if (Math.random() < 0.5) { services.getRandomDeveloperExcuse(function (excuse) { if (excuse) { send('Developer excuse: ' + excuse); } else { // designer excuse does not depend on external request, so it always succeeds sendRandomDesignerExcuse(); } }); } else { sendRandomDesignerExcuse(); } process.exit();
// Messages sent on a regular schedule var config = require('./config'); var services = require('./services'); var bot = require('./bot'); var bots = {}; config.bots.forEach(function (bot) { bots[bot.groupLocalID] = bot; }); var send = function (msg) { bot.postMessage(bots['1'].botID, msg); //bot.postMessage(bots['2'].botID, msg); }; var sendRandomDesignerExcuse = function () { services.getRandomDesignerExcuse(function (excuse) { if (excuse) { send('Designer excuse: ' + excuse); } }); }; if (Math.random() < 0.5) { services.getRandomDeveloperExcuse(function (excuse) { if (excuse) { send('Developer excuse: ' + excuse); } else { // designer excuse does not depend on external request, so it always succeeds sendRandomDesignerExcuse(); } }); } else { sendRandomDesignerExcuse(); }
Refactor `validateSelfClosingTags` to handle new token structure
var utils = require('../utils') , selfClosing = require('void-elements') module.exports = function () {} module.exports.prototype = { name: 'validateSelfClosingTags' , configure: function (options) { utils.validateTrueOptions(this.name, options) } , lint: function (file, errors) { var isXml file.iterateTokensByType('doctype', function (token) { isXml = token.val === 'xml' }) if (!isXml) { file.iterateTokensByType('tag', function (token) { var nextToken = file.getToken(token._index + 1) if (nextToken.type === 'slash' && selfClosing[token.val]) { errors.add('Unnecessary self closing tag', token.line) } }) } } }
var utils = require('../utils') , selfClosing = require('void-elements') module.exports = function () {} module.exports.prototype = { name: 'validateSelfClosingTags' , configure: function (options) { utils.validateTrueOptions(this.name, options) } , lint: function (file, errors) { var isXml file.iterateTokensByType('doctype', function (token) { isXml = token.val === 'xml' }) if (!isXml) { file.iterateTokensByType('tag', function (token) { if (token.selfClosing && selfClosing[token.val]) { errors.add('Unnecessary self closing tag', token.line) } }) } } }
Use pytest.skip so we can check the test wasn't skipped on the CI.
import os import subprocess import pathlib import pytest from django.conf import settings from django.test import TestCase class MakeMessagesCommandRunTestCase(TestCase): """ Sanity check to make sure makemessages runs to completion. """ # this test can make changes to committed files, so only run it # on the CI server @pytest.mark.skipif('CI' not in os.environ or not os.environ['CI'], reason="runs only on CI server") def test_command_succeeds_without_postgres(self): """ Test that we can run makemessages when postgres is not activated. """ repo_root = pathlib.Path(settings.BASE_DIR).parent cmd = ["make", "makemessages"] env = os.environ.copy() # We fake postgres not being available, by setting the wrong IP address. # hopefully postgres isn't running at 127.0.0.2! env.update({"DATA_DB_HOST": "127.0.0.2"}) subprocess.check_output( cmd, env=env, cwd=str(repo_root) )
import os import subprocess import pathlib from django.conf import settings from django.test import TestCase class MakeMessagesCommandRunTestCase(TestCase): """ Sanity check to make sure makemessages runs to completion. """ def test_command_succeeds_without_postgres(self): """ Test that we can run makemessages when postgres is not activated. """ # this test can make changes to committed files, so only run it # on the CI server if 'CI' not in os.environ or not os.environ['CI']: return repo_root = pathlib.Path(settings.BASE_DIR).parent cmd = ["make", "makemessages"] env = os.environ.copy() # We fake postgres not being available, by setting the wrong IP address. # hopefully postgres isn't running at 127.0.0.2! env.update({"DATA_DB_HOST": "127.0.0.2"}) subprocess.check_output( cmd, env=env, cwd=str(repo_root) )
Use out with out, err with err.
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.java; import playn.core.LogImpl; class JavaLog extends LogImpl { @Override protected void logImpl(Level level, String msg, Throwable e) { switch (level) { default: System.out.println(msg); if (e != null) e.printStackTrace(System.out); break; case WARN: case ERROR: System.err.println(msg); if (e != null) e.printStackTrace(System.err); break; } } }
/** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.java; import playn.core.LogImpl; class JavaLog extends LogImpl { @Override protected void logImpl(Level level, String msg, Throwable e) { switch (level) { default: System.out.println(msg); if (e != null) e.printStackTrace(System.err); break; case WARN: case ERROR: System.err.println(msg); if (e != null) e.printStackTrace(System.out); break; } } }
Refactor (to clarify the flow)
package main import ( "fmt" "math/rand" "strconv" "time" "github.com/eferro/go-snmpqueries/pkg/snmpquery" ) func generateRandomQueries(input chan snmpquery.Query) { queryId := 0 for { query := snmpquery.Query{ Id: queryId, Query: "Fake query " + strconv.Itoa(queryId), Destination: "Fake destination " + strconv.Itoa(queryId), } input <- query queryId += 1 time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) } } func processQueries(input chan snmpquery.Query, processed chan snmpquery.Query) { for query := range input { snmpquery.HandleQuery(&query) processed <- query } } func printResults(processed chan snmpquery.Query) { for query := range processed { fmt.Println(query.Query, query.Response) } } func main() { input := make(chan snmpquery.Query) processed := make(chan snmpquery.Query) go generateRandomQueries(input) go processQueries(input, processed) printResults(processed) }
package main import ( "fmt" "math/rand" "strconv" "time" "github.com/eferro/go-snmpqueries/pkg/snmpquery" ) func generateRandomQueries() <-chan snmpquery.Query { out := make(chan snmpquery.Query) go func() { queryId := 0 for { query := snmpquery.Query{ Id: queryId, Query: "Fake query " + strconv.Itoa(queryId), Destination: "Fake destination " + strconv.Itoa(queryId), } out <- query queryId += 1 time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) } }() return out } func main() { input := generateRandomQueries() processed := make(chan snmpquery.Query) go func() { for query := range input { snmpquery.HandleQuery(&query) processed <- query } }() for query := range processed { fmt.Println(query.Query, query.Response) } }
Simplify box2d debug renderer init
/* * Copyright 2014-2015 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kotcrab.vis.runtime.system.physics; import com.artemis.BaseSystem; import com.artemis.annotations.Wire; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.kotcrab.vis.runtime.system.CameraManager; import com.kotcrab.vis.runtime.util.AfterSceneInit; /** @author Kotcrab */ @Wire public class Box2dDebugRenderSystem extends BaseSystem implements AfterSceneInit { private CameraManager cameraManager; private PhysicsSystem physicsSystem; private Box2DDebugRenderer debugRenderer; @Override public void afterSceneInit () { debugRenderer = new Box2DDebugRenderer(); } @Override protected void processSystem () { debugRenderer.render(physicsSystem.getPhysicsWorld(), cameraManager.getCombined()); } }
/* * Copyright 2014-2015 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kotcrab.vis.runtime.system.physics; import com.artemis.BaseSystem; import com.artemis.annotations.Wire; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.kotcrab.vis.runtime.system.CameraManager; /** @author Kotcrab */ @Wire public class Box2dDebugRenderSystem extends BaseSystem { private CameraManager cameraManager; private PhysicsSystem physicsSystem; private Box2DDebugRenderer debugRenderer; public Box2dDebugRenderSystem () { Gdx.app.postRunnable(new Runnable() { @Override public void run () { debugRenderer = new Box2DDebugRenderer(); } }); } @Override protected void processSystem () { if(debugRenderer != null) debugRenderer.render(physicsSystem.getPhysicsWorld(), cameraManager.getCombined()); } }
Call descriptor when a child is added
udefine(function() { return function(Factory, groupInstance) { return function() { var child = arguments[0]; var args = 2 <= arguments.length ? [].slice.call(arguments, 1) : []; if (!( child instanceof Factory)) { if ( typeof child === 'string') { if (Object.hasOwnProperty.call(store, child)) { child = new Factory(Factory.store[child]); } } else { child = new Factory(child); } } groupInstance.push(child); child.parent = this; child.apply(args); child.trigger('add', child, args); }; }; });
udefine(function() { return function(Factory, groupInstance) { return function() { var child = arguments[0]; var args = 2 <= arguments.length ? [].slice.call(arguments, 1) : []; if (!( child instanceof Factory)) { if ( typeof child === 'string') { if (Object.hasOwnProperty.call(store, child)) { child = new Factory(Factory.store[child], args); } } else { child = new Factory(child, args); } } groupInstance.push(child); child.parent = this; child.trigger('add', child, args); }; }; });
Remove unnecessary compat code from ActiveManager
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ class ActiveManager(models.Manager): """ Returns only active objects. """ def get_queryset(self): return super(ActiveManager, self).get_queryset().filter(is_active__exact=True) class ActiveModel(models.Model): """ An abstract base class model that provides an is_active field and attach an ActiveManager. """ is_active = models.BooleanField(default=True, db_index=True) # Managers objects = models.Manager() active = ActiveManager() class Meta: abstract = True class DatedModel(models.Model): """ An abstract base class model that provides a created and a updated fields to store creation date and last updated date. """ created = models.DateTimeField(auto_now_add=True, verbose_name=_('Creation date')) updated = models.DateTimeField(auto_now=True, verbose_name=_('Update date')) class Meta: abstract = True
# -*- coding: utf-8 -*- # Standard library imports from __future__ import unicode_literals # Third party imports from django.db import models from django.utils.translation import ugettext_lazy as _ # Local application / specific library imports class ActiveManager(models.Manager): """ Returns only active objects. """ def get_queryset(self): super_self = super(ActiveManager, self) get_queryset = (super_self.get_query_set if hasattr(super_self, 'get_query_set') else super_self.get_queryset) return get_queryset().filter(is_active__exact=True) class ActiveModel(models.Model): """ An abstract base class model that provides an is_active field and attach an ActiveManager. """ is_active = models.BooleanField(default=True, db_index=True) # Managers objects = models.Manager() active = ActiveManager() class Meta: abstract = True class DatedModel(models.Model): """ An abstract base class model that provides a created and a updated fields to store creation date and last updated date. """ created = models.DateTimeField(auto_now_add=True, verbose_name=_('Creation date')) updated = models.DateTimeField(auto_now=True, verbose_name=_('Update date')) class Meta: abstract = True
Remove useless wrapper function and cleanup WebView a bit Signed-off-by: Victor Porof <7d8eebacd0931807085fa6b9af29638ed74e0886@mozilla.com>
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * React doesn't support non-HTML attributes unless the element is a custom * element which must have a hyphen in the tag name. This means React can't * render most of the attributes of a <webview> so we use this <web-view> as a * wrapper. */ class WebView extends HTMLElement { createdCallback() { this.webview = document.createElement('webview'); for (const { name, value } of Array.from(this.attributes)) { this.webview.setAttribute(name, value); } const shadow = this.createShadowRoot(); shadow.appendChild(this.webview); } attributeChangedCallback(name, oldValue, newValue) { if (newValue) { this.webview.setAttribute(name, newValue); } else { this.webview.removeAttribute(name); } } } document.registerElement('web-view', WebView);
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * React doesn't support non-HTML attributes unless the element is a custom * element which must have a hyphen in the tag name. This means React can't * render most of the attributes of a <webview> so we use this <web-view> as a * wrapper. */ (function() { class WebView extends HTMLElement { createdCallback() { const shadow = this.createShadowRoot(); this.webview = document.createElement('webview'); for (let i = 0; i < this.attributes.length; i++) { const attr = this.attributes[i]; this.webview.setAttribute(attr.name, attr.value); } shadow.appendChild(this.webview); } attributeChangedCallback(name, oldValue, newValue) { if (newValue) { this.webview.setAttribute(name, newValue); } else { this.webview.removeAttribute(name); } } } document.registerElement('web-view', WebView); }());
Update the authentication backend with upcoming features
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): supports_anonymous_user = False supports_object_permissions = False supports_inactive_user = False def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if '$' in user.password: if user.check_password(password): user.password = sha1(password).hexdigest() user.save() return user else: if user.password == sha1(password).hexdigest(): return user return None
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if '$' in user.password: if user.check_password(password): user.password = sha1(password).hexdigest() user.save() return user else: if user.password == sha1(password).hexdigest(): return user return None
Add class to enable loader
<?php namespace OpenOrchestra\UserBundle\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; /** * Class AddSubmitButtonSubscriber */ class AddSubmitButtonSubscriber implements EventSubscriberInterface { /** * @param FormEvent $event */ public function postSetData(FormEvent $event) { $form = $event->getForm(); $parameter = array('label' => 'open_orchestra_base.form.submit', 'attr' => array('class' => 'submit_form')); $form->add('submit', 'submit', $parameter); } /** * @return array The event names to listen to */ public static function getSubscribedEvents() { return array( FormEvents::POST_SET_DATA => 'postSetData', ); } }
<?php namespace OpenOrchestra\UserBundle\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; /** * Class AddSubmitButtonSubscriber */ class AddSubmitButtonSubscriber implements EventSubscriberInterface { /** * @param FormEvent $event */ public function postSetData(FormEvent $event) { $form = $event->getForm(); $parameter = array('label' => 'open_orchestra_base.form.submit'); $form->add('submit', 'submit', $parameter); } /** * @return array The event names to listen to */ public static function getSubscribedEvents() { return array( FormEvents::POST_SET_DATA => 'postSetData', ); } }
Clear caches on DynamicRateDefinition deletion for completeness and to help with tests
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hour = models.FloatField(default=None, blank=True, null=True) per_minute = models.FloatField(default=None, blank=True, null=True) per_second = models.FloatField(default=None, blank=True, null=True) def save(self, *args, **kwargs): self._clear_caches() super().save(*args, **kwargs) def delete(self, *args, **kwargs): self._clear_caches() super().delete(*args, **kwargs) def _clear_caches(self): from corehq.project_limits.rate_limiter import get_dynamic_rate_definition get_dynamic_rate_definition.clear(self.key, {})
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hour = models.FloatField(default=None, blank=True, null=True) per_minute = models.FloatField(default=None, blank=True, null=True) per_second = models.FloatField(default=None, blank=True, null=True) def save(self, *args, **kwargs): from corehq.project_limits.rate_limiter import get_dynamic_rate_definition get_dynamic_rate_definition.clear(self.key, {}) super().save(*args, **kwargs)
Make Python example output identical to C++ and Java by removing redundant spaces.
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #:", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #:", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #:", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #: ", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #: ", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #: ", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
Add chunked transfer encoding terminator
<?php if (function_exists('apache_setenv')) { apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 0); while(ob_get_level()){ob_end_flush();} header("Transfer-Encoding: chunked"); header("Content-Type: text/plain"); flush(); function getThingsToSay() { $results = []; for ($i = 0; $i < 40; $i++) { $output = []; exec('/usr/games/fortune', $output); $results[] = implode("\n", $output); } return $results; } function send_chunk($chunk) { printf("%x\r\n", strlen($chunk)); print $chunk; print "\r\n"; flush(); } $things = getThingsToSay(); send_chunk("Done loading fortunes.\n"); sleep(2); foreach ($things as $fortune) { send_chunk($fortune . "\n\n"); usleep(3e5); } send_chunk(''); print "\r\n";
<?php if (function_exists('apache_setenv')) { apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 0); while(ob_get_level()){ob_end_flush();} header("Transfer-Encoding: chunked"); header("Content-Type: text/plain"); flush(); function getThingsToSay() { $results = []; for ($i = 0; $i < 80; $i++) { $output = []; exec('/usr/games/fortune', $output); $results[] = implode("\n", $output); } return $results; } function send_chunk($chunk) { printf("%x\r\n", strlen($chunk)); print $chunk; print "\r\n"; flush(); } $things = getThingsToSay(); send_chunk("Done loading fortunes.\n"); sleep(2); foreach ($things as $fortune) { send_chunk($fortune . "\n\n"); usleep(3e5); }
Remove .md extension from CONTRIBUTING file
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2012 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Add custom template delimiters. grunt.template.addDelimiters('build-cfpb', '{%', '%}'); grunt.registerTask('build-cfpb', 'Generate CFPB README', function() { var path = require('path'), fs = require('fs'), asset = path.join.bind(null, __dirname, 'assets'), meta = grunt.file.readJSON('package.json'); meta.changelog = grunt.file.readYAML('CHANGELOG'); meta.license = grunt.file.read('LICENSE'); grunt.file.expand('docs/*.md').forEach( function(filepath) { var filename = path.basename( filepath, '.md' ); meta.docs[filename] = grunt.file.read( filepath ); }); // Generate readme. var tmpl = grunt.file.read( asset('README.tmpl.md') ), appendix = grunt.template.process( tmpl, {data: meta, delimiters: 'build-cfpb'} ), readme = grunt.file.exists('README.md') ? grunt.file.read('README.md') : ''; grunt.file.write( 'README.md', readme + appendix ); grunt.log.ok('Created README.md'); // Fail task if any errors were logged. if ( this.errorCount > 0 ) { return false; } }); };
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2012 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Add custom template delimiters. grunt.template.addDelimiters('build-cfpb', '{%', '%}'); grunt.registerTask('build-cfpb', 'Generate CFPB README', function() { var path = require('path'), fs = require('fs'), asset = path.join.bind(null, __dirname, 'assets'), meta = grunt.file.readJSON('package.json'); meta.changelog = grunt.file.readYAML('CHANGELOG.md'); meta.license = grunt.file.read('LICENSE'); grunt.file.expand('docs/*.md').forEach( function(filepath) { var filename = path.basename( filepath, '.md' ); meta.docs[filename] = grunt.file.read( filepath ); }); // Generate readme. var tmpl = grunt.file.read( asset('README.tmpl.md') ), appendix = grunt.template.process( tmpl, {data: meta, delimiters: 'build-cfpb'} ), readme = grunt.file.exists('README.md') ? grunt.file.read('README.md') : ''; grunt.file.write( 'README.md', readme + appendix ); grunt.log.ok('Created README.md'); // Fail task if any errors were logged. if ( this.errorCount > 0 ) { return false; } }); };
Connect the socket.io instance to the API connection only
/** Copyright 2015 Covistra Technologies Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var SocketIO = require('socket.io'), _ = require('lodash'); "use strict"; exports.register = function (server, options, next) { var log = server.plugins['covistra-system'].systemLog; var config = server.plugins['hapi-config'].CurrentConfiguration; log.info("Registering the socket plugin", server.select('api').listener); var io = SocketIO(server.select('api').listener); log.debug("Socket.IO instance has been successfully created"); var socketManager = require('./lib/socket-manager')(server, io, log.child({service: 'socket-manager'}), config); io.on('connection', function(socket) { server.log(['plugin', 'socket', 'debug'], "Client is connected on our socket"); socketManager.clientConnected(socket); }); server.expose('socketManager', socketManager); next(); }; exports.register.attributes = { pkg: require('./package.json') };
/** Copyright 2015 Covistra Technologies Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var SocketIO = require('socket.io'), _ = require('lodash'); "use strict"; exports.register = function (server, options, next) { server.log(['plugin', 'info'], "Registering the Socket plugin"); var io = SocketIO.listen(server.listener); var log = server.plugins['covistra-system'].systemLog; var config = server.plugins['hapi-config'].CurrentConfiguration; var socketManager = require('./lib/socket-manager')(server, io, log.child({service: 'socket-manager'}), config); io.on('connection', function(socket) { server.log(['plugin', 'socket', 'debug'], "Client is connected on our socket"); socketManager.clientConnected(socket); }); server.expose('socketManager', socketManager); next(); }; exports.register.attributes = { pkg: require('./package.json') };
Make GENERIC_REASON consistent with web messages.
package uk.ac.ic.wlgitbridge.snapshot.base; import com.google.gson.JsonElement; import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException; import java.util.Arrays; import java.util.List; public class MissingRepositoryException extends SnapshotAPIException { public static final String GENERIC_REASON = "This Overleaf project currently has no git access.\n" + "\n" + "If this problem persists, please contact us."; public static final String EXPORTED_TO_V2 = "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" + "\n" + "See https://www.overleaf.com/help/342 for more information."; private String message = ""; public MissingRepositoryException() { } public MissingRepositoryException(String message) { this.message = message; } @Override public void fromJSON(JsonElement json) {} @Override public String getMessage() { return message; } @Override public List<String> getDescriptionLines() { return Arrays.asList(getMessage()); } }
package uk.ac.ic.wlgitbridge.snapshot.base; import com.google.gson.JsonElement; import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException; import java.util.Arrays; import java.util.List; public class MissingRepositoryException extends SnapshotAPIException { public static final String GENERIC_REASON = "This Overleaf project currently has no git access.\n" + "\n" + "If you think this is an error, contact support at support@overleaf.com."; public static final String EXPORTED_TO_V2 = "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" + "\n" + "See https://www.overleaf.com/help/342 for more information."; private String message = ""; public MissingRepositoryException() { } public MissingRepositoryException(String message) { this.message = message; } @Override public void fromJSON(JsonElement json) {} @Override public String getMessage() { return message; } @Override public List<String> getDescriptionLines() { return Arrays.asList(getMessage()); } }
Set base path to work in /app
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import coordinateCommonsApp from './reducers'; import ActivePlaces from './containers/ActivePlaces'; import './index.css'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import NavHeader from './components/NavHeader'; import MyPage from './components/MyPage'; let store = createStore(coordinateCommonsApp); render( <Provider store={store}> <Router basename='/app'> <NavHeader /> <Route path="/" exact component={ActivePlaces} /> <Route path="/places/:placeType" component={ActivePlaces} /> <Route path="/mypage" component={MyPage} /> </Router> </Provider>, document.getElementById('root') );
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import coordinateCommonsApp from './reducers'; import ActivePlaces from './containers/ActivePlaces'; import './index.css'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import NavHeader from './components/NavHeader'; import MyPage from './components/MyPage'; let store = createStore(coordinateCommonsApp); render( <Provider store={store}> <Router> <NavHeader /> <Route path="/" exact component={ActivePlaces} /> <Route path="/places/:placeType" component={ActivePlaces} /> <Route path="/mypage" component={MyPage} /> </Router> </Provider>, document.getElementById('root') );
Convert entries to PipelineState objects + typo in wrapper class name
import arrow import logging import argparse import emission.core.wrapper.pipelinestate as ecwp import emission.core.get_database as edb # Run in containers using: # sudo docker exec $CONTAINER bash -c 'cd e-mission-server; source setup/activate.sh; ./e-mission-py.bash bin/debug/find_invalid_pipeline_state.py' def print_all_invalid_state(): all_invalid_states = [ecwp.PipelineState(p) for p in edb.get_pipeline_state_db().find({"curr_run_ts": {"$ne": None}})] for invalid_state in all_invalid_states: print(f"{invalid_state.user_id}: {ecwp.PipelineStages(invalid_state.pipeline_stage)} set to {arrow.get(invalid_state.curr_run_ts)}") if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(prog="find_invalid_pipeline_state") args = parser.parse_args() print_all_invalid_state()
import arrow import logging import argparse import emission.core.wrapper.pipelinestate as ecwp import emission.core.get_database as edb # Run in containers using: # sudo docker exec $CONTAINER bash -c 'cd e-mission-server; source setup/activate.sh; ./e-mission-py.bash bin/debug/find_invalid_pipeline_state.py' def print_all_invalid_state(): all_invalid_states = edb.get_pipeline_state_db().find({"curr_run_ts": {"$ne": None}}) for invalid_state in all_invalid_states: print(f"{invalid_state.user_id}: {ecwp.PipelineStage(invalid_state.pipeline_stage)} set to {arrow.get(invalid_state.curr_run_ts)}") if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(prog="find_invalid_pipeline_state") args = parser.parse_args() print_all_invalid_state()
Update version to pick up plurals fix
from setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Reset regex lastIndex after use
module.exports = (function () { var fs = require( 'fs' ), // http://stackoverflow.com/q/1068308 / https://github.com/jxson/front-matter regex = /^(\s*\{\{\{([\s\S]+)\}\}\}\s*)/gi, attribuets, body; function parseFile ( path, callback ) { fs.readFile( path, 'utf-8', function ( err, data ) { callback( err, parseString( data ) ); }); } function parseString ( data ) { if ( !data ) { return {} }; var match = regex.exec( data ); if ( match && match.length ) { attributes = JSON.parse( '{' + match[ 2 ].replace(/^\s+|\s+$/g, '') + '}' ); body = data.replace( match[ 0 ], '' ); } else { attributes = {}; body = data; } regex.lastIndex = 0; return { attributes: attributes, body: body }; } return { parseFile : parseFile, parse : parseString }; })();
module.exports = (function () { var fs = require( 'fs' ), // http://stackoverflow.com/q/1068308 / https://github.com/jxson/front-matter regex = /^(\s*\{\{\{([\s\S]+)\}\}\}\s*)/gi, attributes, body; function parseFile ( path, callback ) { fs.readFile( path, 'utf-8', function ( err, data ) { callback( err, parseString( data ) ); }); } function parseString ( data ) { if ( !data ) { return {} }; var match = regex.exec( data ); if ( match && match.length ) { attributes = JSON.parse( '{' + match[ 2 ].replace(/^\s+|\s+$/g, '') + '}' ); body = data.replace( match[ 0 ], '' ); } else { attributes = {}; body = data; } return { attributes: attributes, body: body }; } return { parseFile : parseFile, parse : parseString }; })();
Send timezone-aware datetime for task expiry Needed because this task would consistantly fail if django is set to a later-than-UTC timezone, due to celery thinking the task expired the instant it's sent.
from datetime import timedelta from django.conf import settings from django.utils import timezone from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3) try: result = add.apply_async( args=[4, 4], expires=timezone.now() + timedelta(seconds=timeout) ) result.get(timeout=timeout) if result.result != 8: self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result")) except IOError as e: self.add_error(ServiceUnavailable("IOError"), e) except BaseException as e: self.add_error(ServiceUnavailable("Unknown error"), e)
from datetime import datetime, timedelta from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3) try: result = add.apply_async( args=[4, 4], expires=datetime.now() + timedelta(seconds=timeout) ) result.get(timeout=timeout) if result.result != 8: self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result")) except IOError as e: self.add_error(ServiceUnavailable("IOError"), e) except BaseException as e: self.add_error(ServiceUnavailable("Unknown error"), e)
Increase point size in example
""" Create Triangulated Surface ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a surface from a set of points through a Delaunay triangulation. """ # sphinx_gallery_thumbnail_number = 2 import vtki import numpy as np ################################################################################ # First, create some points for the surface. # Define a simple Gaussian surface xx, yy = np.meshgrid(np.linspace(-200,200,20), np.linspace(-200,200,20)) A, b = 100, 100 zz = A*np.exp(-0.5*((xx/b)**2. + (yy/b)**2.)) # Get the points as a 2D NumPy array (N by 3) points = np.c_[xx.reshape(-1), yy.reshape(-1), zz.reshape(-1)] print(points[0:5, :]) ################################################################################ # Now use those points to create a point cloud ``vtki`` data object. This will # be encompassed in a :class:`vtki.PolyData` object. # simply pass the numpy points to the PolyData constructor cloud = vtki.PolyData(points) vtki.set_plot_theme('doc') cloud.plot(point_size=15, use_panel=False) ################################################################################ # Now that we have a ``vtki`` data structure of the points, we can perform a # triangulation to turn those boring discrete points into a connected surface. surf = cloud.delaunay_2d() surf.plot(show_edges=True)
""" Create Triangulated Surface ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a surface from a set of points through a Delaunay triangulation. """ # sphinx_gallery_thumbnail_number = 2 import vtki import numpy as np ################################################################################ # First, create some points for the surface. # Define a simple Gaussian surface xx, yy = np.meshgrid(np.linspace(-200,200,20), np.linspace(-200,200,20)) A, b = 100, 100 zz = A*np.exp(-0.5*((xx/b)**2. + (yy/b)**2.)) # Get the points as a 2D NumPy array (N by 3) points = np.c_[xx.reshape(-1), yy.reshape(-1), zz.reshape(-1)] print(points[0:5, :]) ################################################################################ # Now use those points to create a point cloud ``vtki`` data object. This will # be encompassed in a :class:`vtki.PolyData` object. # simply pass the numpy points to the PolyData constructor cloud = vtki.PolyData(points) cloud.plot() ################################################################################ # Now that we have a ``vtki`` data structure of the points, we can perform a # triangulation to turn those boring discrete points into a connected surface. surf = cloud.delaunay_2d() surf.plot(show_edges=True)