text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add plugin name and help intructions to warning message
/* MIT License http://www.opensource.org/licenses/mit-license.php Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ var DefinePlugin = require("./DefinePlugin"); function EnvironmentPlugin(keys) { this.defaultValues = {}; if (Array.isArray(keys)) { this.keys = keys; } else if (keys === Object(keys)) { this.keys = Object.keys(keys); this.defaultValues = keys; } else { this.keys = Array.prototype.slice.call(arguments); } } EnvironmentPlugin.prototype.apply = function(compiler) { var definitions = this.keys.reduce(function(defs, key) { var value = process.env[key] || this.defaultValues[key]; if(value === undefined) { compiler.plugin("this-compilation", function(compilation) { var error = new Error( 'EnvironmentPlugin - ' + key + ' environment variable is undefined. \033[0m\n\n' + 'You can pass an object with default values to suppress this warning. \n' + 'See http://webpack.github.io/docs/list-of-plugins.html#environmentplugin for example.' ); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } defs["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return defs; }.bind(this), {}); compiler.apply(new DefinePlugin(definitions)); }; module.exports = EnvironmentPlugin;
/* MIT License http://www.opensource.org/licenses/mit-license.php Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ var DefinePlugin = require("./DefinePlugin"); function EnvironmentPlugin(keys) { this.defaultValues = {}; if (Array.isArray(keys)) { this.keys = keys; } else if (keys === Object(keys)) { this.keys = Object.keys(keys); this.defaultValues = keys; } else { this.keys = Array.prototype.slice.call(arguments); } } EnvironmentPlugin.prototype.apply = function(compiler) { var definitions = this.keys.reduce(function(defs, key) { var value = process.env[key] || this.defaultValues[key]; if(value === undefined) { compiler.plugin("this-compilation", function(compilation) { var error = new Error(key + " environment variable is undefined."); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } defs["process.env." + key] = value ? JSON.stringify(value) : "undefined"; return defs; }.bind(this), {}); compiler.apply(new DefinePlugin(definitions)); }; module.exports = EnvironmentPlugin;
Fix bug in sequelize pluralization
const db = require('../db.js'); const languageToId = require('../seed/languages.js').languageToId; const levelToId = require('../seed/levels.js').levelToId; const LanguagesLevels = require('../models/languageLevelModel.js'); const Users = require('../models/userModel.js'); module.exports = (type, userId, languageLevels) => ( // languageLevels is an array of tuples in the form of [language, level] db.query(` DELETE FROM users_languages_levels WHERE user_id = '${userId}' `) // delete existing associations between user and any languageLevels .spread(() => Users.findById(userId)) .then(user => { const languageLevelQueries = languageLevels.map(languageLevel => ( LanguagesLevels.findOrCreate({ where: { language_id: languageToId[languageLevel[0]], level_id: levelToId[languageLevel[1]], }, }) .spread(result => result) // each result is an instance of the LanguagesLevels sequelize model )); return Promise.all(languageLevelQueries) .then(lls => { const addQueries = lls.map(ll => ( user.addLanguages_level(ll, { offer_or_learn: type }) )); return Promise.all(addQueries); }); }) );
const db = require('../db.js'); const languageToId = require('../seed/languages.js').languageToId; const levelToId = require('../seed/levels.js').levelToId; const LanguagesLevels = require('../models/languageLevelModel.js'); const Users = require('../models/userModel.js'); module.exports = (type, userId, languageLevels) => ( // languageLevels is an array of tuples in the form of [language, level] db.query(` DELETE FROM users_languages_levels WHERE user_id = '${userId}' `) // delete existing associations between user and any languageLevels .spread(() => Users.findById(userId)) .then(user => { const languageLevelQueries = languageLevels.map(languageLevel => ( LanguagesLevels.findOrCreate({ where: { language_id: languageToId[languageLevel[0]], level_id: levelToId[languageLevel[1]], }, }) .spread(result => result) // each result is an instance of the LanguagesLevels sequelize model )); return Promise.all(languageLevelQueries) .then(lls => { const addQueries = lls.map(ll => ( user.addLanguagesLevels(ll, { offer_or_learn: type }) )); return Promise.all(addQueries); }); }) );
Use the shorter decorator() method .. because they are same for `HttpClient`.
package armeria; import brave.Tracing; import com.linecorp.armeria.client.HttpClient; import com.linecorp.armeria.client.HttpClientBuilder; import com.linecorp.armeria.client.tracing.HttpTracingClient; import com.linecorp.armeria.server.Server; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.logging.LoggingService; import com.linecorp.armeria.server.tracing.HttpTracingService; public class Frontend { public static void main(String[] args) { Tracing tracing = TracingFactory.create("frontend"); HttpClient backendClient = new HttpClientBuilder("http://localhost:9000/") .decorator(HttpTracingClient.newDecorator(tracing, "backend")) .build(); Server server = new ServerBuilder() .http(8081) .service("/", (ctx, res) -> backendClient.get("/api")) .decorator(HttpTracingService.newDecorator(tracing)) .decorator(LoggingService.newDecorator()) .build(); server.start().join(); } }
package armeria; import brave.Tracing; import com.linecorp.armeria.client.HttpClient; import com.linecorp.armeria.client.HttpClientBuilder; import com.linecorp.armeria.client.tracing.HttpTracingClient; import com.linecorp.armeria.common.HttpRequest; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.server.Server; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.logging.LoggingService; import com.linecorp.armeria.server.tracing.HttpTracingService; public class Frontend { public static void main(String[] args) { Tracing tracing = TracingFactory.create("frontend"); HttpClient backendClient = new HttpClientBuilder("http://localhost:9000/") .decorator( HttpRequest.class, HttpResponse.class, HttpTracingClient.newDecorator(tracing, "backend")) .build(); Server server = new ServerBuilder() .http(8081) .service("/", (ctx, res) -> backendClient.get("/api")) .decorator(HttpTracingService.newDecorator(tracing)) .decorator(LoggingService.newDecorator()) .build(); server.start().join(); } }
Use one of the defined ones
package httpie import ( "testing" "strings" "bufio" "bytes" ) var delimData = []string{ "Hello", "World", "This", "Is", "A", "Test", }; func TestDelim(t *testing.T) { data := []byte(strings.Join(delimData, "\n") + "\n") delim := NewLine reader := bufio.NewReader(bytes.NewBuffer(data)) out := []string{} for _, seg := range delimData { b, _ := delim.Consume(reader) if string(b) == seg { out = append(out, string(b)) } } if len(out) != len(delimData) { t.Errorf("Delimeter consumer output doesn't match: actual=%s expected=%s", out, delimData) } }
package httpie import ( "testing" "strings" "bufio" "bytes" ) var delimData = []string{ "Hello", "World", "This", "Is", "A", "Test", }; func TestDelim(t *testing.T) { data := []byte(strings.Join(delimData, "\n") + "\n") delim := Delimeter{'\n'} reader := bufio.NewReader(bytes.NewBuffer(data)) out := []string{} for _, seg := range delimData { b, _ := delim.Consume(reader) if string(b) == seg { out = append(out, string(b)) } } if len(out) != len(delimData) { t.Errorf("Delimeter consumer output doesn't match: actual=%s expected=%s", out, delimData) } }
Add default value for changeHandlerName to config
// function to create the singleton options object that can be shared // throughout an application function createurlQueryConfig() { // default options return { // add in generated URL change handlers based on a urlPropsQueryConfig if provided addUrlChangeHandlers: true, // add in `props.params` from react-router to the url object addRouterParams: true, // function to specify change handler name (onChange<PropName>) changeHandlerName: propName => `onChange${propName[0].toUpperCase()}${propName.substring(1)}`, // use this history if no history is specified history: { push() { // eslint-disable-next-line console.error('No history provided to react-url-query. Please provide one via configureUrlQuery.'); }, replace() { // eslint-disable-next-line console.error('No history provided to react-url-query. Please provide one via configureUrlQuery.'); }, }, // reads in location from react-router-redux if available and passes it // to the reducer in the urlQueryMiddleware readLocationFromStore(state) { if (state && state.routing) { return state.routing.locationBeforeTransitions; } return undefined; }, }; } export default createurlQueryConfig();
// function to create the singleton options object that can be shared // throughout an application function createurlQueryConfig() { // default options return { // add in generated URL change handlers based on a urlPropsQueryConfig if provided addUrlChangeHandlers: true, // add in `props.params` from react-router to the url object addRouterParams: true, // use this history if no history is specified history: { push() { // eslint-disable-next-line console.error('No history provided to react-url-query. Please provide one via configureUrlQuery.'); }, replace() { // eslint-disable-next-line console.error('No history provided to react-url-query. Please provide one via configureUrlQuery.'); }, }, // reads in location from react-router-redux if available and passes it // to the reducer in the urlQueryMiddleware readLocationFromStore(state) { if (state && state.routing) { return state.routing.locationBeforeTransitions; } return undefined; }, }; } export default createurlQueryConfig();
Use a neighbour for the lookup
/* * Copyright 2006-2022 the original author or 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 org.objenesis.instantiator.exotic.util; import org.junit.jupiter.api.Test; import org.objenesis.test.EmptyClass; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Henri Tremblay */ public class ClassDefinitionUtilsTest { @Test public void testDefineClass() throws Exception { String className = "org.objenesis.test.EmptyClassBis"; byte[] b = ClassDefinitionUtils.readClass(className); Class<?> c = ClassDefinitionUtils.defineClass(className, b, EmptyClass.class, getClass().getClassLoader()); assertEquals(c.getName(), className); } }
/* * Copyright 2006-2022 the original author or 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 org.objenesis.instantiator.exotic.util; import org.junit.jupiter.api.Test; import org.objenesis.Objenesis; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Henri Tremblay */ public class ClassDefinitionUtilsTest { @Test public void testDefineClass() throws Exception { String className = "org.objenesis.test.EmptyClassBis"; byte[] b = ClassDefinitionUtils.readClass(className); Class<?> c = ClassDefinitionUtils.defineClass(className, b, Objenesis.class, getClass().getClassLoader()); assertEquals(c.getName(), className); } }
Fix search page loading spinner
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import searchFiltersSelector from 'selectors/searchFiltersSelector'; import searchResultsSelector from 'selectors/searchResultsSelector'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const unitsSelector = (state) => state.data.units; const searchPageSelector = createSelector( requestIsActiveSelectorFactory(ActionTypes.API.SEARCH_RESULTS_GET_REQUEST), searchFiltersSelector, searchResultsSelector, unitsSelector, ( isFetchingSearchResults, searchFilters, searchResults, units ) => { return { filters: searchFilters, isFetchingSearchResults, results: searchResults, units, }; } ); export default searchPageSelector;
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import searchFiltersSelector from 'selectors/searchFiltersSelector'; import searchResultsSelector from 'selectors/searchResultsSelector'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const unitsSelector = (state) => state.data.units; const searchPageSelector = createSelector( requestIsActiveSelectorFactory(ActionTypes.API.RESOURCES_GET_REQUEST), searchFiltersSelector, searchResultsSelector, unitsSelector, ( isFetchingSearchResults, searchFilters, searchResults, units ) => { return { filters: searchFilters, isFetchingSearchResults, results: searchResults, units, }; } ); export default searchPageSelector;
Choose a version of ftfy to use depending on the version of Python
#!/usr/bin/env python VERSION = "0.5.4" from setuptools import setup, find_packages import sys classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' # Choose a version of ftfy to use depending on the version of Python if sys.version_info[0] < 3: FTFY_DEP = 'ftfy >= 4.3, < 5' else: FTFY_DEP = 'ftfy >= 5' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', FTFY_DEP ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
#!/usr/bin/env python VERSION = "0.5.3" from setuptools import setup, find_packages classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Topic :: Text Processing :: Linguistic' ] GITHUB_URL = 'http://github.com/LuminosoInsight/luminoso-api-client-python' setup( name="luminoso-api", version=VERSION, maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', url=GITHUB_URL, download_url='%s/tarball/v%s' % (GITHUB_URL, VERSION), platforms=["any"], description="Python client library for communicating with the Luminoso REST API", classifiers=classifiers, packages=find_packages(exclude=('tests',)), install_requires=[ 'requests >= 1.2.1, < 3.0', 'ftfy >= 3.3, < 5', ], entry_points={ 'console_scripts': [ 'lumi-upload = luminoso_api.upload:main', 'lumi-json-stream = luminoso_api.json_stream:main', ]}, )
Add ok button to version popup
// INTERACTIONS_OBJECT = {}; INTERACTIONS_OBJECT.help_interactions = ["Help Contents", "Version Info"] IONUX.Views.HelpMenu = Backbone.View.extend({ el: "#topbar #help", events: { "click #helpmenu-version": "version_clicked" }, modal_template: '<div id="version-overlay" class="modal-ooi modal hide"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h1>Version Information</h1></div><div class="modal-body"><dl><% _.each(version, function(v, k, l) { %><dt><%= k %></dt><dd><%= v %></dd><% }) %></dl></div><div class="modal-footer"><button class="btn-blue" style="float:right;"data-dismiss="modal">OK</button></div>', version_clicked: function() { var modal_html = _.template(this.modal_template)(this.model.attributes); $(modal_html).modal() .on('hidden', function() { $('#version-overlay').remove(); }); } });
// INTERACTIONS_OBJECT = {}; INTERACTIONS_OBJECT.help_interactions = ["Help Contents", "Version Info"] IONUX.Views.HelpMenu = Backbone.View.extend({ el: "#topbar #help", events: { "click #helpmenu-version": "version_clicked" }, modal_template: '<div id="version-overlay" class="modal-ooi modal hide"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h1>Version Information</h1></div><div class="modal-body"><dl><% _.each(version, function(v, k, l) { %><dt><%= k %></dt><dd><%= v %></dd><% }) %></dl></div></div>', version_clicked: function() { var modal_html = _.template(this.modal_template)(this.model.attributes); $(modal_html).modal() .on('hidden', function() { $('#version-overlay').remove(); }); } });
Add locally referenced subtype to element referenced opcodes
class Reference(object): def __init__(self, type): super().__init__() self._type = type @property def type(self): return self._type class ElementReference(Reference): def __init__(self, thing, element, local=None): super(ElementReference, self).__init__(element.type) self.thing, self.element, self.local = thing, element, local @property def thing_index(self): return self.thing.index @property def element_index(self): return self.element.index @property def local_index(self): return self.local.index @property def convention(self): return self.element.convention @property def static(self): return self.element.static class LocalReference(Reference): def __init__(self, local): super(LocalReference, self).__init__(local.type) self.local = local @property def local_index(self): return self.local.index class StaticReference(Reference): def __init__(self, value): super(StaticReference, self).__init__(value.type) self.value = value
class Reference(object): def __init__(self, type): super().__init__() self._type = type @property def type(self): return self._type class ElementReference(Reference): def __init__(self, thing, element): super(ElementReference, self).__init__(element.type) self.thing, self.element = thing, element @property def thing_index(self): return self.thing.index @property def element_index(self): return self.element.index @property def convention(self): return self.element.convention @property def static(self): return self.element.static class LocalReference(Reference): def __init__(self, local): super(LocalReference, self).__init__(local.type) self.local = local @property def local_index(self): return self.local.index class StaticReference(Reference): def __init__(self, value): super(StaticReference, self).__init__(value.type) self.value = value
Deployment: Use connection string for production's sequelize connection
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import config from '../../config/config'; const basename = path.basename(module.filename); const db = {}; let sequelize; if (process.env.NODE_ENV === 'production') { sequelize = new Sequelize(process.env.DATABASE_URL); } else { sequelize = new Sequelize(config.db.database, config.db.user, config.db.password, config.db.options); } fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js') ) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; export default db;
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import config from '../../config/config'; const basename = path.basename(module.filename); const db = {}; const sequelize = new Sequelize(config.db.database, config.db.user, config.db.password, config.db.options); fs .readdirSync(__dirname) .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js') ) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; export default db;
Fix an error in production.
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) with open('config.json') as f: config = json.loads(f.read()) def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_code == 0) def http_handler(address, **kwargs): try: r = requests.get(address) except requests.exceptions.RequestException: return json.dumps(False) return json.dumps(r.status_code == 200) get_handler = { 'http': http_handler, 'shell': shell_handler, } @app.route('/') def index(): data = { 'tasks': config['tasks'], 'title': config['title'], } return render_template('index.html', **data) @app.route('/<task_id>') def status(task_id): try: task = filter(lambda t: t['id'] == task_id, config['tasks'])[0] except IndexError: return 'This task does not exist', 404 return get_handler[task['type']](**task) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) config = {} def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_code == 0) def http_handler(address, **kwargs): try: r = requests.get(address) except requests.exceptions.RequestException: return json.dumps(False) return json.dumps(r.status_code == 200) get_handler = { 'http': http_handler, 'shell': shell_handler, } @app.route('/') def index(): data = { 'tasks': config['tasks'], 'title': config['title'], } return render_template('index.html', **data) @app.route('/<task_id>') def status(task_id): try: task = filter(lambda t: t['id'] == task_id, config['tasks'])[0] except IndexError: return 'This task does not exist', 404 return get_handler[task['type']](**task) if __name__ == '__main__': with open('config.json') as f: config = json.loads(f.read()) app.run(debug=True, host='0.0.0.0')
Add smelting recipes support, for voxel-furnace
var craftingrecipes = require('craftingrecipes'); var ItemPile = require('itempile'); module.exports = function(game, opts) { return new RecipesPlugin(game, opts); }; function RecipesPlugin(game, opts) { this.craftList = new craftingrecipes.RecipeList(); this.smeltMap = {}; this.thesaurus = new craftingrecipes.CraftingThesaurus(); } RecipesPlugin.prototype.register = function(recipe) { return this.craftList.register(recipe); }; RecipesPlugin.prototype.registerAmorphous = function(ingredients, result) { return this.register(new craftingrecipes.AmorphousRecipe(ingredients, ItemPile.fromArrayIfArray(result))); }; RecipesPlugin.prototype.registerPositional = function(ingredients, result) { return this.register(new craftingrecipes.PositionalRecipe(ingredients, ItemPile.fromArrayIfArray(result))); }; RecipesPlugin.prototype.find = function(inventory) { return this.craftList.find(inventory); }; RecipesPlugin.prototype.craft = function(inventory) { return this.craftList.craft(inventory); }; RecipesPlugin.prototype.registerSmelting = function(input, output) { if (input in this.craftList) console.log('WARNING: voxel-recipes registerSmelting overwriting recipes '+input+' -> '+output); // TODO: do we care? this.craftList[input] = ItemPile.fromArrayIfArray(output); }; RecipesPlugin.prototype.smelt = function(input) { if (!input || !input.item) return undefined; var output = this.craftList[input.item]; // TODO: smelting inputs of different stack sizes? (vs always 1) return output ? output.clone() : undefined; };
var craftingrecipes = require('craftingrecipes'); var ItemPile = require('itempile'); module.exports = function(game, opts) { return new RecipesPlugin(game, opts); }; function RecipesPlugin(game, opts) { this.craftList = new craftingrecipes.RecipeList(); this.thesaurus = new craftingrecipes.CraftingThesaurus(); } RecipesPlugin.prototype.register = function(recipe) { return this.craftList.register(recipe); }; RecipesPlugin.prototype.registerAmorphous = function(ingredients, result) { return this.register(new craftingrecipes.AmorphousRecipe(ingredients, ItemPile.fromArrayIfArray(result))); }; RecipesPlugin.prototype.registerPositional = function(ingredients, result) { return this.register(new craftingrecipes.PositionalRecipe(ingredients, ItemPile.fromArrayIfArray(result))); }; RecipesPlugin.prototype.find = function(inventory) { return this.craftList.find(inventory); }; RecipesPlugin.prototype.craft = function(inventory) { return this.craftList.craft(inventory); }; RecipesPlugin.prototype.registerSmelting = function(input, output) { }; RecipesPlugin.prototype.smelted = function(input) { };
Use pointers to be more efficient
package git import ( "errors" "regexp" ) type GitRemote struct { Name string URL string } func Remotes() ([]*GitRemote, error) { r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)") output, err := execGitCmd("remote", "-v") if err != nil { return nil, errors.New("Can't load git remote") } remotes := make([]*GitRemote, 0) for _, o := range output { if r.MatchString(o) { match := r.FindStringSubmatch(o) remotes = append(remotes, &GitRemote{Name: match[1], URL: match[2]}) } } if len(remotes) == 0 { return nil, errors.New("Can't find git remote (push)") } return remotes, nil } func OriginRemote() (*GitRemote, error) { remotes, err := Remotes() if err != nil { return nil, err } for _, r := range remotes { if r.Name == "origin" { return r, nil } } return nil, errors.New("Can't find git remote orign (push)") }
package git import ( "errors" "regexp" ) type GitRemote struct { Name string URL string } func Remotes() ([]GitRemote, error) { r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)") output, err := execGitCmd("remote", "-v") if err != nil { return nil, errors.New("Can't load git remote") } remotes := make([]GitRemote, 0) for _, o := range output { if r.MatchString(o) { match := r.FindStringSubmatch(o) remotes = append(remotes, GitRemote{Name: match[1], URL: match[2]}) } } if len(remotes) == 0 { return nil, errors.New("Can't find git remote (push)") } return remotes, nil } func OriginRemote() (*GitRemote, error) { remotes, err := Remotes() if err != nil { return nil, err } for _, r := range remotes { if r.Name == "origin" { return &r, nil } } return nil, errors.New("Can't find git remote orign (push)") }
Add libsqlncli library to test with
var odbc = require("../"); //odbc.library = '/usr/lib/odbc/libsqlite3odbc-0.91'; //odbc.library = '/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc'; //odbc.library = '/opt/sqlncli-11.0.1790.0/lib64/libsqlncli-11.0'; exports.connectionString = "DRIVER={SQLite3};DATABASE=data/sqlite-test.db"; //exports.connectionString = "DRIVER={MySQL};DATABASE=test;HOST=localhost;USER=test;"; //exports.connectionString = process.env.ODBC_CONNETION_STRING; exports.connectionObject = { DRIVER : "{SQLITE3}", DATABASE : "data/sqlite-test.db" }; exports.connections = [ { DRIVER : "{SQLITE3}", DATABASE : "data/sqlite-test.db" } ]; exports.databaseName = "MAIN"; exports.tableName = "NODE_ODBC_TEST_TABLE"; exports.dropTables = function (db, cb) { db.query("drop table " + exports.tableName, cb); }; exports.createTables = function (db, cb) { db.query("create table " + exports.tableName + " (COLINT INTEGER, COLDATETIME DATETIME, COLTEXT TEXT)", cb); };
var odbc = require("../"); //odbc.library = '/usr/lib/odbc/libsqlite3odbc-0.91'; //odbc.library = '/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc'; exports.connectionString = "DRIVER={SQLite3};DATABASE=data/sqlite-test.db"; //exports.connectionString = "DRIVER={MySQL};DATABASE=test;HOST=localhost;USER=test;"; //exports.connectionString = process.env.ODBC_CONNETION_STRING; exports.connectionObject = { DRIVER : "{SQLITE3}", DATABASE : "data/sqlite-test.db" }; exports.connections = [ { DRIVER : "{SQLITE3}", DATABASE : "data/sqlite-test.db" } ]; exports.databaseName = "MAIN"; exports.tableName = "NODE_ODBC_TEST_TABLE"; exports.dropTables = function (db, cb) { db.query("drop table " + exports.tableName, cb); }; exports.createTables = function (db, cb) { db.query("create table " + exports.tableName + " (COLINT INTEGER, COLDATETIME DATETIME, COLTEXT TEXT)", cb); };
Fix tiny typo in deprecation notice.
import Ember from 'ember-metal/core'; import ControllerMixin from 'ember-runtime/mixins/controller'; import ObjectProxy from 'ember-runtime/system/object_proxy'; export var objectControllerDeprecation = 'Ember.ObjectController is deprecated, ' + 'please use Ember.Controller and use `model.propertyName`.'; /** @module ember @submodule ember-runtime */ /** `Ember.ObjectController` is part of Ember's Controller layer. It is intended to wrap a single object, proxying unhandled attempts to `get` and `set` to the underlying model object, and to forward unhandled action attempts to its `target`. `Ember.ObjectController` derives this functionality from its superclass `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin. @class ObjectController @namespace Ember @extends Ember.ObjectProxy @uses Ember.ControllerMixin @deprecated **/ export default ObjectProxy.extend(ControllerMixin, { init: function() { Ember.deprecate(objectControllerDeprecation, this.isGenerated); } });
import Ember from 'ember-metal/core'; import ControllerMixin from 'ember-runtime/mixins/controller'; import ObjectProxy from 'ember-runtime/system/object_proxy'; export var objectControllerDeprecation = 'Ember.ObjectController is deprected, ' + 'please use Ember.Controller and use `model.propertyName`.'; /** @module ember @submodule ember-runtime */ /** `Ember.ObjectController` is part of Ember's Controller layer. It is intended to wrap a single object, proxying unhandled attempts to `get` and `set` to the underlying model object, and to forward unhandled action attempts to its `target`. `Ember.ObjectController` derives this functionality from its superclass `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin. @class ObjectController @namespace Ember @extends Ember.ObjectProxy @uses Ember.ControllerMixin @deprecated **/ export default ObjectProxy.extend(ControllerMixin, { init: function() { Ember.deprecate(objectControllerDeprecation, this.isGenerated); } });
Add performance monitoring for Best Of
import monitor from 'monitor-dog' import { dbAdapter } from '../../../models' import { reportError } from '../../../support/exceptions' import { serializePostsCollection } from '../../../serializers/v2/post'; export default class TimelinesController { app = null; constructor(app) { this.app = app; } bestOf = async (req, res) => { const timer = monitor.timer('timelines.bestof-time') try { const DEFAULT_LIMIT = 30; const currentUserId = req.user ? req.user.id : null; const offset = parseInt(req.query.offset, 10) || 0; const limit = parseInt(req.query.limit, 10) || DEFAULT_LIMIT; const foundPosts = await dbAdapter.bestPosts(req.user, offset, limit); const postsObjects = dbAdapter.initRawPosts(foundPosts, { currentUser: currentUserId }); const postsCollectionJson = await serializePostsCollection(postsObjects); res.jsonp(postsCollectionJson); monitor.increment('timelines.bestof-requests') } catch (e) { reportError(res)(e); } finally { timer.stop() } }; }
import { dbAdapter } from '../../../models' import { reportError } from '../../../support/exceptions' import { serializePostsCollection } from '../../../serializers/v2/post'; export default class TimelinesController { app = null; constructor(app) { this.app = app; } bestOf = async (req, res) => { try { const DEFAULT_LIMIT = 30; const currentUserId = req.user ? req.user.id : null; const offset = parseInt(req.query.offset, 10) || 0; const limit = parseInt(req.query.limit, 10) || DEFAULT_LIMIT; const foundPosts = await dbAdapter.bestPosts(req.user, offset, limit); const postsObjects = dbAdapter.initRawPosts(foundPosts, { currentUser: currentUserId }); const postsCollectionJson = await serializePostsCollection(postsObjects); res.jsonp(postsCollectionJson); } catch (e) { reportError(res)(e); } }; }
Exclude node_modules from bable build
var path = require('path') var gulp = require('gulp') var sourcemaps = require('gulp-sourcemaps') var babel = require('gulp-babel') var paths = { es6: ['**/*.js', '!gulpfile.js', '!build/**/*.*', '!node_modules/**/*.*'], es5: 'build', // must be absolute or relative to source map sourceRoot: path.join(__dirname) } gulp.task('babel', function () { return gulp.src(paths.es6) .pipe(sourcemaps.init()) .pipe(babel({ optional: [ 'es7.asyncFunctions', 'es7.exportExtensions' ] })) .pipe(sourcemaps.write('.', {sourceRoot: paths.sourceRoot})) .pipe(gulp.dest(paths.es5)) }) gulp.task('watch', function () { gulp.watch(paths.es6, ['babel']) }) gulp.task('default', ['watch'])
var path = require('path') var gulp = require('gulp') var sourcemaps = require('gulp-sourcemaps') var babel = require('gulp-babel') var paths = { es6: ['**/*.js', '!gulpfile.js', '!build/**/*.*'], es5: 'build', // must be absolute or relative to source map sourceRoot: path.join(__dirname) } gulp.task('babel', function () { return gulp.src(paths.es6) .pipe(sourcemaps.init()) .pipe(babel({ optional: [ 'es7.asyncFunctions', 'es7.exportExtensions' ] })) .pipe(sourcemaps.write('.', {sourceRoot: paths.sourceRoot})) .pipe(gulp.dest(paths.es5)) }) gulp.task('watch', function () { gulp.watch(paths.es6, ['babel']) }) gulp.task('default', ['watch'])
Add error check for Linux check.
package cmd import ( "io/ioutil" "log" "github.com/mitchellh/go-homedir" "github.com/mobingilabs/mocli/pkg/util" "github.com/spf13/cobra" ) var loginCmd = &cobra.Command{ Use: "login", Short: "", Long: `Placeholder for the documentation.`, Run: login, } func init() { rootCmd.AddCommand(loginCmd) loginCmd.Flags().StringP("client-id", "i", "", "client id") loginCmd.Flags().StringP("client-secret", "s", "", "client secret") loginCmd.Flags().StringP("grant-type", "g", "client_credentials", "grant type (valid values: 'client_credentials', 'password')") } func login(cmd *cobra.Command, args []string) { log.Println("login here") hd, _ := homedir.Dir() log.Println("home:", hd) cred := hd + `/.mocli/credentials` token, err := ioutil.ReadFile(cred) if err != nil { log.Println(err) err = ioutil.WriteFile(cred, []byte("hello"), 0644) if err != nil { log.Println(err) } } log.Println(string(token)) user, pass := util.GetUserPassword() log.Println(user, pass) }
package cmd import ( "io/ioutil" "log" "github.com/mitchellh/go-homedir" "github.com/mobingilabs/mocli/pkg/util" "github.com/spf13/cobra" ) var loginCmd = &cobra.Command{ Use: "login", Short: "", Long: `Placeholder for the documentation.`, Run: login, } func init() { rootCmd.AddCommand(loginCmd) loginCmd.Flags().StringP("client-id", "i", "", "client id") loginCmd.Flags().StringP("client-secret", "s", "", "client secret") loginCmd.Flags().StringP("grant-type", "g", "client_credentials", "grant type (valid values: 'client_credentials', 'password')") } func login(cmd *cobra.Command, args []string) { log.Println("login here") hd, _ := homedir.Dir() log.Println("home:", hd) cred := hd + `/.mocli/credentials` token, err := ioutil.ReadFile(cred) if err != nil { log.Println(err) ioutil.WriteFile(hd+`/.mocli/credentials`, []byte("hello"), 0644) } log.Println(string(token)) user, pass := util.GetUserPassword() log.Println(user, pass) }
Remove unused variable for challenge name
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) const fs = require('fs') const { safeLoad } = require('js-yaml') const { promisify } = require('util') const readFile = promisify(fs.readFile) const path = require('path') const loadYamlFile = async (filename) => { const contents = await readFile(filename, { encoding: 'utf8' }) return safeLoad(contents) } describe('challengeTutorialSequence', () => { let challenges before(async () => { challenges = await loadYamlFile(path.join(__dirname, '../../data/static/challenges.yml')) }) it('should have unique tutorial orders', async () => { const tutorialOrderCounts = {} for (const { tutorial } of challenges) { if (tutorial) { const order = tutorial.order if (!Object.prototype.hasOwnProperty.call(tutorialOrderCounts, order)) { tutorialOrderCounts[order] = 0 } tutorialOrderCounts[order]++ } } for (const order of Object.keys(tutorialOrderCounts)) { const count = tutorialOrderCounts[order] expect(count, `Tutorial order "${order}" is used for multiple challenges.`).to.equal(1) } }) })
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) const fs = require('fs') const { safeLoad } = require('js-yaml') const { promisify } = require('util') const readFile = promisify(fs.readFile) const path = require('path') const loadYamlFile = async (filename) => { const contents = await readFile(filename, { encoding: 'utf8' }) return safeLoad(contents) } describe('challengeTutorialSequence', () => { let challenges before(async () => { challenges = await loadYamlFile(path.join(__dirname, '../../data/static/challenges.yml')) }) it('should have unique tutorial orders', async () => { const tutorialOrderCounts = {} for (const { name, tutorial } of challenges) { if (tutorial) { const order = tutorial.order if (!Object.prototype.hasOwnProperty.call(tutorialOrderCounts, order)) { tutorialOrderCounts[order] = 0 } tutorialOrderCounts[order]++ } } for (const order of Object.keys(tutorialOrderCounts)) { const count = tutorialOrderCounts[order] expect(count, `Tutorial order "${order}" is used for multiple challenges.`).to.equal(1) } }) })
Add special to membership model
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Objectid = mongoose.Schema.Types.ObjectId; var MembershipSchema = new Schema({ name: String, space_credits_per_month: Number, stuff_credits_per_month: Number, // bandwidth_per_month: Number, description: String, cost: Number, cost_period: String, max_members: Number, cost_extra_member: Number, space_credits_per_month_extra_member: Number, stuff_credits_per_month_extra_member: Number, // bandwidth_per_month_extra_member: Number, gigs: Number, business_address: Boolean, hotdesk: Boolean, boardroom_access: Boolean, free_printing: Boolean, hotdesk_discount: Number, boardroom_discount: Number, discount_multiplier: { type: Number, default: 1 }, special: Boolean, _owner_id: Objectid, _deleted: { type: Boolean, default: false, index: true }, }); MembershipSchema.set("_perms", { admin: "crud", owner: "r", user: "r", all: "r" }); module.exports = mongoose.model('Membership', MembershipSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Objectid = mongoose.Schema.Types.ObjectId; var MembershipSchema = new Schema({ name: String, space_credits_per_month: Number, stuff_credits_per_month: Number, // bandwidth_per_month: Number, description: String, cost: Number, cost_period: String, max_members: Number, cost_extra_member: Number, space_credits_per_month_extra_member: Number, stuff_credits_per_month_extra_member: Number, // bandwidth_per_month_extra_member: Number, gigs: Number, business_address: Boolean, hotdesk: Boolean, boardroom_access: Boolean, free_printing: Boolean, hotdesk_discount: Number, boardroom_discount: Number, discount_multiplier: { type: Number, default: 1 }, _owner_id: Objectid, _deleted: { type: Boolean, default: false, index: true }, }); MembershipSchema.set("_perms", { admin: "crud", owner: "r", user: "r", all: "r" }); module.exports = mongoose.model('Membership', MembershipSchema);
Load script using current protocol
'use strict'; /** * Module dependencies. */ var integration = require('analytics.js-integration'); var when = require('when'); /** * Expose `Parsely` integration. */ var Parsely = module.exports = integration('Parsely') .global('PARSELY') .global('parsely') .option('apiKey', '') .tag('<script src="//d1z2jf7jlzjs58.cloudfront.net/p.js">'); Parsely.prototype.initialize = function() { var self = this; window.parsely = window.parsely || { apikey: this.options.apiKey }; // append the meta tag we need first before JS fires var meta = document.createElement('meta'); meta.id = 'parsely-cfg'; meta.setAttribute('data-parsely-site', this.options.apiKey); var head = document.getElementsByTagName('head')[0]; if (!head) return; head.appendChild(meta); this.load(function() { when(self.loaded, self.ready); }); }; Parsely.prototype.loaded = function() { return !!window.PARSELY; };
'use strict'; /** * Module dependencies. */ var integration = require('analytics.js-integration'); var when = require('when'); /** * Expose `Parsely` integration. */ var Parsely = module.exports = integration('Parsely') .global('PARSELY') .global('parsely') .option('apiKey', '') .tag('<script src="https://d1z2jf7jlzjs58.cloudfront.net/p.js">'); Parsely.prototype.initialize = function() { var self = this; window.parsely = window.parsely || { apikey: this.options.apiKey }; // append the meta tag we need first before JS fires var meta = document.createElement('meta'); meta.id = 'parsely-cfg'; meta.setAttribute('data-parsely-site', this.options.apiKey); var head = document.getElementsByTagName('head')[0]; if (!head) return; head.appendChild(meta); this.load(function() { when(self.loaded, self.ready); }); }; Parsely.prototype.loaded = function() { return !!window.PARSELY; };
Fix small issue with `--top-n` command switch
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
Set JWT token expiration to 1 month for ease of use
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const User = require('../models/user.js'); const jwt = require('jsonwebtoken'); const jwtConfig = require('../jwt_config'); router.post('/', (request, response) => { const username = request.body.username; User.findOne({username: username}) .then(user => { if (user) { const token = jwt.sign( {userId: user._id, username: user.username, coupleId: user.couple}, jwtConfig.key, {expiresIn: '1month'}); response.send(token); } else { response.status(404).send(); } }) .catch(e => { console.error(e); response.status(500).send(); }); }); module.exports = router;
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const User = require('../models/user.js'); const jwt = require('jsonwebtoken'); const jwtConfig = require('../jwt_config'); router.post('/', (request, response) => { const username = request.body.username; User.findOne({username: username}) .then(user => { if (user) { const token = jwt.sign( {userId: user._id, username: user.username, coupleId: user.couple}, jwtConfig.key, {expiresIn: '1day'}); response.send(token); } else { response.status(404).send(); } }) .catch(e => { console.error(e); response.status(500).send(); }); }); module.exports = router;
Disable Flask debug - incompatible with SocketIO
import os class Config(object): DEBUG = False # WTF_CSRF_ENABLED = False DATABASE_NAME = "projectp" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # refers to application_top APP_STATIC = os.path.join(BASE_DIR, 'static') # Database (sqlite) configuration SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db') DATABASE_CONNECT_OPTIONS = {} SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): SECRET_KEY = "aardappelpuree" class ProductionConfig(Config): SECRET_KEY = "appeltaart" config = { 'development': DevelopmentConfig, 'production': DevelopmentConfig }
import os class Config(object): DEBUG = True # WTF_CSRF_ENABLED = False DATABASE_NAME = "projectp" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # refers to application_top APP_STATIC = os.path.join(BASE_DIR, 'static') # Database (sqlite) configuration SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db') DATABASE_CONNECT_OPTIONS = {} SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): SECRET_KEY = "aardappelpuree" class ProductionConfig(Config): SECRET_KEY = "appeltaart" config = { 'development': DevelopmentConfig, 'production': DevelopmentConfig }
Implement simple logging to console.
/** * Copyright 2012 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.ios; import cli.System.Console; import playn.core.Log; class IOSLog implements Log { // TODO: stack traces @Override public void debug(String msg) { Console.WriteLine("DEBUG: " + msg); } @Override public void debug(String msg, Throwable e) { debug(msg + ": " + e.getMessage()); } @Override public void info(String msg) { Console.WriteLine(msg); } @Override public void info(String msg, Throwable e) { info(msg + ": " + e.getMessage()); } @Override public void warn(String msg) { Console.WriteLine("WARN: " + msg); } @Override public void warn(String msg, Throwable e) { warn(msg + ": " + e.getMessage()); } @Override public void error(String msg) { Console.WriteLine("ERROR: " + msg); } @Override public void error(String msg, Throwable e) { error(msg + ": " + e.getMessage()); } }
/** * Copyright 2012 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.ios; import playn.core.Log; class IOSLog implements Log { @Override public void error(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void error(String msg) { throw new RuntimeException("TODO"); } @Override public void info(String msg) { throw new RuntimeException("TODO"); } @Override public void info(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void debug(String msg) { throw new RuntimeException("TODO"); } @Override public void debug(String msg, Throwable e) { throw new RuntimeException("TODO"); } @Override public void warn(String msg) { throw new RuntimeException("TODO"); } @Override public void warn(String msg, Throwable e) { throw new RuntimeException("TODO"); } }
Set parallel to 1000 because supervisor + ulimit = fail
# Source Server Stats # File: sourcestats/settings.py # Desc: settings for the Flask server DEBUG = True # Number of servers to collect from in parallel PARALLEL = 1000 # Loop intervals (+time to execute!) COLLECT_INTERVAL = 30 FIND_INTERVAL = 300 # Timeout for reading addresses via UDP from Valve MASTER_TIMEOUT = 30 # Timeout for reading status from gameservers SERVER_TIMEOUT = 30 # Number of times a server fails before blacklisting FAIL_COUNT = 5 # Batch size for indexing documents in ES ES_BATCH = 1000 # Default number of terms to aggregate in ES (/players) ES_TERMS = 1000 ES_INDEX = 'sourcestats' ES_HOSTS = ['localhost:9200'] #VALVE_HOSTS = ['hl2master.steampowered.com'] VALVE_HOSTS = [ '208.64.200.52', '208.64.200.65', '208.64.200.39' ] # See: https://python-valve.readthedocs.org/en/latest/master_server.html#valve.source.master_server.MasterServerQuerier.find VALVE_REGIONS = [ u'na', u'sa', u'eu', u'as', u'oc', u'af', u'rest' ]
# Source Server Stats # File: sourcestats/settings.py # Desc: settings for the Flask server DEBUG = True # Number of servers to collect from in parallel PARALLEL = 4000 # Loop intervals (+time to execute!) COLLECT_INTERVAL = 30 FIND_INTERVAL = 300 # Timeout for reading addresses via UDP from Valve MASTER_TIMEOUT = 30 # Timeout for reading status from gameservers SERVER_TIMEOUT = 30 # Number of times a server fails before blacklisting FAIL_COUNT = 5 # Batch size for indexing documents in ES ES_BATCH = 1000 # Default number of terms to aggregate in ES (/players) ES_TERMS = 1000 ES_INDEX = 'sourcestats' ES_HOSTS = ['localhost:9200'] #VALVE_HOSTS = ['hl2master.steampowered.com'] VALVE_HOSTS = [ '208.64.200.52', '208.64.200.65', '208.64.200.39' ] # See: https://python-valve.readthedocs.org/en/latest/master_server.html#valve.source.master_server.MasterServerQuerier.find VALVE_REGIONS = [ u'na', u'sa', u'eu', u'as', u'oc', u'af', u'rest' ]
Remove return type breaking failing test
<?php declare(strict_types=1); namespace Moka\Tests; abstract class IncompleteAbstractTestClass implements TestInterface { public $public; protected $protected; private $private; public $isTrue; public static $getInt; public function isTrue(): bool { return true; } public function getInt(): int { return 11; } public function getSelf(): TestInterface { return $this; } public function getCallable(): callable { return function () { }; } public function withArgument(int $argument): int { return $argument; } public function withArguments( int $required, $nullable = null, string &$byReference = PHP_EOL, FooTestClass $class = null, array $array = [3], callable $callable = null, ...$variadic ): int { return $required; } public function throwException() { } abstract public function abstractMethod(); }
<?php declare(strict_types=1); namespace Moka\Tests; abstract class IncompleteAbstractTestClass implements TestInterface { public $public; protected $protected; private $private; public $isTrue; public static $getInt; public function isTrue(): bool { return true; } public function getInt(): int { return 11; } public function getSelf(): TestInterface { return $this; } public function getCallable(): callable { return function () { }; } public function withArgument(int $argument): int { return $argument; } public function withArguments( int $required, $nullable = null, string &$byReference = PHP_EOL, FooTestClass $class = null, array $array = [3], callable $callable = null, ...$variadic ): int { return $required; } public function throwException(): void { } abstract public function abstractMethod(); }
Update for newer selenium version.
from distutils.version import StrictVersion from selenium.webdriver.common.action_chains import ActionChains import selenium # To rexport here. from .config import * sel_ver = StrictVersion(selenium.__version__) v2_35_0 = StrictVersion("2.35.0") if sel_ver < v2_35_0: raise Exception("please ascertain whether the ActionChains.send_keys " "patch is required for Selenium version: " + selenium.__version__) if sel_ver >= v2_35_0 and sel_ver <= StrictVersion("2.37.2"): # Work around bug def send_keys(self, *keys_to_send): """ Sends keys to current focused element. :Args: - keys_to_send: The keys to send. """ self.key_down(keys_to_send) return self ActionChains.send_keys = send_keys
from distutils.version import StrictVersion from selenium.webdriver.common.action_chains import ActionChains import selenium from .config import * sel_ver = StrictVersion(selenium.__version__) v2_37_2 = StrictVersion("2.37.2") if sel_ver > v2_37_2: raise Exception("please ascertain whether the ActionChains.send_keys " "patch is required for Selenium version: " + selenium.__version__) if sel_ver >= StrictVersion("2.35.0") and sel_ver <= v2_37_2: # Work around bug def send_keys(self, *keys_to_send): """ Sends keys to current focused element. :Args: - keys_to_send: The keys to send. """ self.key_down(keys_to_send) return self ActionChains.send_keys = send_keys
Allow prefixed templates for different cart types
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from . import models from . import forms def cart(request, typ): cart = models.Cart.objects.get_or_create_from_request(request, typ) if request.method == 'POST': formset = forms.CartItemFormSet(instance=cart, data=request.POST) if formset.is_valid(): formset.save() return HttpResponseRedirect(reverse('satchless-cart-view', kwargs={'typ': typ})) else: formset = forms.CartItemFormSet(instance=cart) return render_to_response( ['satchless/cart/%s/view.html' % typ, 'satchless/cart/view.html'], {'cart': cart, 'formset': formset}, context_instance=RequestContext(request))
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.views.generic.simple import direct_to_template from . import models from . import forms def cart(request, typ): cart = models.Cart.objects.get_or_create_from_request(request, typ) if request.method == 'POST': formset = forms.CartItemFormSet(instance=cart, data=request.POST) if formset.is_valid(): formset.save() return HttpResponseRedirect(reverse('satchless-cart-view', kwargs={'typ': typ})) else: formset = forms.CartItemFormSet(instance=cart) return direct_to_template(request, 'satchless/cart/view.html', {'cart': cart, 'formset': formset})
Fix "amount from" for "Small orders"
package org.camunda.bpm.demo.orderconfirmation.config; import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO; import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import java.util.List; import java.util.logging.Logger; /* * Helper class to create an initial set of discount rules */ @Singleton @Startup public class DiscountRuleEntryConfig { private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName()); @Inject private RuleEntryDAO rulesDAO; /* * If no discount rules are present in the database, we create some initial ones */ @PostConstruct public void initializeDiscountRules() { List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries(); if ((rules == null) || (rules.size() == 0)) { log.info("Creating initial sample discount rules: ..."); rulesDAO.save(new DiscountRuleEntry("Small orders", 0, 500, 5)); rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7)); rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10)); } } }
package org.camunda.bpm.demo.orderconfirmation.config; import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO; import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import java.util.List; import java.util.logging.Logger; /* * Helper class to create an initial set of discount rules */ @Singleton @Startup public class DiscountRuleEntryConfig { private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName()); @Inject private RuleEntryDAO rulesDAO; /* * If no discount rules are present in the database, we create some initial ones */ @PostConstruct public void initializeDiscountRules() { List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries(); if ((rules == null) || (rules.size() == 0)) { log.info("Creating initial sample discount rules: ..."); rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5)); rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7)); rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10)); } } }
Fix small bugs in FreeDOM shim.
/** * @param {freedomWindow} The window in which the freedom module resides */ var FreedomCommunication = function(freedomWindow) { var contextWindows = []; freedomWindow.port.on('freedom_shim', function(args) { for (var i = 0; i < contextWindows.length; i++) { contextWindows[i].port.emit('freedom_shim', args); } }); var freedom = { addContentContext: function(context) { console.log('Adding context window to freedom'); contextWindows.push(context); context.port.on("freedom_shim_listen", function(event) { freedomWindow.port.emit("freedom_shim_listen", event); }); context.port.on("freedom_shim", function(args) { freedomWindow.port.emit('freedom_shim', args); }); }}; return freedom; }; exports.FreedomCommunication = FreedomCommunication;
/** * @param {freedomWindow} The window in which the freedom module resides */ var FreedomCommunication = function(freedomWindow) { var contextWindows = []; freedomWindow.port.on('freedom_shim', function(args) { for (var i = 0; i < freedom.contextWindows.length; i++) { freedom.contextWindows.port.emit('freedom_shim', args); } }); var freedom = { addContentContext: function(context) { console.log('Adding context window to freedom'); contextWindows.push(context); context.port.on("freedom_shim_listen", function(event) { freedomWindow.port.emit("freedom_shim_listen", event); }); context.port.on("freedom_shim", function(args) { freedomWindow.port.emit('freedom_shim', args); }); }}; return freedom; }; exports.FreedomCommunication = FreedomCommunication;
Use correct name on logger.change
<?php namespace Bolt\Provider; use Bolt\Logger\Manager; use Bolt\Logger\Handler\SystemHandler; use Bolt\Logger\Handler\RecordChangeHandler; use Monolog\Logger; use Silex\Application; use Silex\ServiceProviderInterface; /** * Monolog provider for Bolt system logging entries * * @author Gawain Lynch <gawain.lynch@gmail.com> */ class LoggerServiceProvider implements ServiceProviderInterface { public function register(Application $app) { // System log $app['logger.system'] = $app->share(function ($app) { $log = new Logger('logger.system'); $log->pushHandler(new SystemHandler($app)); return $log; }); // Changelog $app['logger.change'] = $app->share(function ($app) { $log = new Logger('logger.change'); $log->pushHandler(new RecordChangeHandler($app)); return $log; }); // Manager $app['logger.manager'] = $app->share(function ($app) { $mgr = new Manager($app); return $mgr; }); } public function boot(Application $app) { } }
<?php namespace Bolt\Provider; use Bolt\Logger\Manager; use Bolt\Logger\Handler\SystemHandler; use Bolt\Logger\Handler\RecordChangeHandler; use Monolog\Logger; use Silex\Application; use Silex\ServiceProviderInterface; /** * Monolog provider for Bolt system logging entries * * @author Gawain Lynch <gawain.lynch@gmail.com> */ class LoggerServiceProvider implements ServiceProviderInterface { public function register(Application $app) { // System log $app['logger.system'] = $app->share(function ($app) { $log = new Logger('logger.system'); $log->pushHandler(new SystemHandler($app)); return $log; }); // Changelog $app['logger.change'] = $app->share(function ($app) { $log = new Logger('logger.system'); $log->pushHandler(new RecordChangeHandler($app)); return $log; }); // Manager $app['logger.manager'] = $app->share(function ($app) { $mgr = new Manager($app); return $mgr; }); } public function boot(Application $app) { } }
Change teaser grid to use trending petitions
import React from 'react'; import TeaserGrid from 'components/TeaserGrid'; import Container from 'components/Container'; import BlockContainer from 'components/BlockContainer'; import Section from 'components/Section'; import Heading2 from 'components/Heading2'; import styles from './homepage-petitions.scss'; import Link from 'components/Link'; const HomepagePetitions = ({ petitions, title, text, linkText }) => ( <section> <Section> <Container> <BlockContainer> <div className={styles.head}> <Heading2 text={title} /> <Link href='/petitions'>{linkText}</Link> </div> </BlockContainer> <TeaserGrid petitions={petitions.trending} /> </Container> </Section> </section> ); export default HomepagePetitions;
import React from 'react'; import TeaserGrid from 'components/TeaserGrid'; import Container from 'components/Container'; import BlockContainer from 'components/BlockContainer'; import Section from 'components/Section'; import Heading2 from 'components/Heading2'; import styles from './homepage-petitions.scss'; import Link from 'components/Link'; const HomepagePetitions = ({ petitions, title, text, linkText }) => ( <section> <Section> <Container> <BlockContainer> <div className={styles.head}> <Heading2 text={title} /> <Link href='/petitions'>{linkText}</Link> </div> </BlockContainer> <TeaserGrid petitions={petitions.latest} /> </Container> </Section> </section> ); export default HomepagePetitions;
Delete redundant lines of code
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import dataproperty from ._text_writer import TextTableWriter class CsvTableWriter(TextTableWriter): """ Concrete class of a table writer for CSV format. :Examples: :ref:`example-csv-table-writer` """ @property def support_split_write(self): return True def __init__(self): super(CsvTableWriter, self).__init__() self.indent_string = u"" self.column_delimiter = u"," self.is_padding = False self.is_write_header_separator_row = False def _write_header(self): if dataproperty.is_empty_list_or_tuple(self.header_list): return super(CsvTableWriter, self)._write_header() def _get_opening_row_item_list(self): return [] def _get_value_row_separator_item_list(self): return [] def _get_closing_row_item_list(self): return []
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import dataproperty from ._text_writer import TextTableWriter class CsvTableWriter(TextTableWriter): """ Concrete class of a table writer for CSV format. :Examples: :ref:`example-csv-table-writer` """ @property def support_split_write(self): return True def __init__(self): super(CsvTableWriter, self).__init__() self.indent_string = u"" self.column_delimiter = u"," self.is_padding = False self.is_write_header_separator_row = False def _verify_header(self): pass def _write_header(self): if dataproperty.is_empty_list_or_tuple(self.header_list): return super(CsvTableWriter, self)._write_header() def _get_opening_row_item_list(self): return [] def _get_value_row_separator_item_list(self): return [] def _get_closing_row_item_list(self): return []
Make multiton creation thread safe and fix some code style.
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.core; import java.util.Map; import java.util.HashMap; public class MultitonInfo<T> implements Axiom, ContextFactory<T> { Map<Object, T> instanceMap = new HashMap<Object, T>(); String name; PropertyInfo p; public MultitonInfo(String name, PropertyInfo p) { this.name = name; this.p = p; } public String getName() { return name; } public synchronized T getInstance(Map<String, Object> args, X x) { Object key = args.get(p.getName()); if ( ! instanceMap.containsKey(key) ) { try { Class<T> type = (Class<T>)p.getClassInfo().getObjClass(); T obj = type.newInstance(); ((ContextAware)obj).setX(x); for ( Map.Entry<String, Object> entry : args.entrySet() ) { ((FObject)obj).setProperty(entry.getKey(), entry.getValue()); } instanceMap.put(key, obj); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } } return instanceMap.get(key); } }
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.core; import java.util.Map; import java.util.HashMap; public class MultitonInfo<T> implements Axiom, ContextFactory<T> { Map<Object, T> instanceMap = new HashMap<Object, T>(); String name; PropertyInfo p; public MultitonInfo(String name, PropertyInfo p) { this.name = name; this.p = p; } public String getName() { return name; } public T getInstance(Map<String, Object> args, X x) { Object key = args.get(p.getName()); if ( ! instanceMap.containsKey(key) ) { try { Class<T> type = (Class<T>)p.getClassInfo().getObjClass(); T obj = type.newInstance(); ((ContextAware)obj).setX(x); for (Map.Entry<String, Object> entry : args.entrySet()) { ((FObject)obj).setProperty(entry.getKey(), entry.getValue()); } instanceMap.put(key, obj); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } } return instanceMap.get(key); } }
Use sign instead of round Lets use the function for what it is designed for.
(function($){ $.permutation = function(){ return new Permutation($.toArray(arguments)); }; var Permutation = $.Permutation = function(image){ this.image = image; }; Permutation.prototype.actOn = function(element){ return this.image[element]; }; Permutation.prototype.multiply = function(permutation){ return new Permutation(this.image.map( function(element){ return permutation.actOn(element); } )); }; Permutation.prototype.isIdentity = function(){ return this.image.reduce(function(accumalator, element, index){ return accumalator && (element == index); }, true); }; Permutation.prototype.sign = function(){ var product = 1; for (var i = 0; i < this.image.length; i++) { for (var j = i + 1; j < this.image.length; j++) { product *= (this.image[i] - this.image[j]) / (i - j); } }; return Math.sign(product); }; })(window.wish = window.wish || {});
(function($){ $.permutation = function(){ return new Permutation($.toArray(arguments)); }; var Permutation = $.Permutation = function(image){ this.image = image; }; Permutation.prototype.actOn = function(element){ return this.image[element]; }; Permutation.prototype.multiply = function(permutation){ return new Permutation(this.image.map( function(element){ return permutation.actOn(element); } )); }; Permutation.prototype.isIdentity = function(){ return this.image.reduce(function(accumalator, element, index){ return accumalator && (element == index); }, true); }; Permutation.prototype.sign = function(){ var product = 1; for (var i = 0; i < this.image.length; i++) { for (var j = i + 1; j < this.image.length; j++) { product *= (this.image[i] - this.image[j]) / (i - j); } }; return Math.round(product); }; })(window.wish = window.wish || {});
Append app path to Python path in WSGI
""" WSGI config for federez_ldap project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import sys import os from os.path import dirname sys.path.append(dirname(dirname(__file__))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "federez_ldap.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for federez_ldap project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "federez_ldap.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
UPDATE - fix datafixtures bug
<?php namespace AdminBundle\DataFixtures\ORM; use AdminBundle\Entity\Admin; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; class LoadAdminData implements FixtureInterface, ContainerAwareInterface { private $container; public function setContainer(ContainerInterface $container = null) { $this->container = $container; } public function load(ObjectManager $manager) { $adminUser = new Admin(); $adminUser->setEmail("admin@admin.com"); $adminUser->setUsername("admin"); $password = $this->container->get('security.password_encoder')->encodePassword($adminUser, "admin"); $adminUser->setPassword($password); $adminUser->setFirstname('David'); $adminUser->setLastname('Kleiber'); $manager->persist($adminUser); $manager->flush(); } }
<?php namespace AdminBundle\DataFixtures\ORM; use AdminBundle\Entity\Admin; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; class LoadAdminData implements FixtureInterface, ContainerAwareInterface { private $container; public function setContainer(ContainerInterface $container = null) { $this->container = $container; } public function load(ObjectManager $manager) { $adminUser = new Admin(); $adminUser->setEmail("admin@admin.com"); $adminUser->setUsername("admin"); $password = $this->container->get('security.password_encoder')->encodePassword($adminUser, "admin"); $adminUser->setPassword($password); $manager->persist($adminUser); $manager->flush(); } }
Change to show error message when browserify failed
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var buffer = require("vinyl-buffer"); var reactify = require("reactify"); var watch = require("gulp-watch"); var plumber = require("gulp-plumber"); var uglify = require('gulp-uglify'); gulp.task("browserify", function() { var bs = browserify({ entries: ["./src/main.js"], transform: [reactify] }); bs.bundle() .on("error", function(e) { console.log(e.message) }) .pipe(plumber()) .pipe(source("app.js")) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest("./public/js")); }); gulp.task("watch", function() { gulp.watch("src/*.js", ["browserify"]); gulp.watch("src/*.jsx", ["browserify"]); }); gulp.task("default", ["browserify"]);
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var buffer = require("vinyl-buffer"); var reactify = require("reactify"); var watch = require("gulp-watch"); var plumber = require("gulp-plumber"); var uglify = require('gulp-uglify'); gulp.task("browserify", function() { var bs = browserify({ entries: ["./src/main.js"], transform: [reactify] }); bs.bundle() .on("error", function() {}) .pipe(plumber()) .pipe(source("app.js")) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest("./public/js")); }); gulp.task("watch", function() { gulp.watch("src/*.js", ["browserify"]); gulp.watch("src/*.jsx", ["browserify"]); }); gulp.task("default", ["browserify"]);
Remove Feature flag from the location security check for dashboard
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) if icds_pre_release_features(request.couch_user): loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
Move fatal throw to separate function
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; // Throw a fatal error const fatal = err => { console.error(`fatal: ${err}`); } process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { fatal("Could not change the previous commit"); } else { console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } }); } else { fatal("Could not parse \"" + date + "\" into a valid date"); } } else { fatal("No date string given"); }
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
Prepare help command for inheritance
package io.georocket.commands; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import de.undercouch.underline.InputReader; import de.undercouch.underline.OptionParserException; import de.undercouch.underline.UnknownAttributes; import io.georocket.GeoRocketCli; import io.vertx.core.Handler; /** * Displays a command's help * @author Michel Kraemer */ public class HelpCommand extends AbstractGeoRocketCommand { protected List<String> commands = new ArrayList<String>(); /** * Sets the commands to display the help for * @param commands the commands */ @UnknownAttributes("COMMAND") public void setCommands(List<String> commands) { this.commands = commands; } @Override public String getUsageName() { return "help"; } @Override public String getUsageDescription() { return "Display a command's help"; } @Override public void doRun(String[] remainingArgs, InputReader in, PrintWriter out, Handler<Integer> handler) throws OptionParserException, IOException { // simply forward commands to GeoRocketCli and append '-h' GeoRocketCli cmd = new GeoRocketCli(); cmd.setup(); String[] args = commands.toArray(new String[commands.size() + 1]); args[args.length - 1] = "-h"; cmd.setEndHandler(handler); cmd.run(args, in, out); } }
package io.georocket.commands; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import de.undercouch.underline.InputReader; import de.undercouch.underline.OptionParserException; import de.undercouch.underline.UnknownAttributes; import io.georocket.GeoRocketCli; import io.vertx.core.Handler; /** * Displays a command's help * @author Michel Kraemer */ public class HelpCommand extends AbstractGeoRocketCommand { private List<String> commands = new ArrayList<String>(); /** * Sets the commands to display the help for * @param commands the commands */ @UnknownAttributes("COMMAND") public void setCommands(List<String> commands) { this.commands = commands; } @Override public String getUsageName() { return "help"; } @Override public String getUsageDescription() { return "Display a command's help"; } @Override public void doRun(String[] remainingArgs, InputReader in, PrintWriter out, Handler<Integer> handler) throws OptionParserException, IOException { // simply forward commands to GeoRocketCli and append '-h' GeoRocketCli cmd = new GeoRocketCli(); cmd.setup(); String[] args = commands.toArray(new String[commands.size() + 1]); args[args.length - 1] = "-h"; cmd.setEndHandler(handler); cmd.run(args, in, out); } }
Use `op` instead of `app` so that `list_migrations` still works By importing `app` the `list_migrations.py` script broke because it doesn't have the `app` context.
"""DOS is coming Revision ID: 420 Revises: 410_remove_empty_drafts Create Date: 2015-11-16 14:10:35.814066 """ # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") conn = op.get_bind() res = conn.execute("SELECT * FROM frameworks WHERE slug = 'digital-outcomes-and-specialists'") results = res.fetchall() if not results: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """)
"""DOS is coming Revision ID: 420 Revises: 410_remove_empty_drafts Create Date: 2015-11-16 14:10:35.814066 """ # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op import sqlalchemy as sa from app.models import Framework def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") framework = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists').first() if not framework: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """)
Add `field` to error message
import { ObjectId } from 'mongodb'; import Type from '../core/type'; export const MongoIdType = new Type({ name: 'mongoid', generatePrimaryKeyVal() { return new ObjectId(); }, fromString(str) { return ObjectId(str); }, fromClient(field, value) { if (value instanceof ObjectId) { return value; } if (value) { const str = value.toString(); // we don't want to accept 12-byte strings from the client if (str.length !== 24) { throw new Error(`Invalid ObjectId for field ${field}`); } return ObjectId(str); } //return undefined; }, toClient(field, value) { return value ? value.toString() : value; } });
import { ObjectId } from 'mongodb'; import Type from '../core/type'; export const MongoIdType = new Type({ name: 'mongoid', generatePrimaryKeyVal() { return new ObjectId(); }, fromString(str) { return ObjectId(str); }, fromClient(field, value) { if (value instanceof ObjectId) { return value; } if (value) { const str = value.toString(); // we don't want to accept 12-byte strings from the client if (str.length !== 24) { throw new Error('Invalid ObjectId'); } return ObjectId(str); } //return undefined; }, toClient(field, value) { return value ? value.toString() : value; } });
Select all dupes except the lowest UID. Drupal’s user_load_by_mail function used in the login process resolves the lowest UID when trying to log in, so these are never accessed.
<?php /** * Script to remove users with * * to run: * drush --script-path=../scripts/ php-script remove-duplicate-emails.php */ $users = db_query('SELECT * FROM users WHERE mail IN (SELECT mail FROM users GROUP BY mail HAVING COUNT(mail) > 1) AND uid NOT IN (SELECT MIN(uid) FROM users GROUP BY mail HAVING COUNT(mail) > 1)'); foreach ($users as $user) { $user = user_load($user->uid); if($user->access == 0) { print 'Deleting ' . $user->uid . ' ('. $user->mail . ')' . PHP_EOL; $northstar_id = $user->field_northstar_id[LANGUAGE_NONE][0]['value']; if ($northstar_id !== 'NONE') { print 'User ' . $user->uid . ' has a Northstar profile: ' . $northstar_id; } user_delete($user->uid); } else { print 'Ignoring duplicate ' . $user->uid . ' ('. $user->mail . ')' . PHP_EOL; } }
<?php /** * Script to remove users with * * to run: * drush --script-path=../scripts/ php-script remove-duplicate-emails.php */ $users = db_query('SELECT * FROM users u WHERE mail IN (SELECT mail FROM users GROUP BY mail HAVING COUNT(mail) > 1);'); foreach ($users as $user) { $user = user_load($user->uid); if($user->access == 0) { print 'Deleting ' . $user->uid . ' ('. $user->mail . ')' . PHP_EOL; $northstar_id = $user->field_northstar_id[LANGUAGE_NONE][0]['value']; if ($northstar_id !== 'NONE') { print 'User ' . $user->uid . ' has a Northstar profile: ' . $northstar_id; } user_delete($user->uid); } else { print 'Ignoring duplicate ' . $user->uid . ' ('. $user->mail . ')' . PHP_EOL; } }
Remove default implementation of fullList() Using a limit of Long.MAX_VALUE can degrade performances
package fr.openwide.core.jpa.more.business.search.query; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import fr.openwide.core.jpa.more.business.sort.ISort; import fr.openwide.core.jpa.more.business.sort.ISort.SortOrder; public abstract class AbstractSearchQuery<T, S extends ISort<?>> implements ISearchQuery<T, S> /* NOT Serializable */ { @PersistenceContext protected EntityManager entityManager; protected List<S> defaultSorts; protected Map<S, SortOrder> sortMap; @SafeVarargs protected AbstractSearchQuery(S ... defaultSorts) { this.defaultSorts = ImmutableList.copyOf(defaultSorts); } // Sort @Override public ISearchQuery<T, S> sort(Map<S, SortOrder> sortMap) { this.sortMap = ImmutableMap.copyOf(sortMap); return this; } }
package fr.openwide.core.jpa.more.business.search.query; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import fr.openwide.core.jpa.more.business.sort.ISort; import fr.openwide.core.jpa.more.business.sort.ISort.SortOrder; public abstract class AbstractSearchQuery<T, S extends ISort<?>> implements ISearchQuery<T, S> /* NOT Serializable */ { @PersistenceContext protected EntityManager entityManager; protected List<S> defaultSorts; protected Map<S, SortOrder> sortMap; @SafeVarargs protected AbstractSearchQuery(S ... defaultSorts) { this.defaultSorts = ImmutableList.copyOf(defaultSorts); } // Sort @Override public ISearchQuery<T, S> sort(Map<S, SortOrder> sortMap) { this.sortMap = ImmutableMap.copyOf(sortMap); return this; } // May be overridden for performance purposes @Override @Transactional(readOnly = true) public List<T> fullList() { return list(0, Long.MAX_VALUE); } }
Set a JWT signature algorithm for the Globus backend to RS512
""" Globus Auth OpenID Connect backend, docs at: https://docs.globus.org/api/auth http://globus-integration-examples.readthedocs.io """ from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' JWT_ALGORITHMS = ['RS256', 'RS512'] EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
""" Globus Auth OpenID Connect backend, docs at: https://docs.globus.org/api/auth http://globus-integration-examples.readthedocs.io """ from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
Reorder functions to fix linting
const escapeClass = str => String(str).replace(/[^a-z0-9]/g, ''); const escapeHTML = str => { const div = document.createElement('div'); div.appendChild(document.createTextNode(str)); return div.innerHTML; }; const emptyHTML = `<span class="playbyplay-empty">History is empty.</span>`; const statusClass = run => run.status ? `playbyplay-status-${escapeClass(run.status)}` : ''; const runHTML = (run, index) => `<tr class="playbyplay-run ${statusClass(run)}"> <td class="playbyplay-col playbyplay-input"> <pre class="playbyplay-pre"><code>${escapeHTML(run.input)}</code></pre> </td> <td class="playbyplay-col playbyplay-output"> <pre class="playbyplay-pre">${escapeHTML(run.output)}</pre> </td> <td class="playbyplay-col"> <button class="playbyplay-button playbyplay-restore" data-index="${index}"> Restore </button> </td> </tr>`; const runsHTML = runs => `<button class="playbyplay-button playbyplay-clear">Clear</button> <table class="playbyplay-runs"> ${runs.map(runHTML).join('')} </table>`; const containerInnerHTML = runs => `<button class="playbyplay-button playbyplay-hide">&lt; Back</button>` + `${runs.length ? runsHTML(runs) : emptyHTML}`; export default containerInnerHTML;
const escapeClass = str => String(str).replace(/[^a-z0-9]/g, ''); const escapeHTML = str => { const div = document.createElement('div'); div.appendChild(document.createTextNode(str)); return div.innerHTML; }; const containerInnerHTML = runs => `<button class="playbyplay-button playbyplay-hide">&lt; Back</button>` + `${runs.length ? runsHTML(runs) : emptyHTML}`; const runsHTML = runs => `<button class="playbyplay-button playbyplay-clear">Clear</button> <table class="playbyplay-runs"> ${runs.map(runHTML).join('')} </table>`; const runHTML = (run, index) => `<tr class="playbyplay-run ${statusClass(run)}"> <td class="playbyplay-col playbyplay-input"> <pre class="playbyplay-pre"><code>${escapeHTML(run.input)}</code></pre> </td> <td class="playbyplay-col playbyplay-output"> <pre class="playbyplay-pre">${escapeHTML(run.output)}</pre> </td> <td class="playbyplay-col"> <button class="playbyplay-button playbyplay-restore" data-index="${index}"> Restore </button> </td> </tr>`; const statusClass = run => run.status ? `playbyplay-status-${escapeClass(run.status)}` : ''; const emptyHTML = `<span class="playbyplay-empty">History is empty.</span>`; export default containerInnerHTML;
Fix initialization of OC_Filesystem setup from DAV
<?php /** * ownCloud * * @author Jakob Sack * @copyright 2011 Jakob Sack kde@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library 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 library. If not, see <http://www.gnu.org/licenses/>. * */ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic { /** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @return bool */ protected function validateUserPass($username, $password){ OC_Util::setUpFS();//login hooks may need early access to the filesystem if(OC_User::login($username,$password)){ OC_Util::setUpFS($username); return true; } else{ return false; } } }
<?php /** * ownCloud * * @author Jakob Sack * @copyright 2011 Jakob Sack kde@jakobsack.de * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library 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 library. If not, see <http://www.gnu.org/licenses/>. * */ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic { /** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @return bool */ protected function validateUserPass($username, $password){ OC_Util::setUpFS();//login hooks may need early access to the filesystem if(OC_User::login($username,$password)){ OC_Util::setUpFS(); return true; } else{ return false; } } }
Remove the no-JS version from the app I haven't looked into it for a long while.
from flask import Flask, g from .main.views import main from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
from flask import Flask, g from .main.views import main from .nojs.views import nojs from sqlalchemy import create_engine from smoke_signal.database.models import Base from sqlalchemy.orm import sessionmaker app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") app.config.from_pyfile("config.py") app.register_blueprint(main) app.register_blueprint(nojs) @app.before_request def init_db(): engine = create_engine(app.config["DATABASE_PATH"]) if not engine.dialect.has_table(engine.connect(), "feed"): Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) g.db = Session() @app.teardown_appcontext def shutdown_session(exception=None): db = getattr(g, 'db', None) if db is not None: g.db.close()
Fix unit test that refers to a now-aliased time zone.
<?php class A01_Frontend_ProfileCest extends CestAbstract { /** * @before setupComplete * @before login */ public function setProfileInfo(FunctionalTester $I) { $I->wantTo('Set a user profile.'); $I->amOnPage('/dashboard'); $I->see('Dashboard'); $I->amOnPage('/profile'); $I->see('Profile'); $I->see('Super Administrator'); $I->click('Edit'); $I->submitForm('.form', [ 'timezone' => 'America/Chicago', 'locale' => 'fr_FR.UTF-8', ]); $I->seeCurrentUrlEquals('/profile'); $I->see('Chicago'); $I->see('Français'); } }
<?php class A01_Frontend_ProfileCest extends CestAbstract { /** * @before setupComplete * @before login */ public function setProfileInfo(FunctionalTester $I) { $I->wantTo('Set a user profile.'); $I->amOnPage('/dashboard'); $I->see('Dashboard'); $I->amOnPage('/profile'); $I->see('Profile'); $I->see('Super Administrator'); $I->click('Edit'); $I->submitForm('.form', [ 'timezone' => 'US/Central', 'locale' => 'fr_FR.UTF-8', ]); $I->seeCurrentUrlEquals('/profile'); $I->see('Central Time'); $I->see('Français'); } }
Add appcontext to router history
"use strict"; //This JS file simply bootstraps the app from the root component when the window loads var AppRoot = require('./components/AppRoot.jsx'); var Home = require('./components/Home.jsx'); var React = require('react'); var ReactDOM = require('react-dom'); var Redirect = require('react-router').Redirect; var Router = require('react-router').Router; var Route = require('react-router').Route; var useRouterHistory = require('react-router').useRouterHistory; var createHistory = require('history').createHistory; const history = useRouterHistory(createHistory)({ basename: '/react-bp' }); //Keep references to these outside of the function var appRootComponent; //This function executes immediately (function() { //This function is attached to execute when the window loads document.addEventListener('DOMContentLoaded', function() { ReactDOM.render( /* jshint ignore:start */ <Router history={history}> <Route path="/" component={AppRoot}> <Route path="/home" component={Home}/> <Redirect from="*" to="/home"/> </Route> </Router>, document.getElementById('app') /* jshint ignore:end */ ); }); })();
"use strict"; //This JS file simply bootstraps the app from the root component when the window loads var AppRoot = require('./components/AppRoot.jsx'); var Home = require('./components/Home.jsx'); var React = require('react'); var ReactDOM = require('react-dom'); var Redirect = require('react-router').Redirect; var Router = require('react-router').Router; var Route = require('react-router').Route; var browserHistory = require('react-router').browserHistory; //Keep references to these outside of the function var appRootComponent; //This function executes immediately (function() { //This function is attached to execute when the window loads document.addEventListener('DOMContentLoaded', function() { ReactDOM.render( /* jshint ignore:start */ <Router history={browserHistory}> <Route path="/" component={AppRoot}> <Route path="/home" component={Home}/> <Redirect from="*" to="/home"/> </Route> </Router>, document.getElementById('app') /* jshint ignore:end */ ); }); })();
Update dev tool for applying ES patches Adds path rewrite for `test/framework` -> `es/es-testing/`
#!/usr/bin/env python3 """ Use to apply patches from ES upstream with: git apply --reject \ <(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py) """ import sys def main(): for line in sys.stdin: sys.stdout.write( line .replace('diff --git a/server/', 'diff --git a/es/es-server/') .replace('--- a/server/', '--- a/es/es-server/') .replace('+++ b/server/', '+++ b/es/es-server/') .replace('diff --git a/test/framework', 'diff --git a/es/es-testing/') .replace('--- a/test/framework', '--- a/es/es-testing/') .replace('+++ b/test/framework', '+++ b/es/es-testing/') ) if __name__ == "__main__": main()
#!/usr/bin/env python3 """ Use to apply patches from ES upstream with: git apply --reject \ <(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py) """ import sys def main(): for line in sys.stdin: sys.stdout.write( line .replace('diff --git a/server/', 'diff --git a/es/es-server/') .replace('--- a/server/', '--- a/es/es-server/') .replace('+++ b/server/', '+++ b/es/es-server/') ) if __name__ == "__main__": main()
Add fetch for student id data on initial load
import React from 'react' import { AppState } from 'react-native' import { connect } from 'react-redux' class AppStateContainer extends React.Component { state = { appState: AppState.currentState } async componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange) } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange) } _handleAppStateChange = (nextAppState) => { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { this.props.updateStudentProfile() } this.setState({ appState: nextAppState }) } render() { this.props.updateStudentProfile() return null } } const mapDispatchToProps = (dispatch, ownProps) => ( { updateStudentProfile: () => { dispatch({ type: 'UPDATE_STUDENT_PROFILE' }) } } ) module.exports = connect(null, mapDispatchToProps)(AppStateContainer)
import React from 'react' import { AppState } from 'react-native' import { connect } from 'react-redux' class AppStateContainer extends React.Component { state = { appState: AppState.currentState } async componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange) } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange) } _handleAppStateChange = (nextAppState) => { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { this.props.updateStudentProfile() } this.setState({ appState: nextAppState }) } render() { return null } } const mapDispatchToProps = (dispatch, ownProps) => ( { updateStudentProfile: () => { dispatch({ type: 'UPDATE_STUDENT_PROFILE' }) } } ) module.exports = connect(null ,mapDispatchToProps)(AppStateContainer)
Change endpoint for the api calls
import * as $ from "../../bower_components/jquery/dist/jquery"; export const DEBUG = true /** * Function to make all the api calls. * @param url * @param options * @param success_cb * @param failure_cb */ export function ajaxRequest(url, options={}, success_cb=null, failure_cb=null) { var defaultOptions = { method: 'GET' } $.extend(defaultOptions, options) $.ajax({ url: url, method: options.method }) .done((data) => { if (success_cb) success_cb(data) }) .fail((data) => { if (failure_cb) failure_cb(data) if (DEBUG) { console.warn('There was an error on the request. More info:') console.log(data) } }) } export function cfModal(inner, options={}) { let default_options = {} }
import * as $ from "../../bower_components/jquery/dist/jquery"; export const API_ENDPOINT = 'http://localhost:8000'; export const DEBUG = true /** * Function to make all the api calls. * @param url * @param options * @param success_cb * @param failure_cb */ export function ajaxRequest(url, options={}, success_cb=null, failure_cb=null) { var defaultOptions = { method: 'GET' } $.extend(defaultOptions, options) $.ajax({ url: API_ENDPOINT + url, method: options.method }) .done((data) => { if (success_cb) success_cb(data) }) .fail((data) => { if (failure_cb) failure_cb(data) if (DEBUG) { console.warn('There was an error on the request. More info:') console.log(data) } }) } export function cfModal(inner, options={}) { let default_options = {} }
Add fallback array map trim for all input fields by default
<?php /* * NOTICE OF LICENSE * * Part of the Rinvex Support Package. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Rinvex Support Package * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Rinvex\Support\Http\Requests; use Illuminate\Foundation\Http\FormRequest as BaseFormRequest; class FormRequest extends BaseFormRequest { /** * {@inheritdoc} */ protected function getValidatorInstance() { if (method_exists($this, 'process')) { $this->replace($this->container->call([$this, 'process'], [$this->all()])); } else { $this->replace(array_filter(array_map(function ($item) { return is_string($item) ? trim($item) : $item; }, $this->all()))); } return parent::getValidatorInstance(); } }
<?php /* * NOTICE OF LICENSE * * Part of the Rinvex Support Package. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Rinvex Support Package * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Rinvex\Support\Http\Requests; use Illuminate\Foundation\Http\FormRequest as BaseFormRequest; class FormRequest extends BaseFormRequest { /** * {@inheritdoc} */ protected function getValidatorInstance() { if (method_exists($this, 'process')) { $this->replace($this->container->call([$this, 'process'], [$this->all()])); } return parent::getValidatorInstance(); } }
Add blur filter to all images in css
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = 'transparent'; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ', ' + '1)' }); }); css.walkRules('img', function (decl) { // Find all filter declarations css.walkDecls('filter', function (decl) { // Add blur filter to existing filters decl.value = 'blur(5px) ' + decl.value; }); //find all images in css css.walkRules('img', function (decl) { //Add blur filter to images decl.append({ prop: 'filter', value: 'blur(5px)' }); }); }; });
var postcss = require('postcss'), color = require('color'); module.exports = postcss.plugin('postcss-lowvision', function () { return function (css) { css.walkDecls('color', function (decl) { var val = decl.value; var rgb = color(val); rgb = rgb.rgbArray(); decl.value = 'transparent'; decl.cloneAfter({ prop: 'text-shadow', value: '0 0 5px rgba(' + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ', ' + '1)' }); }); css.walkRules('img', function (decl) { // Find all filter declarations css.walkDecls('filter', function (decl) { // Add blur filter to existing filters decl.value = 'blur(5px) ' + decl.value; }); decl.append({ prop: 'filter', value: 'blur(5px)' }); }); }; });
Use `Number.isNaN` when it's available.
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { if (undefined !== Number.isNaN) { return Number.isNaN(subject); } else { // There is no Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { // There is not Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
Move variable declarations and add section headers
'use strict'; // TODO: clean-up // MODULES // var abs = require( '@stdlib/math/base/special/abs' ); var divide = require( 'compute-divide' ); var mean = require( 'compute-mean' ); var subtract = require( 'compute-subtract' ); var asinh = require( './../lib' ); // FIXTURES // var data = require( './fixtures/julia/data.json' ); // MAIN // var nativeErrs; var customErrs; var yexpected; var ynative; var ycustom; var x; var i; x = data.x; yexpected = data.expected; ycustom = new Array( x.length ); ynative = new Array( x.length ); for ( i = 0; i < x.length; i++ ) { if ( yexpected[ i ] === 0.0 ) { yexpected[ i ] += 1e-16; } ycustom[ i ] = asinh( x[ i ] ); ynative[ i ] = Math.asinh( x[ i ] ); } customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) ); nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) ); console.log( 'The mean relative error of Math.asinh compared to Julia is %d', mean( nativeErrs ) ); console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
'use strict'; // TODO: clean-up var abs = require( '@stdlib/math/base/special/abs' ); var divide = require( 'compute-divide' ); var mean = require( 'compute-mean' ); var subtract = require( 'compute-subtract' ); var asinh = require( './../lib' ); var data = require( './fixtures/julia/data.json' ); var x = data.x; var yexpected = data.expected; var ycustom = new Array( x.length ); var ynative = new Array( x.length ); for ( var i = 0; i < x.length; i++ ) { if ( yexpected[ i ] === 0.0 ) { yexpected[ i ] += 1e-16; } ycustom[ i ] = asinh( x[ i ] ); ynative[ i ] = Math.asinh( x[ i ] ); } var customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) ); var nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) ); console.log( 'The mean relative error of Math.asinh compared to Julia is %d', mean( nativeErrs ) ); console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
Add `id` to `SystemHealthEndpoint` response.
from __future__ import absolute_import import itertools from hashlib import md5 from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (SuperuserPermission,) def get(self, request): results = status_checks.check_all() return Response({ 'problems': map( lambda problem: { 'id': md5(problem.message).hexdigest(), 'message': problem.message, 'severity': problem.severity, 'url': problem.url, }, sorted(itertools.chain.from_iterable(results.values()), reverse=True), ), 'healthy': {type(check).__name__: not problems for check, problems in results.items()}, })
from __future__ import absolute_import import itertools from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (SuperuserPermission,) def get(self, request): results = status_checks.check_all() return Response({ 'problems': map( lambda problem: { 'message': problem.message, 'severity': problem.severity, 'url': problem.url, }, sorted(itertools.chain.from_iterable(results.values()), reverse=True), ), 'healthy': {type(check).__name__: not problems for check, problems in results.items()}, })
Fix in JS Engine test.
package com.axiastudio.zoefx.core.script; import com.axiastudio.zoefx.core.Utilities; import org.junit.BeforeClass; import org.junit.Test; /** * User: tiziano * Date: 14/04/14 * Time: 16:48 */ public class JSScriptEngineImplTest { @BeforeClass public static void setUpClass() { JSEngineImpl engine = new JSEngineImpl(); Utilities.registerUtility(engine, ScriptEngine.class); } @Test public void testEval() throws Exception { ScriptEngine engine = Utilities.queryUtility(ScriptEngine.class); String script = "return \"ciao\";"; Object eval = engine.eval(script); assert eval.toString().equals("ciao"); } }
package com.axiastudio.zoefx.core.script; import com.axiastudio.zoefx.core.Utilities; import org.junit.BeforeClass; import org.junit.Test; /** * User: tiziano * Date: 14/04/14 * Time: 16:48 */ public class JSScriptEngineImplTest { @BeforeClass public static void setUpClass() { JSEngineImpl engine = new JSEngineImpl(); Utilities.registerUtility(engine, ScriptEngine.class); } @Test public void testEval() throws Exception { ScriptEngine engine = Utilities.queryUtility(ScriptEngine.class); String script = "function test(){ return \"ciao\"; } test()"; Object eval = engine.eval(script); assert eval.toString().equals("ciao"); } }
Change `List` so that it sets it's head, tail and `length` properties & export it from module.
/* vim:set ts=2 sw=2 sts=2 expandtab */ /*jshint asi: true undef: true es5: true node: true browser: true devel: true forin: true latedef: false globalstrict: true */ 'use strict'; var sequence = require('./sequence'), isEmpty = sequence.isEmpty, count = sequence.count, first = sequence.first, rest = sequence.rest, cons = sequence.cons, make = sequence.make, empty = sequence.empty function List(head, tail) { this.head = head this.tail = tail || empty this.length = count(tail) + 1 } List.prototype.length = 0 List.prototype.toString = function() { var value = '', tail = this; while (!isEmpty(tail)) { value = value + ' ' + first(tail) tail = rest(tail) } return '(' + value.substr(1) + ')' } exports.List = List count.define(List, function(list) { return list.length }) first.define(List, function(list) { return list.head }) rest.define(List, function(list) { return list.tail }) make.define(List, function(tail, head) { return new List(head, tail) }) function list() { var items = arguments, count = items.length, tail = empty while (count--) tail = cons(items[count], tail) return tail } exports.list = list
/* vim:set ts=2 sw=2 sts=2 expandtab */ /*jshint asi: true undef: true es5: true node: true browser: true devel: true forin: true latedef: false globalstrict: true */ 'use strict'; var sequence = require('./sequence'), isEmpty = sequence.isEmpty, count = sequence.count, first = sequence.first, rest = sequence.rest, cons = sequence.cons, make = sequence.make, empty = sequence.empty function List() {} List.prototype.length = 0 List.prototype.toString = function() { var value = '', tail = this; while (!isEmpty(tail)) { value = value + ' ' + first(tail) tail = rest(tail) } return '(' + value.substr(1) + ')' } count.define(List, function(list) { return list.length }) first.define(List, function(list) { return list.head }) rest.define(List, function(list) { return list.tail }) make.define(List, function(tail, head) { return new List(head, tail) }) function list() { var items = arguments, count = items.length, tail = empty while (count--) tail = cons(items[count], tail) return tail } exports.list = list
Change plotDipole to return html instead of saving it as a file
""" analysis/rxd.py Functions to plot and analyze RxD-related results Contributors: salvadordura@gmail.com """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from netpyne import __gui__ if __gui__: import matplotlib.pyplot as plt from matplotlib_scalebar import scalebar from .utils import exception, _showFigure, _saveFigData import numpy as np # ------------------------------------------------------------------------------------------------------------------- ## Plot HNN dipole # ------------------------------------------------------------------------------------------------------------------- @exception def plotDipole(): from .. import sim from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import file_html from bokeh.layouts import layout TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select" fig = figure(title="HNN Diple Plot", tools=TOOLS) spkt = sim.allSimData['spkt'] spkid = sim.allSimData['spkid'] fig.scatter(spkt, spkid, size=1, legend="all spikes") plot_layout = layout(fig, sizing_mode='scale_both') html = file_html(plot_layout, CDN, title="HNN Dipole Plot (spikes for now!)") return html
""" analysis/rxd.py Functions to plot and analyze RxD-related results Contributors: salvadordura@gmail.com """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from netpyne import __gui__ if __gui__: import matplotlib.pyplot as plt from matplotlib_scalebar import scalebar from .utils import exception, _showFigure, _saveFigData import numpy as np # ------------------------------------------------------------------------------------------------------------------- ## Plot HNN dipole # ------------------------------------------------------------------------------------------------------------------- @exception def plotDipole(): from .. import sim from bokeh.plotting import figure, show, output_file TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select" fig = figure(title="HNN Diple Plot", tools=TOOLS) spkt = sim.allSimData['spkt'] spkid = sim.allSimData['spkid'] fig.scatter(spkt, spkid, size=1, legend="all spikes") output_file("hnn_dipole.html", title="HNN Dipole Plot (spikes for now!)") show(fig) # open a browser
Add testing setup See if Sinon works for you
const chai = require('chai') const assert = chai.assert; const sinon = require('sinon/pkg/sinon'); const Ball = require("../lib/ball") describe("Ball", function(){ context("with assigned attributes", function(){ var ball = new Ball(2, 2, 10) it("should have an x position", function(){ assert.equal(ball.x, 2) }) it("should have a y position", function(){ assert.equal(ball.y, 2) }) it("should have a radius", function(){ assert.equal(ball.radius, 10) }) it("should not be moving", function(){ assert.equal(ball.moving, false) }) context("when moving", function(){ var ball = new Ball(2, 2, 10) xit("should increase its x and y with no bounce", sinon.test(function(){ ball = Ball.new(0, 0, 10) ball.speed = 1; ball.xDirection = 1; ball.yDirection = 1; var noBounce = sinon.stub(Ball, "bounceCheck"); noBounce.yields(null, this) ball.move(); nobounce.restore(); })) }) })
const chai = require('chai') const assert = chai.assert; const sinon = require('sinon/pkg/sinon'); const Ball = require("../lib/ball") describe("Ball", function(){ context("with assigned attributes", function(){ var ball = new Ball(2, 2, 10) it("should have an x position", function(){ assert.equal(ball.x, 2) }) it("should have a y position", function(){ assert.equal(ball.y, 2) }) it("should have a radius", function(){ assert.equal(ball.radius, 10) }) it("should not be moving", function(){ assert.equal(ball.moving, false) }) context("when moving", function(){ var ball = new Ball(2, 2, 10) it("should increase its x and y with no bounce", sinon.test(function(){ ball = Ball.new(0, 0, 10) ball.speed = 1; ball.xDirection = 1; ball.yDirection = 1; var noBounce = sinon.stub(Ball, "bounceCheck"); noBounce.yields(null, this) ball.move(); nobounce.restore(); })) }) })
Add support for ./hash to mcmanage
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
Add docstring into load function Follow to Google style.
# Copyright 2015-2016 Masayuki Yamamoto # # 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. """Handle nicovideo.jp user_session.""" import pkg_resources class LoaderNotFoundError(Exception): """Session loader is not found.""" class UserSessionNotFoundError(Exception): """Profile exists, but user_session is not found.""" def load(ltype, profile): """Return nicovideo.jp user session string. Args: ltype (str): loader type profile (str): file path for profile Returns: str: user session Raises: LoaderNotFoundError Error from loader """ for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype): load_func = entry.load() return load_func(profile) raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
# Copyright 2015-2016 Masayuki Yamamoto # # 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. """Handle nicovideo.jp user_session.""" import pkg_resources class LoaderNotFoundError(Exception): """Session loader is not found.""" class UserSessionNotFoundError(Exception): """Profile exists, but user_session is not found.""" def load(ltype, profile): for entry in pkg_resources.iter_entry_points('yanico.sessions', ltype): load_func = entry.load() return load_func(profile) raise LoaderNotFoundError('{} loader is not found.'.format(ltype))
Remove unused apps from the DocumentType typeahead Summary: Ref T10951. This diff removes uninstalled applications from the result set for DocumentType restults Test Plan: Uninstall an application (diviner for example), then go to the document type search menu and ensure that the uninstalled application doesn't show up. Reviewers: #blessed_reviewers, epriestley Reviewed By: #blessed_reviewers, epriestley Subscribers: epriestley Maniphest Tasks: T10951 Differential Revision: https://secure.phabricator.com/D16445
<?php final class PhabricatorSearchDocumentTypeDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Document Types'); } public function getPlaceholderText() { return pht('Select a document type...'); } public function getDatasourceApplicationClass() { return 'PhabricatorSearchApplication'; } public function loadResults() { $results = $this->buildResults(); return $this->filterResultsAgainstTokens($results); } public function renderTokens(array $values) { return $this->renderTokensFromResults($this->buildResults(), $values); } private function buildResults() { $viewer = $this->getViewer(); $types = PhabricatorSearchApplicationSearchEngine::getIndexableDocumentTypes( $viewer); $icons = mpull( PhabricatorPHIDType::getAllTypes(), 'getTypeIcon', 'getTypeConstant'); $results = array(); foreach ($types as $type => $name) { $results[$type] = id(new PhabricatorTypeaheadResult()) ->setPHID($type) ->setName($name) ->setIcon(idx($icons, $type)); } return $results; } }
<?php final class PhabricatorSearchDocumentTypeDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Document Types'); } public function getPlaceholderText() { return pht('Select a document type...'); } public function getDatasourceApplicationClass() { return 'PhabricatorSearchApplication'; } public function loadResults() { $results = $this->buildResults(); return $this->filterResultsAgainstTokens($results); } public function renderTokens(array $values) { return $this->renderTokensFromResults($this->buildResults(), $values); } private function buildResults() { $types = PhabricatorSearchApplicationSearchEngine::getIndexableDocumentTypes(); $icons = mpull( PhabricatorPHIDType::getAllTypes(), 'getTypeIcon', 'getTypeConstant'); $results = array(); foreach ($types as $type => $name) { $results[$type] = id(new PhabricatorTypeaheadResult()) ->setPHID($type) ->setName($name) ->setIcon(idx($icons, $type)); } return $results; } }
Fix forgotten registration of BeanDefinitionParser for <management:jms-caching-connection-factory>
/* * Copyright 2008-2010 Xebia and the original author or 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 fr.xebia.management.config; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * {@link org.springframework.beans.factory.xml.NamespaceHandler} for the ' * <code>management</code>' namespace. */ public class ManagementNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("servlet-context-aware-mbean-server", new ServletContextAwareMBeanServerDefinitionParser()); registerBeanDefinitionParser("profile-aspect", new ProfileAspectDefinitionParser()); registerBeanDefinitionParser("application-version-mbean", new WebApplicationMavenInformationDefinitionParser()); registerBeanDefinitionParser("jms-connection-factory-wrapper", new SpringManagedConnectionFactoryDefinitionParser()); registerBeanDefinitionParser("jms-caching-connection-factory", new ManagedCachingConnectionFactoryDefinitionParser()); registerBeanDefinitionParser("eh-cache-management-service", new EhCacheManagementServiceDefinitionParser()); } }
/* * Copyright 2008-2010 Xebia and the original author or 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 fr.xebia.management.config; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * {@link org.springframework.beans.factory.xml.NamespaceHandler} for the ' * <code>management</code>' namespace. */ public class ManagementNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("servlet-context-aware-mbean-server", new ServletContextAwareMBeanServerDefinitionParser()); registerBeanDefinitionParser("profile-aspect", new ProfileAspectDefinitionParser()); registerBeanDefinitionParser("application-version-mbean", new WebApplicationMavenInformationDefinitionParser()); registerBeanDefinitionParser("jms-connection-factory-wrapper", new SpringManagedConnectionFactoryDefinitionParser()); registerBeanDefinitionParser("eh-cache-management-service", new EhCacheManagementServiceDefinitionParser()); } }
Configure webpack to spit `scripts.js` into the "example_site". This is a temporary solution to make the dev experience a bit cleaner. Until we figure out if / where the example-site should live / be committed, webpack will look to spit out the bundle up a director, into "example_site//public"
var webpack = require('webpack'); var development = process.env.NODE_ENV !== "production"; var path = require('path'); var PATHS = { BUILD: path.join(__dirname, '..', 'example_site/public'), APP: __dirname + '/src' } module.exports = { context: __dirname, devtool: development ? "inline-sourcemap" : null, entry: PATHS.APP + "/script.jsx", output: { path: PATHS.BUILD, filename: "scripts.js" }, module : { loaders : [ { test : /\.jsx?/, include : PATHS.APP, loader : 'babel' } ] }, plugins: development ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
var webpack = require('webpack'); var development = process.env.NODE_ENV !== "production"; var PATHS = { BUILD: __dirname + '/dist', APP: __dirname + '/src' } module.exports = { context: __dirname, devtool: development ? "inline-sourcemap" : null, entry: PATHS.APP + "/script.jsx", output: { path: PATHS.BUILD, filename: "scripts.js" }, module : { loaders : [ { test : /\.jsx?/, include : PATHS.APP, loader : 'babel' } ] }, plugins: development ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), ], };
Add command-line support to HTML-to-JSON script The code is very common between the script and the test runner, which obviates the need to do a bit of refactoring. That will have the advantage of removing the JSDOM dependency from the test-runner and code consumers.
#!/usr/bin/env node 'use strict' function convert(win, htmlRoot, jsonRoot) { if (!jsonRoot) jsonRoot = [] for (let i = 0; i < htmlRoot.childNodes.length; i++) { const node = htmlRoot.childNodes[i] if (node.nodeType === win.Node.ELEMENT_NODE) { const jsonElement = { element: node.tagName.toLowerCase(), contains: convert(win, node, null) } if (node.attributes.length > 0) { jsonElement.attributes = {} for (const attr of node.attributes) { jsonElement.attributes[attr.name] = attr.value } } jsonRoot.push(jsonElement) } else if (node.nodeType === win.Node.TEXT_NODE) { const content = node.nodeValue if (content.length > 0) { jsonRoot.push({ text: content }) } } } return jsonRoot } if (require.main === module) { // TODO DRY wrt test runner const fs = require('fs') const jsdom = require('jsdom') const { JSDOM } = jsdom const html = fs.readFileSync(process.argv[2], 'utf-8') .replace(/\s*\n\s*/gm, '') const doc = new JSDOM(html).window.document const res = convert( doc.defaultView, doc.body, null) console.log(JSON.stringify(res, null, 2)) } else { module.exports = convert }
#!/usr/bin/env node 'use strict' function convert(win, htmlRoot, jsonRoot) { if (!jsonRoot) jsonRoot = [] for (let i = 0; i < htmlRoot.childNodes.length; i++) { const node = htmlRoot.childNodes[i] if (node.nodeType === win.Node.ELEMENT_NODE) { const jsonElement = { element: node.tagName.toLowerCase(), contains: convert(win, node, null) } if (node.attributes.length > 0) { jsonElement.attributes = {} for (const attr of node.attributes) { jsonElement.attributes[attr.name] = attr.value } } jsonRoot.push(jsonElement) } else if (node.nodeType === win.Node.TEXT_NODE) { const content = node.nodeValue if (content.length > 0) { jsonRoot.push({ text: content }) } } } return jsonRoot } if (require.main === module) { // TODO loaded from commandline } else { module.exports = convert }
Improve how the active link is checked
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = request.path.find(path) == 0 if active: return css_class return ''
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = path in request.path if active: return css_class return ''
Revert "Fix bbl up for AWS" This reverts commit 94599faddf4921e2ad53ffe47755b4b89ebd3a41. [#139857703] Signed-off-by: Christian Ang <15ae83feccf4d84083a62aba1cdf46bd8ce2e33b@pivotal.io>
package ec2 import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AvailabilityZoneRetriever struct { ec2ClientProvider ec2ClientProvider } func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever { return AvailabilityZoneRetriever{ ec2ClientProvider: ec2ClientProvider, } } func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String(region)}, }}, }) if err != nil { return []string{}, err } azList := []string{} for _, az := range output.AvailabilityZones { if az == nil { return []string{}, errors.New("aws returned nil availability zone") } if az.ZoneName == nil { return []string{}, errors.New("aws returned availability zone with nil zone name") } azList = append(azList, *az.ZoneName) } return azList, nil }
package ec2 import ( "errors" goaws "github.com/aws/aws-sdk-go/aws" awsec2 "github.com/aws/aws-sdk-go/service/ec2" ) type AvailabilityZoneRetriever struct { ec2ClientProvider ec2ClientProvider } func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever { return AvailabilityZoneRetriever{ ec2ClientProvider: ec2ClientProvider, } } func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) { output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{ Filters: []*awsec2.Filter{{ Name: goaws.String("region-name"), Values: []*string{goaws.String(region)}, }}, }) if err != nil { return []string{}, err } azList := []string{} for _, az := range output.AvailabilityZones { if az == nil { return []string{}, errors.New("aws returned nil availability zone") } if az.ZoneName == nil { return []string{}, errors.New("aws returned availability zone with nil zone name") } if *az.ZoneName != "us-east-1d" { azList = append(azList, *az.ZoneName) } } return azList, nil }
[entries] Normalize return value format for all objects to [key, value] entries Meaning, an object of the following structure: { a: 1, b: 2 } Would be returned as [['a', 1], ['b', 2]] Also, for numbers, return an array of numbers instead of strings.
/** * Try to make loopable any kind of javascript primitive * @param {array|number|string|object|Map|Set} collection - hopefully something that we can loop * @returns {Array} it will return always an array */ export default function looppa(collection) { // handle falsy values if (!collection) { return []; } // handle objects with an 'entries' function // such as: Arrays, Maps, Sets, NodeLists... if (typeof collection.entries === 'function') { return [...collection.entries()]; } // handle numbers and strings switch (typeof collection) { case 'number': return Array.from({ length: collection }, (v, key) => key); case 'string': return collection.split(''); default: // Default for all other object types, booleans and symbols return Object .keys(collection) .map((key) => { return [key, collection[key]]; }); } }
/** * Try to make loopable any kind of javascript primitive * @param {array|number|string|object|Map|Set} collection - hopefully something that we can loop * @returns {Array} it will return always an array */ export default function looppa(collection) { // handle falsy values if (!collection) { return []; } // don't touch arrays if (Array.isArray(collection)) { return collection; } // handle numbers and strings switch (typeof collection) { case 'number': return Object.keys(Array.from(Array(collection))); case 'string': return collection.split(''); default: //noop } // get the object entries if (Object.prototype.toString.call(collection) === '[object Object]') { return Object .keys(collection) .reduce(function(acc, key) { acc.push([key, collection[key]]); return acc; }, []); } // loop Map and Set return Array.from(collection); }
Allow threshold for IRV elections to be configurable.
import _ from 'lodash'; import {countFirstPrefs} from './utils'; function irv (election, config) { var curBallots, curCandidates, voteCount, firstPrefs, ratios, winner, loser; config = _.defaults(config, { threshold: 0.5 }); curBallots = election.ballots; curCandidates = election.candidates; while (true) { // jshint loopfunc:true voteCount = _.sumBy(curBallots, 'count'); firstPrefs = countFirstPrefs(curBallots, curCandidates); ratios = _.mapValues(firstPrefs, votes => votes / voteCount); winner = _.findKey(ratios, function (x) {return x > config.threshold; }); if (!!winner) return winner; loser = _.map(_.orderBy(_.toPairs(firstPrefs), x => x[1], ['asc']), x => x[0])[0]; curBallots = _.compact(_.map(curBallots, function (ballot) { return ballot.eliminate(loser); })); curCandidates = _.without(curCandidates, loser); } } export default irv;
import _ from 'lodash'; import {countFirstPrefs} from './utils'; function irv (election) { var curBallots, curCandidates, voteCount, firstPrefs, ratios, winner, loser; curBallots = election.ballots; curCandidates = election.candidates; while (true) { // jshint loopfunc:true voteCount = _.sumBy(curBallots, 'count'); firstPrefs = countFirstPrefs(curBallots, curCandidates); ratios = _.mapValues(firstPrefs, votes => votes / voteCount); winner = _.findKey(ratios, function (x) {return x > 0.5; }); if (!!winner) return winner; loser = _.map(_.orderBy(_.toPairs(firstPrefs), x => x[1], ['asc']), x => x[0])[0]; curBallots = _.compact(_.map(curBallots, function (ballot) { return ballot.eliminate(loser); })); curCandidates = _.without(curCandidates, loser); } } export default irv;
Make the verbose name for weight entries more user friendly
# -*- coding: utf-8 -*- # This file is part of Workout Manager. # # Workout Manager 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. # # Workout Manager 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(verbose_name = _('Date')) weight = models.FloatField(verbose_name = _('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: # Order by creation_date, ascending (oldest last), better for diagram ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
# -*- coding: utf-8 -*- # This file is part of Workout Manager. # # Workout Manager 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. # # Workout Manager 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: # Order by creation_date, ascending (oldest last), better for diagram ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
Add a second trivial streaming test to make sure our re-useing the spark context is ok
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # """Simple streaming test""" from sparktestingbase.streamingtestcase import StreamingTestCase import unittest2 class SimpleStreamingTest(StreamingTestCase): """A simple test.""" @classmethod def tokenize(cls, f): return f.flatMap(lambda line: line.split(" ")) @classmethod def noop(cls, f): return f.map(lambda x: x) def test_simple_transformation(self): input = [["hi"], ["hi holden"], ["bye"]] expected = [["hi"], ["hi", "holden"], ["bye"]] self.run_func(input, SimpleStreamingTest.tokenize, expected) def test_noop_transformation(self): input = [["hi"], ["hi holden"], ["bye"]] self.run_func(input, SimpleStreamingTest.noop, input) if __name__ == "__main__": unittest2.main()
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # """Simple streaming test""" from sparktestingbase.streamingtestcase import StreamingTestCase import unittest2 class SimpleStreamingTest(StreamingTestCase): """A simple test.""" @classmethod def tokenize(cls, f): return f.flatMap(lambda line: line.split(" ")) def test_simple_transformation(self): input = [["hi"], ["hi holden"], ["bye"]] expected = [["hi"], ["hi", "holden"], ["bye"]] self.run_func(input, SimpleStreamingTest.tokenize, expected) if __name__ == "__main__": unittest2.main()
Fix - change loacl counters value after updateCounter
<?php /** * Created by PhpStorm. * User: titan * Date: 02.03.17 * Time: 21:16 */ namespace titanproger\redis_models; class TRedisModelHash extends TRedisModelBase { public function updateCounters($counters) { $key_name = $this->getRedisKeyName(); foreach($counters as $name => $value) { static::getRedisDb()->cmdHashFieldIncrement($key_name, $name , $value ); //duplicates \yii\db\BaseActiveRecord::updateCounters from here if (!isset($this->_attributes[$name])) $this->_attributes[$name] = $value; else $this->_attributes[$name] += $value; $this->_oldAttributes[$name] = $this->_attributes[$name]; } } protected function saveToKey($key_name) { $result = static::getRedisDb()->cmdHashSet( $key_name , $this->getAttributes(), $this->expire_time ); return $result != null; } protected function loadFromKey($key_name) { $this->setAttributes( $data = static::getRedisDb()->cmdHashGet($key_name) , false); return $data != null; } }
<?php /** * Created by PhpStorm. * User: titan * Date: 02.03.17 * Time: 21:16 */ namespace titanproger\redis_models; class TRedisModelHash extends TRedisModelBase { public function updateCounters($counters) { $key_name = $this->getRedisKeyName(); foreach($counters as $field => $delta) { static::getRedisDb()->cmdHashFieldIncrement($key_name, $field , $delta ); } } protected function saveToKey($key_name) { $result = static::getRedisDb()->cmdHashSet( $key_name , $this->getAttributes(), $this->expire_time ); return $result != null; } protected function loadFromKey($key_name) { $this->setAttributes( $data = static::getRedisDb()->cmdHashGet($key_name) , false); return $data != null; } }
Remove is_string because it exist in RF 2.9
# Copyright 2008-2011 Nokia Networks # Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors # Copyright 2016- Robot Framework Foundation # # 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. # Originally based on Robot Framework 3.0.2 robot.utils.robottypes # Can be removed when library minimum required Robot Framework version is # greater than 3.0.2. Then Robot Framework is_truthy should also support # string NONE as Python False. from robot.utils import is_string def is_truthy(item): if is_string(item): return item.upper() not in ('FALSE', 'NO', '', 'NONE') return bool(item) def is_falsy(item): return not is_truthy(item) def is_noney(item): return item is None or is_string(item) and item.upper() == 'NONE'
# Copyright 2008-2011 Nokia Networks # Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors # Copyright 2016- Robot Framework Foundation # # 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. # Originally based on Robot Framework 3.0.2 robot.utils.robottypes # Can be removed when library minimum required Robot Framework version is # greater than 3.0.2. Then Robot Framework is_truthy should also support # string NONE as Python False. import sys if sys.version_info[0] == 2: def is_string(item): return isinstance(item, (str, unicode)) else: from robot.utils import is_string def is_truthy(item): if is_string(item): return item.upper() not in ('FALSE', 'NO', '', 'NONE') return bool(item) def is_falsy(item): return not is_truthy(item) def is_noney(item): return item is None or is_string(item) and item.upper() == 'NONE'
Halt appropriately on server error start. Show the error and return a correct non-successful exit code.
package main // import "github.com/CenturyLinkLabs/imagelayers" import ( "flag" "fmt" "log" "net/http" "os" "github.com/CenturyLinkLabs/imagelayers/api" "github.com/CenturyLinkLabs/imagelayers/server" "github.com/gorilla/mux" ) type layerServer struct { } func NewServer() *layerServer { return new(layerServer) } func (s *layerServer) Start(port int) error { router := s.createRouter() log.Printf("Server starting on port %d", port) portString := fmt.Sprintf(":%d", port) return http.ListenAndServe(portString, router) } func (s *layerServer) createRouter() server.Router { registry := api.NewRemoteRegistry() router := server.Router{mux.NewRouter()} registry.Routes("/registry", &router) return router } func main() { port := flag.Int("p", 8888, "port on which the server will run") flag.Parse() s := NewServer() if err := s.Start(*port); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } }
package main // import "github.com/CenturyLinkLabs/imagelayers" import ( "flag" "fmt" "log" "net/http" "github.com/CenturyLinkLabs/imagelayers/api" "github.com/CenturyLinkLabs/imagelayers/server" "github.com/gorilla/mux" ) type layerServer struct { } func NewServer() *layerServer { return new(layerServer) } func (s *layerServer) Start(port int) { router := s.createRouter() log.Printf("Server running on port %d", port) portString := fmt.Sprintf(":%d", port) http.ListenAndServe(portString, router) } func (s *layerServer) createRouter() server.Router { registry := api.NewRemoteRegistry() router := server.Router{mux.NewRouter()} registry.Routes("/registry", &router) return router } func main() { port := flag.Int("p", 8888, "port on which the server will run") flag.Parse() s := NewServer() s.Start(*port) }
Fix bug in Condorcet counting that threw off pair counts. Previous version failed to properly account for ballots that did not include _all_ candidates. This throws the count off substantially for elections where many voters do not return total orders.
import _ from 'lodash'; export function ballotToPairs (ballot, candidates) { var voteWeight = ballot.count || 1; var ranks = ballot.ranks; var result = Object.create(null); _.forEach(candidates, function (first) { result[first] = Object.create(null); _.forEach(candidates, function (second) { if (ranks[first] < ranks[second] || !_.has(ranks, second)) { result[first][second] = voteWeight; } else { result[first][second] = 0; } }); }); return result; } export function ballotArrayToPairs (ballots, candidates) { var result = Object.create(null); _.forEach(candidates, function (first) { result[first] = Object.create(null); _.forEach(candidates, function (second) { result[first][second] = 0; }); }); var pairs = _.map(ballots, _.partial(ballotToPairs, _, candidates)); _.forEach(pairs, function (pairMap) { _.forEach(candidates, function (first) { _.forEach(candidates, function (second) { result[first][second] += pairMap[first][second]; }); }); }); return result; }
import _ from 'lodash'; export function ballotToPairs (ballot, candidates) { var voteWeight = ballot.count || 1; var ranks = ballot.ranks; var result = Object.create(null); _.forEach(candidates, function (first) { result[first] = Object.create(null); _.forEach(candidates, function (second) { if (ranks[first] < ranks[second]) { result[first][second] = voteWeight; } else { result[first][second] = 0; } }); }); return result; } export function ballotArrayToPairs (ballots, candidates) { var result = Object.create(null); _.forEach(candidates, function (first) { result[first] = Object.create(null); _.forEach(candidates, function (second) { result[first][second] = 0; }); }); var pairs = _.map(ballots, _.partial(ballotToPairs, _, candidates)); _.forEach(pairs, function (pairMap) { _.forEach(candidates, function (first) { _.forEach(candidates, function (second) { result[first][second] += pairMap[first][second]; }); }); }); return result; }
Fix to a bug in the template attribute creation
<?php App::uses('AppModel', 'Model'); /** * TemplateElementAttribute Model * */ class TemplateElementAttribute extends AppModel { public $actsAs = array('Containable'); public $belongsTo = array('TemplateElement'); public $validate = array( 'name' => array( 'valueNotEmpty' => array( 'rule' => array('valueNotEmpty'), ), ), 'description' => array( 'valueNotEmpty' => array( 'rule' => array('valueNotEmpty'), ), ), 'category' => array( 'rule' => array('comparison', '!=', 'Select Category'), 'message' => 'Please choose a category.' ), 'type' => array( 'rule' => array('comparison', '!=', 'Select Type'), 'message' => 'Please choose a type.' ), ); public function beforeValidate($options = array()) { parent::beforeValidate(); } }
<?php App::uses('AppModel', 'Model'); /** * TemplateElementAttribute Model * */ class TemplateElementAttribute extends AppModel { public $actsAs = array('Containable'); public $belongsTo = array('TemplateElement'); public $validate = array( 'name' => array( 'valueNotEmpty' => array( 'rule' => array('valueNotEmpty'), ), ), 'description' => array( 'valueNotEmpty' => array( 'rule' => array('valueNotEmpty'), ), 'message' => 'Please enter a Description', ), 'category' => array( 'rule' => array('comparison', '!=', 'Select Category'), 'message' => 'Please choose a category.' ), 'type' => array( 'rule' => array('comparison', '!=', 'Select Type'), 'message' => 'Please choose a type.' ), ); public function beforeValidate($options = array()) { parent::beforeValidate(); } }
Fix verion-check to look in right place for React.js
'use strict'; var grunt = require('grunt'); // Check that the version we're exporting is the same one we expect in the // package. This is not an ideal way to do this, but makes sure that we keep // them in sync. var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/; module.exports = function() { var reactVersion = reactVersionExp.exec( grunt.file.read('./src/browser/ui/React.js') )[1]; var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version; var reactToolsVersion = grunt.config.data.pkg.version; if (reactVersion !== reactToolsVersion) { grunt.log.error( 'React version does not match react-tools version. Expected %s, saw %s', reactToolsVersion, reactVersion ); return false; } if (npmReactVersion !== reactToolsVersion) { grunt.log.error( 'npm-react version does not match react-tools veersion. Expected %s, saw %s', reactToolsVersion, npmReactVersion ); return false; } };
'use strict'; var grunt = require('grunt'); // Check that the version we're exporting is the same one we expect in the // package. This is not an ideal way to do this, but makes sure that we keep // them in sync. var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/; module.exports = function() { var reactVersion = reactVersionExp.exec( grunt.file.read('./src/browser/React.js') )[1]; var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version; var reactToolsVersion = grunt.config.data.pkg.version; if (reactVersion !== reactToolsVersion) { grunt.log.error( 'React version does not match react-tools version. Expected %s, saw %s', reactToolsVersion, reactVersion ); return false; } if (npmReactVersion !== reactToolsVersion) { grunt.log.error( 'npm-react version does not match react-tools veersion. Expected %s, saw %s', reactToolsVersion, npmReactVersion ); return false; } };
Add test to controller factory when not found controller.
<?php namespace Ouzo; use Ouzo\Routing\RouteRule; use Ouzo\Tests\CatchException; class SimpleTestController extends Controller { } class ControllerFactoryTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function shouldResolveAction() { //given $routeRule = new RouteRule('GET', '/simple_test/action1', 'simple_test#action1', false); $factory = new ControllerFactory('\\Ouzo\\'); $config = Config::getValue('global'); $_SERVER['REQUEST_URI'] = "{$config['prefix_system']}/simple_test/action1"; //when $currentController = $factory->createController($routeRule); //then $this->assertEquals('action1', $currentController->currentAction); } /** * @test */ public function shouldThrowExceptionWhenControllerNotFound() { //given $routeRule = new RouteRule('GET', '/simple_test/action', 'not_exists#action', false); $factory = new ControllerFactory('\\Ouzo\\'); //when CatchException::when($factory)->createController($routeRule); //then CatchException::assertThat()->isInstanceOf('\Ouzo\FrontControllerException'); } }
<?php namespace Ouzo; use Ouzo\Routing\RouteRule; class SimpleTestController extends Controller { } class ControllerFactoryTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function shouldResolveAction() { //given $routeRule = new RouteRule('GET', '/simple_test/action1', 'simple_test#action1', false); $factory = new ControllerFactory('\\Ouzo\\'); $config = Config::getValue('global'); $_SERVER['REQUEST_URI'] = "{$config['prefix_system']}/simple_test/action1"; //when $currentController = $factory->createController($routeRule); //then $this->assertEquals('action1', $currentController->currentAction); } }
Add 2.5.0 to extra requirements.
import os from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open("README.rst") as f: long_desc = f.read() setup( name="custodian", packages=find_packages(), version="0.1.0a", install_requires=[], extras_require={"vasp": ["pymatgen>=2.5.0"]}, package_data={}, author="Shyue Ping Ong", author_email="shyuep@gmail.com", maintainer="Shyue Ping Ong", url="https://github.com/materialsproject/custodian", license="MIT", description="A simple JIT job management framework in Python.", long_description=long_desc, keywords=["jit", "just-in-time", "job", "management", "vasp"], classifiers=[ "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Information Analysis", "Topic :: Scientific/Engineering :: Physics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Software Development :: Libraries :: Python Modules" ], download_url="https://github.com/materialsproject/custodian/archive/master.zip", scripts=[os.path.join("scripts", f) for f in os.listdir("scripts")] )
import os from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open("README.rst") as f: long_desc = f.read() setup( name="custodian", packages=find_packages(), version="0.1.0a", install_requires=[], extras_require={"vasp": ["pymatgen>=2.4.3"]}, package_data={}, author="Shyue Ping Ong", author_email="shyuep@gmail.com", maintainer="Shyue Ping Ong", url="https://github.com/materialsproject/custodian", license="MIT", description="A simple JIT job management framework in Python.", long_description=long_desc, keywords=["jit", "just-in-time", "job", "management", "vasp"], classifiers=[ "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Information Analysis", "Topic :: Scientific/Engineering :: Physics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Software Development :: Libraries :: Python Modules" ], download_url="https://github.com/materialsproject/custodian/archive/master.zip", scripts=[os.path.join("scripts", f) for f in os.listdir("scripts")] )
Fix minor typo in doc string in test support mopule Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI. This uses the netconfig_ module from my ``micropython-stm-lib``. To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter, add the following to ``mpconfigboard.mk`` in your board definition:: MICROPY_PY_WIZNET5K = 5500 MICROPY_PY_LWIP ?= 1 MICROPY_PY_USSL ?= 1 MICROPY_SSL_MBEDTLS ?= 1 and re-compile & upload the firmware:: cd mpy-cross make cd ../ports/stm32 make submodules make BOARD=MYBOARD # do whatever it takes connect your board in DFU mode make BOARD=MYBOARD deploy .. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig """ from netconfig import connect nic = connect('paddyland-wiznet.json', True) print(nic.ifconfig())
"""Sets up network on MicroPython board with Wiznet 5500 ethernet adapter attached via SPI. This uses the netconfig_ module from my ``micropythonstm-lib``. To compile the MicroPython ``stm32`` port with support for the Wiznet 5500 adapter, add the following to ``mpconfigboard.mk`` in your board definition:: MICROPY_PY_WIZNET5K = 5500 MICROPY_PY_LWIP ?= 1 MICROPY_PY_USSL ?= 1 MICROPY_SSL_MBEDTLS ?= 1 and re-compile & upload the firmware:: cd mpy-cross make cd ../ports/stm32 make submodules make BOARD=MYBOARD # do whatever it takes connect your board in DFU mode make BOARD=MYBOARD deploy .. _netconfig: https://github.com/SpotlightKid/micropython-stm-lib/tree/master/netconfig """ from netconfig import connect nic = connect('paddyland-wiznet.json', True) print(nic.ifconfig())
Use counter for JVM Info
package io.quarkus.micrometer.runtime.binder; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; public class JVMInfoBinder implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { Counter.builder("jvm_info") .description("JVM version info") .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", System.getProperty("java.vm.vendor", "unknown"), "runtime", System.getProperty("java.runtime.name", "unknown")) .register(registry) .increment(); } }
package io.quarkus.micrometer.runtime.binder; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; public class JVMInfoBinder implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { Gauge.builder("jvm_info", () -> 1L) .description("JVM version info") .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", System.getProperty("java.vm.vendor", "unknown"), "runtime", System.getProperty("java.runtime.name", "unknown")) .strongReference(true) .register(registry); } }
Revert "Temporarily disallow rule cloning (for benchmarks)" This reverts commit 15c01bdcc559e04fad09f19672e7306b3e316f2a.
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import org.metaborg.meta.lang.dynsem.interpreter.nodes.DynSemRootNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public abstract class Rule extends DynSemRootNode { private final DynSemLanguage lang; public Rule(DynSemLanguage lang, SourceSection source, FrameDescriptor fd) { super(lang, source, fd); this.lang = lang; } public Rule(DynSemLanguage lang, SourceSection source) { this(lang, source, null); } protected DynSemLanguage language() { return lang; } @Override public abstract RuleResult execute(VirtualFrame frame); @Override public boolean isCloningAllowed() { return true; } @Override protected boolean isCloneUninitializedSupported() { return true; } @Override protected abstract Rule cloneUninitialized(); public Rule makeUninitializedClone() { return cloneUninitialized(); } }
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import org.metaborg.meta.lang.dynsem.interpreter.nodes.DynSemRootNode; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public abstract class Rule extends DynSemRootNode { private final DynSemLanguage lang; public Rule(DynSemLanguage lang, SourceSection source, FrameDescriptor fd) { super(lang, source, fd); this.lang = lang; } public Rule(DynSemLanguage lang, SourceSection source) { this(lang, source, null); } protected DynSemLanguage language() { return lang; } @Override public abstract RuleResult execute(VirtualFrame frame); @Override public boolean isCloningAllowed() { return false; } @Override protected boolean isCloneUninitializedSupported() { return false; } @Override protected abstract Rule cloneUninitialized(); public Rule makeUninitializedClone() { return cloneUninitialized(); } }
Check if stack is empty before popping off a message.
package org.tigris.subversion.svnclientadapter.javahl; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.tigris.subversion.javahl.ChangePath; import org.tigris.subversion.javahl.LogMessageCallback; import org.tigris.subversion.javahl.Revision; public class JhlLogMessageCallback implements LogMessageCallback { private List messages = new ArrayList(); private Stack stack = new Stack(); public void singleMessage(ChangePath[] changedPaths, long revision, String author, long timeMicros, String message, boolean hasChildren) { if (revision == Revision.SVN_INVALID_REVNUM) { if (!stack.empty()) stack.pop(); return; } JhlLogMessage msg = new JhlLogMessage(changedPaths, revision, author, timeMicros, message, hasChildren); if (stack.empty()) { messages.add(msg); } else { JhlLogMessage current = (JhlLogMessage) stack.peek(); current.addChild(msg); } if (hasChildren) stack.push(msg); } public JhlLogMessage[] getLogMessages() { JhlLogMessage[] array = new JhlLogMessage[messages.size()]; return (JhlLogMessage[]) messages.toArray(array); } }
package org.tigris.subversion.svnclientadapter.javahl; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.tigris.subversion.javahl.ChangePath; import org.tigris.subversion.javahl.LogMessageCallback; import org.tigris.subversion.javahl.Revision; public class JhlLogMessageCallback implements LogMessageCallback { private List messages = new ArrayList(); private Stack stack = new Stack(); public void singleMessage(ChangePath[] changedPaths, long revision, String author, long timeMicros, String message, boolean hasChildren) { if (revision == Revision.SVN_INVALID_REVNUM) { stack.pop(); return; } JhlLogMessage msg = new JhlLogMessage(changedPaths, revision, author, timeMicros, message, hasChildren); if (stack.empty()) { messages.add(msg); } else { JhlLogMessage current = (JhlLogMessage) stack.peek(); current.addChild(msg); } if (hasChildren) stack.push(msg); } public JhlLogMessage[] getLogMessages() { JhlLogMessage[] array = new JhlLogMessage[messages.size()]; return (JhlLogMessage[]) messages.toArray(array); } }
Add --tsconfig CLI option to specify a TypeScript config file
#!/usr/bin/env node 'use strict'; const dependencyTree = require('../'); const program = require('commander'); program .version(require('../package.json').version) .usage('[options] <filename>') .option('-d, --directory <path>', 'location of files of supported filetypes') .option('-c, --require-config <path>', 'path to a requirejs config') .option('-w, --webpack-config <path>', 'path to a webpack config') .option('-t, --ts-config <path>', 'path to a typescript config') .option('--list-form', 'output the list form of the tree (one element per line)') .parse(process.argv); let tree; const options = { filename: program.args[0], root: program.directory, config: program.requireConfig, webpackConfig: program.webpackConfig, tsConfig: program.tsConfig }; if (program.listForm) { tree = dependencyTree.toList(options); tree.forEach(function(node) { console.log(node); }); } else { tree = dependencyTree(options); console.log(JSON.stringify(tree)); }
#!/usr/bin/env node 'use strict'; const dependencyTree = require('../'); const program = require('commander'); program .version(require('../package.json').version) .usage('[options] <filename>') .option('-d, --directory <path>', 'location of files of supported filetypes') .option('-c, --require-config <path>', 'path to a requirejs config') .option('-w, --webpack-config <path>', 'path to a webpack config') .option('--list-form', 'output the list form of the tree (one element per line)') .parse(process.argv); let tree; const options = { filename: program.args[0], root: program.directory, config: program.requireConfig, webpackConfig: program.webpackConfig }; if (program.listForm) { tree = dependencyTree.toList(options); tree.forEach(function(node) { console.log(node); }); } else { tree = dependencyTree(options); console.log(JSON.stringify(tree)); }
Fix estimator loop, consider rest plugins as well.
import logging from flexget.plugin import get_plugins_by_group, register_plugin log = logging.getLogger('est_released') class EstimateRelease(object): """ Front-end for estimator plugins that estimate release times for various things (series, movies). """ def estimate(self, entry): """ Estimate release schedule for Entry :param entry: :return: estimated date of released for the entry, None if it can't figure it out """ log.info(entry['title']) estimators = get_plugins_by_group('estimate_release') for estimator in estimators: estimate = estimator.instance.estimate(entry) # return first successful estimation if estimate is not None: return estimate register_plugin(EstimateRelease, 'estimate_release', api_ver=2)
import logging from flexget.plugin import get_plugins_by_group, register_plugin log = logging.getLogger('est_released') class EstimateRelease(object): """ Front-end for estimator plugins that estimate release times for various things (series, movies). """ def estimate(self, entry): """ Estimate release schedule for Entry :param entry: :return: estimated date of released for the entry, None if it can't figure it out """ log.info(entry['title']) estimators = get_plugins_by_group('estimate_release') for estimator in estimators: return estimator.instance.estimate(entry) register_plugin(EstimateRelease, 'estimate_release', api_ver=2)
Fix missing label on button Fix missing label on button
var animation = require('alloy/animation'); function IndexOpen(e) { $.logo.init({ image: '/images/alloy.png', width: 216, height: 200, opacity: 0.1 }); $.buttongrid.relayout(e); } var red = '#900A05'; var brightred = '#B00C07'; var black = '#000000'; var gray = '#888888'; $.buttongrid.init({ buttons: [ { id: 'Cloudy', title: 'Cloudy', backgroundColor: black, backgroundSelectedColor: gray }, { id: 'Drizzle', title: 'Drizzle' }, { id: 'Haze', title: 'Haze' }, { id: 'MostlyCloudy', title: 'Mostly Cloudy' }, { id: 'SlightDrizzle', title: 'Slight Drizzle' }, { id: 'Snow', title: 'Snow' }, { id: 'Sunny', title: 'Sunny' }, { id: 'Thunderstorms', title: 'Thunderstorms', click: function (e) { alert('Thunder!'); } } ], buttonWidth: Alloy.isTablet ? 200: 100, buttonHeight: Alloy.isTablet ? 200 : 100, backgroundColor: red, backgroundSelectedColor: brightred, duration: 1000 }); $.index.open();
var animation = require("alloy/animation"); function IndexOpen(e) { $.logo.init({ image: '/images/alloy.png', width: 216, height: 200, opacity: 0.1 }); $.buttongrid.relayout(e); } var red = "#900A05"; var brightred = "#B00C07"; var black = "#000000"; var gray = '#888888'; $.buttongrid.init({ buttons: [ { id: 'Cloudy', title: "Cloudy", backgroundColor: black, backgroundSelectedColor: gray }, { id: 'Drizzle', title: "Drizzle" }, { id: 'Haze', title: 'Haze' }, { id: 'MostlyCloudy', title: "Mostly Cloudy" }, { id: 'SlightDrizzle' }, { id: 'Snow', title: 'Snow' }, { id: 'Sunny', title: 'Sunny' }, { id: 'Thunderstorms', title: 'Thunderstorms', click: function (e) { alert("Thunder!"); } } ], buttonWidth: Alloy.isTablet ? 200: 100, buttonHeight: Alloy.isTablet ? 200 : 100, backgroundColor: red, backgroundSelectedColor: brightred, duration: 1000 }); $.index.open();
Grunt: Update sockjs-client path for 1.X
module.exports = function (grunt) { grunt.initConfig({ uglify: { main: { options: { preserveComments: 'some' }, files: { 'dist/ng-stomp.min.js': ['src/ng-stomp.js'], 'dist/ng-stomp.standalone.min.js': [ 'bower_components/sockjs-client/dist/sockjs.min.js', 'bower_components/stomp-websocket/lib/stomp.min.js', 'src/ng-stomp.js' ] } } }, standard: { options: { format: true }, app: { src: ['ng-stomp.js'] } } }) grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-standard') grunt.registerTask('default', ['standard', 'uglify']) }
module.exports = function (grunt) { grunt.initConfig({ uglify: { main: { options: { preserveComments: 'some' }, files: { 'dist/ng-stomp.min.js': ['src/ng-stomp.js'], 'dist/ng-stomp.standalone.min.js': [ 'bower_components/sockjs/sockjs.min.js', 'bower_components/stomp-websocket/lib/stomp.min.js', 'src/ng-stomp.js' ] } } }, standard: { options: { format: true }, app: { src: ['ng-stomp.js'] } } }) grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-standard') grunt.registerTask('default', ['standard', 'uglify']) }
Change senlin dashboard to not be the default dashboard Change-Id: I81d492bf8998e74f5bf53b0226047a070069b060 Closes-Bug: #1754183
# 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. from senlin_dashboard import exceptions DASHBOARD = 'cluster' ADD_INSTALLED_APPS = [ 'senlin_dashboard', 'senlin_dashboard.cluster' ] DEFAULT = False AUTO_DISCOVER_STATIC_FILES = True ADD_ANGULAR_MODULES = ['horizon.cluster'] ADD_SCSS_FILES = [ 'app/core/cluster.scss' ] ADD_EXCEPTIONS = { 'recoverable': exceptions.RECOVERABLE, 'not_found': exceptions.NOT_FOUND, 'unauthorized': exceptions.UNAUTHORIZED, }
# 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. from senlin_dashboard import exceptions DASHBOARD = 'cluster' ADD_INSTALLED_APPS = [ 'senlin_dashboard', 'senlin_dashboard.cluster' ] DEFAULT = True AUTO_DISCOVER_STATIC_FILES = True ADD_ANGULAR_MODULES = ['horizon.cluster'] ADD_SCSS_FILES = [ 'app/core/cluster.scss' ] ADD_EXCEPTIONS = { 'recoverable': exceptions.RECOVERABLE, 'not_found': exceptions.NOT_FOUND, 'unauthorized': exceptions.UNAUTHORIZED, }
Fix GET params bug with BaseService.request
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) if r.status_code != 200: raise APIError(r.status_code) return r.json()
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if method == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) if r.status_code != 200: raise APIError(r.status_code) return r.json()
Hide modules from variables traced by %%snoop
import ast from snoop import snoop from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): filename = self.shell.compile.cache(cell) code = self.shell.compile(cell, filename, 'exec') tracer = snoop() tracer.variable_whitelist = set() for node in ast.walk(ast.parse(cell)): if isinstance(node, ast.Name): name = node.id if isinstance( self.shell.user_global_ns.get(name), type(ast), ): # hide modules continue tracer.variable_whitelist.add(name) tracer.target_codes.add(code) with tracer: self.shell.ex(code)
import ast from snoop import snoop from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): filename = self.shell.compile.cache(cell) code = self.shell.compile(cell, filename, 'exec') tracer = snoop() tracer.variable_whitelist = set() for node in ast.walk(ast.parse(cell)): if isinstance(node, ast.Name): tracer.variable_whitelist.add(node.id) tracer.target_codes.add(code) with tracer: self.shell.ex(code)
Add header comment to sample resource config
'use strict'; // A sample analytics service that uses metering formulas // Formulas are deprecated, we're now using meter, accumulate, aggregate // and rate Javascript functions instead module.exports = { resource_id: 'analytics', measures: [ { name: 'classifiers', unit: 'INSTANCE' }, { name: 'classifier_api_calls', unit: 'CALL' }, { name: 'training_event_api_calls', unit: 'CALL' }], metrics: [ { name: 'classifier_instances', unit: 'INSTANCE', formula: 'AVG({classifier})' }, { name: 'classifier_api_calls', unit: 'CALL', formula: 'SUM({classifier_api.calls})' }, { name: 'training_event_api_calls', unit: 'CALL', formula: 'SUM({training_event_api_calls})' }] };
'use strict'; // Formulas are deprecated, we're now using meter, accumulate, aggregate // and rate Javascript functions instead module.exports = { resource_id: 'analytics', measures: [ { name: 'classifiers', unit: 'INSTANCE' }, { name: 'classifier_api_calls', unit: 'CALL' }, { name: 'training_event_api_calls', unit: 'CALL' }], metrics: [ { name: 'classifier_instances', unit: 'INSTANCE', formula: 'AVG({classifier})' }, { name: 'classifier_api_calls', unit: 'CALL', formula: 'SUM({classifier_api.calls})' }, { name: 'training_event_api_calls', unit: 'CALL', formula: 'SUM({training_event_api_calls})' }] };
Change server.socket_host to allow acces over the network
import os, os.path import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return open('test-carte.html') if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './public' } } webapp = StringGenerator() cherrypy.config.update( {'server.socket_host': '0.0.0.0'} ) cherrypy.quickstart(webapp, '/', conf)
import os, os.path import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return open('test-carte.html') if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './public' } } webapp = StringGenerator() cherrypy.quickstart(webapp, '/', conf)
Create redirect when a product changes
<? include '../scat.php'; $id= (int)$_REQUEST['id']; $name= $_REQUEST['name']; $slug= $_REQUEST['slug']; try { $product= Model::factory('Product')->find_one($id); $old_slug= ""; if (($product->slug && $_REQUEST['slug'] != $product->slug) || ($product->department_id && $_REQUEST['department_id'] != $product->department_id)) { $old_slug= $product->full_slug(); } foreach ($_REQUEST as $k => $v) { if (in_array($k, array('department_id', 'brand_id', 'name', 'description', 'slug', 'image', 'variation_style', 'active'))) { $product->set($k, $v); } } $product->save(); // Save redirect information if ($old_slug) { $new_slug= $product->full_slug(); error_log("Redirecting $old_slug to $new_slug"); $redir= Model::factory('Redirect')->create(); $redir->source= $old_slug; $redir->dest= $new_slug; $redir->save(); } } catch (\PDOException $e) { die_jsonp($e->getMessage()); } echo jsonp($product);
<? include '../scat.php'; $id= (int)$_REQUEST['id']; $name= $_REQUEST['name']; $slug= $_REQUEST['slug']; try { $product= Model::factory('Product')->find_one($id); $old_slug= ""; if (($product->slug && $_REQUEST['slug'] != $product->slug) || ($product->department_id && $_REQUEST['department_id'] != $product->department_id)) { // XXX handle rename $old_slug= ''; } foreach ($_REQUEST as $k => $v) { if (in_array($k, array('department_id', 'brand_id', 'name', 'description', 'slug', 'image', 'variation_style', 'active'))) { $product->set($k, $v); } } $product->save(); // XXX Save redirect information if ($old_slug) { } } catch (\PDOException $e) { die_jsonp($e->getMessage()); } echo jsonp($product);
Fix bug related to creating the log directory
import threading import subprocess import os class TestExecutor(threading.Thread): """ The general thread to perform the tests executions """ def __init__(self, run_id, test_name, queue): super().__init__() self.run_id = run_id self.test_name = test_name self.queue = queue # __init __() def run(self): """ Execute the command to perform the test execution. The return code is enqueued so the scheduler can determine if the run has completed """ filename = "runs/static/runs/logs/{}.txt".format(self.run_id) os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f: CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format( self.test_name) return_code = subprocess.call(CMD, stdout=f, shell=True) self.queue.put((self.run_id, return_code)) # run()
import threading import subprocess class TestExecutor(threading.Thread): """ The general thread to perform the tests executions """ def __init__(self, run_id, test_name, queue): super().__init__() self.run_id = run_id self.test_name = test_name self.queue = queue # __init __() def run(self): """ Execute the command to perform the test execution. The return code is enqueued so the scheduler can determine if the run has completed """ with open( "runs/static/runs/autotests/runs/{}.txt".format( self.run_id), "w") as f: CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format( self.test_name) return_code = subprocess.call(CMD, stdout=f, shell=True) self.queue.put((self.run_id, return_code)) # run()