text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove the use of the BSONByteBuffer
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * 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.jongo.bson; import com.mongodb.DBObject; import com.mongodb.LazyDBObject; import org.bson.LazyBSONCallback; import java.nio.ByteBuffer; import java.nio.ByteOrder; class LazyBsonDocument implements BsonDocument { private final byte[] bytes; LazyBsonDocument(byte[] bytes) { this.bytes = bytes; } public int getSize() { final ByteBuffer buffer = ByteBuffer.wrap(bytes); buffer.order( ByteOrder.LITTLE_ENDIAN ); return buffer.getInt(0); } public byte[] toByteArray() { return bytes; } public DBObject toDBObject() { return new LazyDBObject(bytes, new LazyBSONCallback()); } @Override public String toString() { return toDBObject().toString(); } }
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * 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.jongo.bson; import com.mongodb.DBObject; import com.mongodb.LazyDBObject; import org.bson.LazyBSONCallback; import org.bson.io.BSONByteBuffer; class LazyBsonDocument implements BsonDocument { private final byte[] bytes; LazyBsonDocument(byte[] bytes) { this.bytes = bytes; } public int getSize() { return BSONByteBuffer.wrap(bytes).getInt(0); } public byte[] toByteArray() { return bytes; } public DBObject toDBObject() { return new LazyDBObject(bytes, new LazyBSONCallback()); } @Override public String toString() { return toDBObject().toString(); } }
Update babel-plugin-react-server to use new react-server-module-tagger interface
import loggerSpec from 'react-server-module-tagger'; import path from 'path'; module.exports = function() { return { visitor: { Identifier(p, state) { const {node} = p; const {name} = node; const trim = state.opts.trim; const parent = path.resolve(path.join(process.cwd(), '..')) + path.sep; const filePath = this.file.opts.filename.replace(parent, ''); //TODO: Support labels const moduleTag = loggerSpec({ filePath, trim }); let tokens; if (state.opts.tokens) { tokens = new Set(state.opts.tokens); } else { tokens = new Set(["__LOGGER__", "__CHANNEL__", "__CACHE__"]); } if (tokens.has(name)) { // this strikes me as a dirty, nasty hack. I think it would be better // to parse the object as json and coerce it to an array of // ObjectProperties to construct an ObjectExpression p.node.name = moduleTag; } }, }, }; }
import loggerSpec from 'react-server-module-tagger'; import path from 'path'; module.exports = function() { return { visitor: { Identifier(p, state) { const {node} = p; const {name} = node; const config = { trim: state.opts.trim }; const parent = path.resolve(path.join(process.cwd(), '..')) + path.sep; const fp = this.file.opts.filename.replace(parent, ''); const file = { path: fp }; //TODO: Support labels const moduleTag = loggerSpec.bind({ file, config })(fp); let tokens; if (state.opts.tokens) { tokens = new Set(state.opts.tokens); } else { tokens = new Set(["__LOGGER__", "__CHANNEL__", "__CACHE__"]); } if (tokens.has(name)) { // this strikes me as a dirty, nasty hack. I think it would be better // to parse the object as json and coerce it to an array of // ObjectProperties to construct an ObjectExpression p.node.name = moduleTag; } }, }, }; }
Test deferred registry with biomes
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.BaseRegistryUtil; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.biome.BasicBiome; import net.minecraft.world.biome.Biome; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.registries.*; //@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestBiomes { //public static final Biome BASIC = new BasicBiome("basic"); public static final DeferredRegister<Biome> BLOCKS = DeferredRegister.create(ForgeRegistries.BIOMES, TestMod.MODID); public static final RegistryObject<BasicBiome> BASIC = BLOCKS.register("basic", () -> new BasicBiome("basic")); // @SubscribeEvent // public static void register(Register<Biome> event) { // BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register); // } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.util.registry.BaseRegistryUtil; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.biome.BasicBiome; import net.minecraft.world.biome.Biome; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestBiomes { public static final Biome BASIC = new BasicBiome("basic"); @SubscribeEvent public static void register(Register<Biome> event) { BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, Biome.class).forEach(event.getRegistry()::register); } }
Change GoogleUniversal to set page as well This has additional benefit that future trackEvent() calls will use the new page value as well. Also, it silences a minor warning from the Analytics Debugger.
(function(){ angular.module('angularytics').factory('AngularyticsGoogleHandler', function($log) { var service = {}; service.trackPageView = function(url) { _gaq.push(['_set', 'page', url]); _gaq.push(['_trackPageview', url]); } service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) { _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]); } return service; }).factory('AngularyticsGoogleUniversalHandler', function () { var service = {}; service.trackPageView = function (url) { ga('set', 'page', url); ga('send', 'pageView'); }; service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) { ga('send', 'event', category, action, opt_label, opt_value, {'nonInteraction': opt_noninteraction}); }; return service; }); })();
(function(){ angular.module('angularytics').factory('AngularyticsGoogleHandler', function($log) { var service = {}; service.trackPageView = function(url) { _gaq.push(['_set', 'page', url]); _gaq.push(['_trackPageview', url]); } service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) { _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]); } return service; }).factory('AngularyticsGoogleUniversalHandler', function () { var service = {}; service.trackPageView = function (url) { ga('send', 'pageView', url); }; service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) { ga('send', 'event', category, action, opt_label, opt_value, {'nonInteraction': opt_noninteraction}); }; return service; }); })();
Increment version number to 0.1.3.
# Copyright (c) 2011, SD Elements. See LICENSE.txt for details. import os from distutils.core import setup f = open(os.path.join(os.path.dirname(__file__), 'README')) readme = f.read() f.close() setup(name="django-security", description='A collection of tools to help secure a Django project.', long_description=readme, maintainer="SD Elements", maintainer_email="django-security@sdelements.com", version="0.1.3", packages=["security", "security.migrations", "security.auth_throttling"], url='https://github.com/sdelements/django-security', classifiers=[ 'Framework :: Django', 'Environment :: Web Environment', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=['django>=1.3,<1.4',], )
# Copyright (c) 2011, SD Elements. See LICENSE.txt for details. import os from distutils.core import setup f = open(os.path.join(os.path.dirname(__file__), 'README')) readme = f.read() f.close() setup(name="django-security", description='A collection of tools to help secure a Django project.', long_description=readme, maintainer="SD Elements", maintainer_email="django-security@sdelements.com", version="0.1.2", packages=["security", "security.migrations", "security.auth_throttling"], url='https://github.com/sdelements/django-security', classifiers=[ 'Framework :: Django', 'Environment :: Web Environment', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=['django>=1.3,<1.4',], )
Switch SDK from pickle mapper to mapstructure
package interfaces type SDK struct { Name string `json:"name" node:"name"` Version string `json:"version" node:"version"` ClientIP string `json:"clientIP" node:"client_ip"` Upstream Upstream `json:"upstream"` } type Upstream struct { Name string `json:"name"` URL string `json:"url"` IsNewer bool `json:"isNewer"` } func (sdk *SDK) UnmarshalRecord(nodeBlob interface{}) error { err := DecodeRecord("sdk", "sentry.interfaces.Sdk", nodeBlob, sdk) sdk.Upstream.Name = sdk.Name // TODO check original code sdk.Upstream.URL = "https://docs.sentry.io/clients/python/" // TODO remove hardcode return err } func (sdk *SDK) UnmarshalAPI(rawEvent map[string]interface{}) error { return nil }
package interfaces import ( pickle "github.com/hydrogen18/stalecucumber" "github.com/pkg/errors" ) type SDK struct { Name string `json:"name" pickle:"name"` Version string `json:"version" pickle:"version"` ClientIP string `json:"clientIP" pickle:"client_ip"` Upstream Upstream `json:"upstream" pickle:"-"` } type Upstream struct { Name string `json:"name" pickle:"-"` URL string `json:"url" pickle:"-"` IsNewer bool `json:"isNewer"` } func (sdk *SDK) UnmarshalRecord(nodeBlob interface{}) error { // TODO safe cast to map[interface{}]interface{} // TODO safe get from map using `sdk` alias key // TODO safe get from map using `sentry.interfaces.Sdk` canonical key if err := pickle.UnpackInto(&sdk).From(nodeBlob.(map[interface{}]interface{})["sdk"], nil); err != nil { return errors.Wrapf(err, "can not convert node blob to sentry.interfaces.Sdk") } sdk.Upstream.Name = sdk.Name // TODO check original code sdk.Upstream.URL = "https://docs.sentry.io/clients/python/" // TODO remove hardcode return nil } func (sdk *SDK) UnmarshalAPI(rawEvent map[string]interface{}) error { return nil }
Fix bug in PUT request
'use strict'; var env = require('./env.json'); function httpPost(req, cb) { var https = req.deps.https; console.log('env:', env); var postData = JSON.stringify({ metadata: req.data.s3Object.Metadata, sizes: req.data.sizes }); var options = { hostname: 'plaaant.com', port: 443, path: '/api/image-complete?token=' + env.PLANT_IMAGE_COMPLETE, method: 'PUT', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; console.log('About to PUT to server...'); var request = https.request(options, function(res) { console.log('response from https.request:', res); }); request.write(postData); request.end(); request.on('error', function(e) { console.error('Error in https.request:', e); }); console.log('Completed PUT to server...'); cb(null, req); } module.exports = { httpPost: httpPost };
'use strict'; var env = require('./env.json'); function httpPost(req, cb) { var https = req.deps.https; console.log('env:', env); var postData = JSON.stringify({ metadata: req.data.s3Object.Metadata, sizes: req.data.sizes }); var options = { hostname: 'plaaant.com', port: 443, path: '/api/image-complete?token=' + env.PLANT_IMAGE_COMPLETE, method: 'PUT', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; console.log('About to PUT to server...'); var request = https.request(options, function(res) { console.log('response from https.request:', res); }); request.write(postData); request.end(); req.on('error', function(e) { console.error('Error in https.request:', e); }); console.log('Completed PUT to server...'); cb(null, req); } module.exports = { httpPost: httpPost };
Add ability to get the prefix for a given namespace git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@889 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
package org.codehaus.xfire.aegis; import javax.xml.namespace.QName; /** * Writes messages to an output stream. * * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> */ public interface MessageWriter { void writeValue( Object value ); void writeValueAsInt( Integer i ); void writeValueAsDouble(Double double1); void writeValueAsLong(Long l); void writeValueAsFloat(Float f); void writeValueAsBoolean(boolean b); MessageWriter getAttributeWriter(String name); MessageWriter getAttributeWriter(String name, String namespace); MessageWriter getAttributeWriter(QName qname); MessageWriter getElementWriter(String name); MessageWriter getElementWriter(String name, String namespace); MessageWriter getElementWriter(QName qname); String getPrefixForNamespace( String namespace ); /** * Tells the MessageWriter that writing operations are completed so * it can write the end element. */ void close(); }
package org.codehaus.xfire.aegis; import javax.xml.namespace.QName; /** * Writes messages to an output stream. * * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> */ public interface MessageWriter { void writeValue( Object value ); void writeValueAsInt( Integer i ); void writeValueAsDouble(Double double1); void writeValueAsLong(Long l); void writeValueAsFloat(Float f); void writeValueAsBoolean(boolean b); MessageWriter getAttributeWriter(String name); MessageWriter getAttributeWriter(String name, String namespace); MessageWriter getAttributeWriter(QName qname); MessageWriter getElementWriter(String name); MessageWriter getElementWriter(String name, String namespace); MessageWriter getElementWriter(QName qname); /** * Tells the MessageWriter that writing operations are completed so * it can write the end element. */ void close(); }
Add function to check current status
var CommandQueue = require('./command-queue'); /** * Creates a new robot arm * @constructor * @param {object} options The options object. * @param {object|array} options.axis A list of servos to control robot arm. */ var RobotArm = function(options) { this._queue = new CommandQueue(); this.axis = options.axis; this._queue.on('data', function(fn) { console.assert(typeof fn === 'function', 'fn is not a function'); fn.call(this, function() { this._queue.next(); }.bind(this)); }.bind(this)); }; RobotArm.prototype.then = function(fn) { this._queue.push(fn); return this; }; RobotArm.prototype.play = function(options) { this._queue.play(options); return this; }; RobotArm.prototype.stop = function() { this._queue.stop(); return this; }; RobotArm.prototype.replay = function(options) { this._queue.replay(options); return this; }; RobotArm.prototype.pause = function() { this._queue.pause(); return this; }; RobotArm.prototype.reset = function() { this._queue.stop(); this._queue.clear(); return this; }; RobotArm.prototype.isRunning = function() { return this._queue.isRunning(); }; module.exports = RobotArm;
var CommandQueue = require('./command-queue'); /** * Creates a new robot arm * @constructor * @param {object} options The options object. * @param {object|array} options.axis A list of servos to control robot arm. */ var RobotArm = function(options) { this._queue = new CommandQueue(); this.axis = options.axis; this._queue.on('data', function(fn) { console.assert(typeof fn === 'function', 'fn is not a function'); fn.call(this, function() { this._queue.next(); }.bind(this)); }.bind(this)); }; RobotArm.prototype.then = function(fn) { this._queue.push(fn); return this; }; RobotArm.prototype.play = function(options) { this._queue.play(options); return this; }; RobotArm.prototype.stop = function() { this._queue.stop(); return this; }; RobotArm.prototype.replay = function(options) { this._queue.replay(options); return this; }; RobotArm.prototype.pause = function() { this._queue.pause(); return this; }; RobotArm.prototype.reset = function() { this._queue.stop(); this._queue.clear(); return this; }; module.exports = RobotArm;
Fix HTTP request forwarding bug
/* globals console */ /* eslint no-console: 0 */ import http from 'http'; import { get } from 'lodash'; import { setResponse } from 'utils'; import { config } from 'environment'; /** * Forwards an HTTP request using parameters either provided directly by an action, * or matches a provided key to pre-defined parameters in config.json. */ const forwardHTTPRequest = (action, next) => { const { key } = action; const keyIsInvalid = key && !config.httpRequests[key]; if (keyIsInvalid) { throw new Error(`Property ${key} not declared in httpRequests property of config.json`); } const body = get(config, `httpRequests[${key}].body)`, action.body); const optionsOverride = get(config, `httpRequests[${key}].options`, action.options); const payload = JSON.stringify(body); const options = { method: action.method || 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': payload ? payload.length : 0 }, ...optionsOverride }; const request = http.request(options, (response) => { response.setEncoding('utf8'); response.on('data', (chunk) => { console.log(`Response: ${chunk}`); setResponse(next, JSON.parse(chunk).status); }); }); request.on('error', ({ message }) => { console.log(`Problem with request: ${message}`); }); if (payload) { request.write(payload); } request.end(); }; export default forwardHTTPRequest;
/* globals console */ /* eslint no-console: 0 */ import http from 'http'; import { get } from 'lodash'; import { setResponse } from 'utils'; import { config } from 'environment'; /** * Forwards an HTTP request using parameters either provided directly by an action, * or matches a provided key to pre-defined parameters in config.json. */ const forwardHTTPRequest = (action, next) => { const { key, body } = action; const payload = JSON.stringify(body || config.httpRequests[key].body); const optionsOverride = get(config, `httpRequests[${key}].options`, action.options); const options = { method: action.method || 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': payload.length }, ...optionsOverride }; const request = http.request(options, (response) => { response.setEncoding('utf8'); response.on('data', (chunk) => { console.log(`Response: ${chunk}`); setResponse(next, JSON.parse(chunk).status); }); }); request.on('error', ({ message }) => { console.log(`Problem with request: ${message}`); }); if (payload) { request.write(payload); } request.end(); }; export default forwardHTTPRequest;
Add filters to the talk admin @logston is reviewing talks and wanted to see the talk duration. He also thought it would be useful to be able to filter by the duration and status of the talk.
"""Admin for talk-related models.""" from pygotham.admin.utils import model_view from pygotham.talks import models __all__ = ('CategoryModelView', 'TalkModelView', 'TalkReviewModelView') CategoryModelView = model_view( models.Category, 'Categories', 'Talks', form_columns=('name', 'slug'), ) TalkModelView = model_view( models.Talk, 'Talks', 'Talks', column_filters=('status', 'duration', 'level'), column_list=('name', 'status', 'duration', 'level', 'type', 'user'), column_searchable_list=('name',), ) TalkReviewModelView = model_view( models.Talk, 'Review', 'Talks', can_create=False, can_delete=False, column_list=('name', 'status', 'level', 'type', 'user'), column_searchable_list=('name',), edit_template='talks/review.html', )
"""Admin for talk-related models.""" from pygotham.admin.utils import model_view from pygotham.talks import models __all__ = ('CategoryModelView', 'TalkModelView', 'TalkReviewModelView') CategoryModelView = model_view( models.Category, 'Categories', 'Talks', form_columns=('name', 'slug'), ) TalkModelView = model_view( models.Talk, 'Talks', 'Talks', column_list=('name', 'status', 'level', 'type', 'user'), column_searchable_list=('name',), ) TalkReviewModelView = model_view( models.Talk, 'Review', 'Talks', can_create=False, can_delete=False, column_list=('name', 'status', 'level', 'type', 'user'), column_searchable_list=('name',), edit_template='talks/review.html', )
Add nested tailcall to debugger step test
/* * Test illustrating GH-1684, GH-1726, GH1786. */ /*=== entered test1 entered anotherFunction entered test2 entered anotherFunction ===*/ /* * Run with debugger attached, and: * * - StepOut from test1 and test2. * * - StepOver the 'return' statement in test1 and test2. * * - StepInto anotherFunction in test1 and test2. */ function anotherFunction() { var ret; print('entered anotherFunction'); ret = 'foo' + 123; return ret; } function test1() { print('entered test1'); return anotherFunction(); } function test2() { var ret; print('entered test2'); ret = anotherFunction(); return ret; } try { test1(); test2(); } catch (e) { print(e.stack || e); } /*=== before bar after bar ===*/ /* * Nested case. The tailcall in a nested call (not occurring in the * function where stepping starts) shouldn't affect line pausing. */ function foo() { return 1; } function bar() { return foo(); } function test() { print('before bar'); bar(); // step over this print('after bar'); } try { test(); } catch (e) { print(e.stack || e); } /*=== done ===*/ print('done');
/* * Test illustrating GH-1684 and GH-1726. * * Run with debugger attached, and: * * - StepOut from test1 and test2. * * - StepOver the 'return' statement in test1 and test2. * * - StepInto anotherFunction in test1 and test2. */ /*=== entered test1 entered anotherFunction entered test2 entered anotherFunction done ===*/ function anotherFunction() { var ret; print('entered anotherFunction'); ret = 'foo' + 123; return ret; } function test1() { print('entered test1'); return anotherFunction(); } function test2() { var ret; print('entered test2'); ret = anotherFunction(); return ret; } try { test1(); test2(); } catch (e) { print(e.stack || e); } print('done');
Make isListed / isUnlisted query more specific Address issue #141.
'use strict' /** * @module registry */ module.exports.isListed = isListed module.exports.isUnlisted = isUnlisted var vocab = require('solid-namespace') /** * Returns true if the parsed graph is a `solid:UnlistedDocument` document. * @method isUnlisted * @param graph {Graph} Parsed graph (loaded from a registry-like resource) * @return {Boolean} */ function isUnlisted (graph, rdf) { var ns = vocab(rdf) return graph.any(graph.uri, ns.rdf('type'), ns.solid('UnlistedDocument'), graph.uri) } /** * Returns true if the parsed graph is a `solid:ListedDocument` document. * @method isListed * @param graph {Graph} Parsed graph (loaded from a registry-like resource) * @return {Boolean} */ function isListed (graph, rdf) { var ns = vocab(rdf) return graph.any(graph.uri, ns.rdf('type'), ns.solid('ListedDocument'), graph.uri) }
'use strict' /** * @module registry */ module.exports.isListed = isListed module.exports.isUnlisted = isUnlisted var vocab = require('solid-namespace') /** * Returns true if the parsed graph is a `solid:UnlistedDocument` document. * @method isUnlisted * @param graph {Graph} Parsed graph (loaded from a registry-like resource) * @return {Boolean} */ function isUnlisted (graph, rdf) { var ns = vocab(rdf) return graph.any(null, null, ns.solid('UnlistedDocument'), graph.uri) } /** * Returns true if the parsed graph is a `solid:ListedDocument` document. * @method isListed * @param graph {Graph} Parsed graph (loaded from a registry-like resource) * @return {Boolean} */ function isListed (graph, rdf) { var ns = vocab(rdf) return graph.any(null, null, ns.solid('ListedDocument'), graph.uri) }
Fix title in About Window Shows up as 'Electron' on Windows
var about = module.exports = { init, win: null } var config = require('../../config') var electron = require('electron') function init () { if (about.win) { return about.win.show() } var win = about.win = new electron.BrowserWindow({ backgroundColor: '#ECECEC', center: true, fullscreen: false, height: 170, icon: getIconPath(), maximizable: false, minimizable: false, resizable: false, show: false, skipTaskbar: true, title: 'About ' + config.APP_WINDOW_TITLE, useContentSize: true, width: 300 }) win.loadURL(config.WINDOW_ABOUT) // No menu on the About window win.setMenu(null) win.webContents.once('did-finish-load', function () { win.show() }) win.once('closed', function () { about.win = null }) } function getIconPath () { return process.platform === 'win32' ? config.APP_ICON + '.ico' : config.APP_ICON + '.png' }
var about = module.exports = { init, win: null } var config = require('../../config') var electron = require('electron') function init () { if (about.win) { return about.win.show() } var win = about.win = new electron.BrowserWindow({ backgroundColor: '#ECECEC', center: true, fullscreen: false, height: 170, icon: getIconPath(), maximizable: false, minimizable: false, resizable: false, show: false, skipTaskbar: true, useContentSize: true, width: 300 }) win.loadURL(config.WINDOW_ABOUT) // No menu on the About window win.setMenu(null) win.webContents.once('did-finish-load', function () { win.show() }) win.once('closed', function () { about.win = null }) } function getIconPath () { return process.platform === 'win32' ? config.APP_ICON + '.ico' : config.APP_ICON + '.png' }
Clean up, comments, liveness checking, robust data transfer
import random import json import SocketExtend as SockExt import config as conf import parser as p def ping(sock): try: rand = random.randint(1, 99999) data = {'request':'ping', 'contents': {'value':rand}} SockExt.send_msg(sock, json.dumps(data)) result = json.loads(SockExt.recv_msg(sock)) if result['return'] == rand: return True else: return False except Exception as e: print "Exception while pinging: ", e return False def multiping(port, auths=[]): result = True for a_ip in auths: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.settimeout(120.0) sock.connect((a_ip, int(port))) if not ping(sock): result = False sock.shutdown(socket.SHUT_RDWR) sock.close() return result def alive(port, machines=[]): attempted = 0 success = False while (attempted < conf.tries): try: if utilities.multiping(port, machines): success = True break except Exception as e: attempted += 1 return success
import random import json import SocketExtend as SockExt import config as conf import parser as p def ping(sock): try: rand = random.randint(1, 99999) data = {'request':'ping', 'contents': {'value':rand}} SockExt.send_msg(sock, json.dumps(data)) result = json.loads(SockExt.recv_msg(sock)) if result['return'] == rand: return True else: return False except Exception as e: print "Exception while pinging: ", e return False def multiping(port, auths=[]): result = True for a_ip in auths: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.settimeout(120.0) sock.connect((a_ip, int(port))) if not ping(sock): result = False sock.shutdown(socket.SHUT_RDWR) sock.close() return result def alive(port, machines=[]): attempted = 0 success = False while (attempted < conf.tries): try: if utilities.multiping(port, machines): success = True break except Exception as e: attemped += 1 return success
Add missing assignment of name in constructor
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): self.name = name for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must be non-empty strings') if key[0].isdigit(): raise ValueError('attribute names cannot begin with a number') _key = re.sub(r'[^\w\d_]+', ' ', re.sub(r'[\s-]+', '_', key.upper())) self.__dict__[_key] = value def __repr__(self): return u'<AttrDict: %s>' % self.name def __getattr__(self, key): _key = key.upper() if _key not in self.__dict__: raise AttributeError("AttrDict object has not attribute '{0}'".format(key)) return self.__dict__[_key] def __contains__(self, key): return self.__dict__.__contains__(key.upper()) def __iter__(self): return self.__dict__.__iter__()
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must be non-empty strings') if key[0].isdigit(): raise ValueError('attribute names cannot begin with a number') _key = re.sub(r'[^\w\d_]+', ' ', re.sub(r'[\s-]+', '_', key.upper())) self.__dict__[_key] = value def __repr__(self): return u'<AttrDict: %s>' % self.name def __getattr__(self, key): _key = key.upper() if _key not in self.__dict__: raise AttributeError("AttrDict object has not attribute '{0}'".format(key)) return self.__dict__[_key] def __contains__(self, key): return self.__dict__.__contains__(key.upper()) def __iter__(self): return self.__dict__.__iter__()
Allow passing options to request lib
'use strict'; var request = require('request'); var xray = require('x-ray')(); var tabletojson = require('tabletojson'); module.exports.get = function get(url, options={}) { return new Promise(function(resolve, reject) { const requestOptions = { ...options, method: 'GET', url: url, } request.get(requestOptions, function(err, response, body) { if (err) { return reject(err); } if (response.statusCode >= 400) { return reject(new Error('The website requested returned an error!')); } xray(body, ['table@html'])(function (conversionError, tableHtmlList) { if (conversionError) { return reject(conversionError); } resolve(tableHtmlList.map(function(table) { // xray returns the html inside each table tag, and tabletojson // expects a valid html table, so we need to re-wrap the table. // Returning the first element in the converted array because // we should only ever be parsing one table at a time within this map. return tabletojson.convert('<table>' + table + '</table>')[0]; })); }); }) }); };
'use strict'; var request = require('request'); var xray = require('x-ray')(); var tabletojson = require('tabletojson'); module.exports.get = function get(url) { return new Promise(function(resolve, reject) { request.get(url, function(err, response, body) { if (err) { return reject(err); } if (response.statusCode >= 400) { return reject(new Error('The website requested returned an error!')); } xray(body, ['table@html'])(function (conversionError, tableHtmlList) { if (conversionError) { return reject(conversionError); } resolve(tableHtmlList.map(function(table) { // xray returns the html inside each table tag, and tabletojson // expects a valid html table, so we need to re-wrap the table. // Returning the first element in the converted array because // we should only ever be parsing one table at a time within this map. return tabletojson.convert('<table>' + table + '</table>')[0]; })); }); }) }); };
Remove string annotation (likely incomprehensible to mypy) and minor doc-string formatting.
## # .protocol.version ## """ PQ version class used by startup messages. """ from struct import Struct version_struct = Struct('!HH') class Version(tuple): """ Version((major, minor)) -> Version Version serializer and parser. """ major = property(fget = lambda s: s[0]) minor = property(fget = lambda s: s[1]) def __new__(subtype, major_minor): (major, minor) = major_minor major = int(major) minor = int(minor) # If it can't be packed like this, it's not a valid version. try: version_struct.pack(major, minor) except Exception as e: raise ValueError("unpackable major and minor") from e return tuple.__new__(subtype, (major, minor)) def __int__(self): return (self[0] << 16) | self[1] def bytes(self): return version_struct.pack(self[0], self[1]) def __repr__(self): return '%d.%d' %(self[0], self[1]) def parse(self, data): return self(version_struct.unpack(data)) parse = classmethod(parse) CancelRequestCode = Version((1234, 5678)) NegotiateSSLCode = Version((1234, 5679)) V2_0 = Version((2, 0)) V3_0 = Version((3, 0))
## # .protocol.version ## 'PQ version class' from struct import Struct version_struct = Struct('!HH') class Version(tuple): """Version((major, minor)) -> Version Version serializer and parser. """ major = property(fget = lambda s: s[0]) minor = property(fget = lambda s: s[1]) def __new__(subtype, major_minor : '(major, minor)'): (major, minor) = major_minor major = int(major) minor = int(minor) # If it can't be packed like this, it's not a valid version. try: version_struct.pack(major, minor) except Exception as e: raise ValueError("unpackable major and minor") from e return tuple.__new__(subtype, (major, minor)) def __int__(self): return (self[0] << 16) | self[1] def bytes(self): return version_struct.pack(self[0], self[1]) def __repr__(self): return '%d.%d' %(self[0], self[1]) def parse(self, data): return self(version_struct.unpack(data)) parse = classmethod(parse) CancelRequestCode = Version((1234, 5678)) NegotiateSSLCode = Version((1234, 5679)) V2_0 = Version((2, 0)) V3_0 = Version((3, 0))
Fix 'print_pos' templatetag for 2.7
# -*- coding: utf-8 -*- from django import template from ..models import Season, Race from ..common import ordered_position register = template.Library() @register.filter def champion_filter(season_id): if season_id: season = Season.objects.get(pk=season_id) return '<span class="champion_tag">&#9818;</span>' if season.has_champion() else '' else: return '' @register.filter(is_safe=False) def get_attribute(obj, attr): if attr is None: return None return getattr(obj, attr) @register.filter(is_safe=False) def order_results(results, pos_key): return sorted(results, key=lambda result: (ordered_position(result, pos_key))) @register.filter def print_pos(pos): str_pos = u'' if pos: str_pos = u'{pos}º'.format(pos=pos) if pos == 1: str_pos = u'<strong>{0}</strong>'.format(str_pos) return str_pos @register.filter def race_url(race_id): race = Race.objects.get(pk=race_id) return race.get_absolute_url()
# -*- coding: utf-8 -*- from django import template from ..models import Season, Race from ..common import ordered_position register = template.Library() @register.filter def champion_filter(season_id): if season_id: season = Season.objects.get(pk=season_id) return '<span class="champion_tag">&#9818;</span>' if season.has_champion() else '' else: return '' @register.filter(is_safe=False) def get_attribute(obj, attr): if attr is None: return None return getattr(obj, attr) @register.filter(is_safe=False) def order_results(results, pos_key): return sorted(results, key=lambda result: (ordered_position(result, pos_key))) @register.filter def print_pos(pos): str_pos = u'' if pos: str_pos = u'{pos}º'.format(pos=pos) if pos == 1: str_pos = '<strong>{0}</strong>'.format(str_pos) return str_pos @register.filter def race_url(race_id): race = Race.objects.get(pk=race_id) return race.get_absolute_url()
Implement new static form extension methods Necessary for Symfony 5.0
<?php namespace Dkplus\CsrfApiUnprotectionBundle; use Dkplus\CsrfApiUnprotectionBundle\UnprotectionRule\UnprotectionRule; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\OptionsResolver\OptionsResolver; final class CsrfDisablingExtension extends AbstractTypeExtension { /** @var RequestStack */ private $requests; /** @var UnprotectionRule */ private $unprotectionRule; public static function getExtendedTypes() { return [FormType::class]; } /** * @param RequestStack $requests * @param UnprotectionRule $unprotectionRule */ public function __construct(RequestStack $requests, UnprotectionRule $unprotectionRule) { $this->requests = $requests; $this->unprotectionRule = $unprotectionRule; } public function getExtendedType() { return FormType::class; } public function configureOptions(OptionsResolver $resolver) { if ($this->requests->getMasterRequest() && ! $this->unprotectionRule->matches($this->requests->getMasterRequest()) ) { return; } $resolver->setDefaults(['csrf_protection' => false]); } }
<?php namespace Dkplus\CsrfApiUnprotectionBundle; use Dkplus\CsrfApiUnprotectionBundle\UnprotectionRule\UnprotectionRule; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\OptionsResolver\OptionsResolver; final class CsrfDisablingExtension extends AbstractTypeExtension { /** @var RequestStack */ private $requests; /** @var UnprotectionRule */ private $unprotectionRule; /** * @param RequestStack $requests * @param UnprotectionRule $unprotectionRule */ public function __construct(RequestStack $requests, UnprotectionRule $unprotectionRule) { $this->requests = $requests; $this->unprotectionRule = $unprotectionRule; } public function getExtendedType() { return FormType::class; } public function configureOptions(OptionsResolver $resolver) { if ($this->requests->getMasterRequest() && ! $this->unprotectionRule->matches($this->requests->getMasterRequest()) ) { return; } $resolver->setDefaults(['csrf_protection' => false]); } }
Install the Avena library too.
#!/usr/bin/env python2 from distutils.core import setup from hipshot import hipshot _classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Video', ] with open('README.rst', 'r') as file: _long_description = file.read() _setup_args = { 'author': hipshot.__author__, 'author_email': hipshot.__email__, 'classifiers': _classifiers, 'description': hipshot.__doc__, 'license': hipshot.__license__, 'long_description': _long_description, 'name': 'Hipshot', 'url': 'https://bitbucket.org/eliteraspberries/hipshot', 'version': hipshot.__version__, } if __name__ == '__main__': setup(packages=['avena', 'hipshot'], scripts=['scripts/hipshot'], **_setup_args)
#!/usr/bin/env python2 from distutils.core import setup from hipshot import hipshot _classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Video', ] with open('README.rst', 'r') as file: _long_description = file.read() _setup_args = { 'author': hipshot.__author__, 'author_email': hipshot.__email__, 'classifiers': _classifiers, 'description': hipshot.__doc__, 'license': hipshot.__license__, 'long_description': _long_description, 'name': 'Hipshot', 'url': 'https://bitbucket.org/eliteraspberries/hipshot', 'version': hipshot.__version__, } if __name__ == '__main__': setup(packages=['hipshot'], scripts=['scripts/hipshot'], **_setup_args)
Fix test with DB fixtures
<?php /** * BasicTest.php * Copyright (c) 2020 james@firefly-iii.org * * This file is part of Firefly III (https://github.com/firefly-iii). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ declare(strict_types=1); namespace Tests\Feature; use Tests\TestCase; /** * Class BasicTest */ class BasicTest extends TestCase { /** * A basic test example. * * @return void */ public function testBasicTest(): void { self::assertTrue(true); } /** * */ public function testDatabase(): void { $this->assertDatabaseHas( 'users', [ 'email' => 'james@firefly', ] ); } }
<?php /** * BasicTest.php * Copyright (c) 2020 james@firefly-iii.org * * This file is part of Firefly III (https://github.com/firefly-iii). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ declare(strict_types=1); namespace Tests\Feature; use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; /** * Class BasicTest */ class BasicTest extends TestCase { use RefreshDatabase; /** * A basic test example. * * @return void */ public function testBasicTest(): void { self::assertTrue(true); } /** * */ public function testDatabase(): void { $this->assertDatabaseHas( 'users', [ 'email' => 'james@firefly', ] ); } }
Disable Cython test until Cython support new pythonic layout
import os import unittest class TestCython(unittest.TestCase): pass # Needs to wait unil cython supports pythran new builtins naming #def add_test(name, runner, target): # setattr(TestCython, "test_" + name, lambda s: runner(s, target)) # #try: # import Cython # import glob # import sys # targets = glob.glob(os.path.join(os.path.dirname(__file__), "cython", "setup_*.py")) # sys.path.append(os.path.join(os.path.dirname(__file__), "cython")) # # for target in targets: # def runner(self, target): # cwd = os.getcwd() # try: # os.chdir(os.path.dirname(target)) # exec(open(os.path.basename(target)).read()) # except: # raise # finally: # os.chdir(cwd) # name, _ = os.path.splitext(os.path.basename(target)) # add_test(name, runner, target) # # #except ImportError: # pass
import os import unittest class TestCython(unittest.TestCase): pass def add_test(name, runner, target): setattr(TestCython, "test_" + name, lambda s: runner(s, target)) try: import Cython import glob import sys targets = glob.glob(os.path.join(os.path.dirname(__file__), "cython", "setup_*.py")) sys.path.append(os.path.join(os.path.dirname(__file__), "cython")) for target in targets: def runner(self, target): cwd = os.getcwd() try: os.chdir(os.path.dirname(target)) exec(open(os.path.basename(target)).read()) except: raise finally: os.chdir(cwd) name, _ = os.path.splitext(os.path.basename(target)) add_test(name, runner, target) except ImportError: pass
Delete performance benchmarks, they are now hosted as a separate github repository.
package com.zaxxer.hikari; import java.sql.Statement; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; import com.zaxxer.hikari.mocks.StubStatement; import com.zaxxer.hikari.util.FastStatementList; public class TestFastStatementList { @Test public void testOverflow() { ArrayList<Statement> verifyList = new ArrayList<Statement>(); FastStatementList list = new FastStatementList(); for (int i = 0; i < 100; i++) { StubStatement statement = new StubStatement(null); list.add(statement); verifyList.add(statement); } for (int i = 0; i < 100; i++) { Assert.assertNotNull("Element " + i, list.get(i)); Assert.assertSame(verifyList.get(i), list.get(i)); } } }
package com.zaxxer.hikari; import java.sql.Statement; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; import com.zaxxer.hikari.performance.StubStatement; import com.zaxxer.hikari.util.FastStatementList; public class TestFastStatementList { @Test public void testOverflow() { ArrayList<Statement> verifyList = new ArrayList<Statement>(); FastStatementList list = new FastStatementList(); for (int i = 0; i < 100; i++) { StubStatement statement = new StubStatement(); list.add(statement); verifyList.add(statement); } for (int i = 0; i < 100; i++) { Assert.assertNotNull("Element " + i, list.get(i)); Assert.assertSame(verifyList.get(i), list.get(i)); } } }
Fix `assert_called` usage for Python 3.5 build The `assert_called` method seems to invoke a bug caused by a type in the unittest mock module. (The bug was ultimately tracked and fix here: https://bugs.python.org/issue24656)
# Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify assert uplink_builder_mock.add_hook.called assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify uplink_builder_mock.add_hook.assert_called() assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
# Local imports from uplink import session def test_base_url(uplink_builder_mock): # Setup uplink_builder_mock.base_url = "https://api.github.com" sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.base_url == sess.base_url def test_headers(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.headers["key"] = "value" # Verify uplink_builder_mock.add_hook.assert_called() assert sess.headers == {"key": "value"} def test_params(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.params["key"] = "value" # Verify uplink_builder_mock.add_hook.assert_called() assert sess.params == {"key": "value"} def test_auth(uplink_builder_mock): # Setup uplink_builder_mock.auth = ("username", "password") sess = session.Session(uplink_builder_mock) # Run & Verify assert uplink_builder_mock.auth == sess.auth def test_auth_set(uplink_builder_mock): # Setup sess = session.Session(uplink_builder_mock) # Run sess.auth = ("username", "password") # Verify assert ("username", "password") == uplink_builder_mock.auth
Support conversion profile flavor params control git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@59577 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
<?php /** * @package api * @subpackage objects */ class KalturaConversionProfileAssetParams extends KalturaObject implements IFilterable { /** * The id of the conversion profile * * @var int * @readonly * @filter eq,in */ public $conversionProfileId; /** * The id of the asset params * * @var int * @readonly * @filter eq,in */ public $assetParamsId; /** * The ingestion origin of the asset params * * @var KalturaFlavorReadyBehaviorType * @filter eq,in */ public $readyBehavior; /** * The ingestion origin of the asset params * * @var KalturaAssetParamsOrigin * @filter eq,in */ public $origin; private static $map_between_objects = array ( 'conversionProfileId', 'assetParamsId' => 'flavorParamsId', 'readyBehavior', 'origin', ); public function getMapBetweenObjects ( ) { return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects ); } public function getExtraFilters() { return array(); } public function getFilterDocs() { return array(); } }
<?php /** * @package api * @subpackage objects */ class KalturaConversionProfileAssetParams extends KalturaObject implements IFilterable { /** * The id of the conversion profile * * @var int * @readonly * @filter eq,in */ public $conversionProfileId; /** * The id of the asset params * * @var int * @readonly * @filter eq,in */ public $assetParamsId; /** * @var int * @readonly */ public $partnerId; /** * The ingestion origin of the asset params * * @var KalturaFlavorReadyBehaviorType * @filter eq,in */ public $readyBehavior; /** * The ingestion origin of the asset params * * @var KalturaAssetParamsOrigin * @filter eq,in */ public $origin; private static $map_between_objects = array ( 'conversionProfileId', 'assetParamsId', 'partnerId', 'readyBehavior', 'origin', ); public function getMapBetweenObjects ( ) { return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects ); } public function getExtraFilters() { return array(); } public function getFilterDocs() { return array(); } }
Fix function call and api url
'use strict'; var request = require('request'); function giphy(bot, controller, message) { var msg = ''; var url = 'http://api.giphy.com/v1/gifs/search?q='; url += message.match[1] + '&api_key=dc6zaTOxFJmzC'; request.get(url, function(err, res, body) { if (!err && res.statusCode === 200) { var response = JSON.parse(body); var gifs = response.data.length; var urls = response.data[0].images.fixed_height.url; if (gifs > 0 && urls !== null) { bot.reply(message, urls); } else { msg = 'Huh... I couldn\'t find `' + message.match[1] + '` on Giphy.'; bot.reply(message, msg); } } else { msg = 'Huh... I couldn\'t find `' + message.match[1] + '` on Giphy.'; bot.reply(message, msg); } }); } module.exports = { name: 'giphy me', author: 'Deiby Toralva (deibytb)', patterns: ['giphy me (.*)'], types: ['direct_message', 'direct_mention'], description: 'Search for a gif on Giphy', command: giphy, };
'use strict'; var request = require('request'); function spotify(bot, controller, message) { var msg = ''; var url = 'https://api.spotify.com/v1/search?q='; url += message.match[1] + '&type=track'; request.get(url, function(err, res, body) { if (!err && res.statusCode === 200) { var response = JSON.parse(body); var gifs = response.data.length; var urls = response.data[0].images.fixed_height.url; if (gifs > 0 && urls !== null) { bot.reply(message, urls); } else { msg = 'Huh... I couldn\'t find `' + message.match[1] + '` on Giphy.'; bot.reply(message, msg); } } else { msg = 'Huh... I couldn\'t find `' + message.match[1] + '` on Giphy.'; bot.reply(message, msg); } }); } module.exports = { name: 'giphy me', author: 'Deiby Toralva (deibytb)', //patterns: ['giphy me (.*)'], types: ['direct_message', 'direct_mention'], description: 'Search for a gif on Giphy', command: giphy, };
Tweak poster size a bit.
$('form').submit(function(event) { event.preventDefault(); var movie = $('#movie'), id = $('#search-id').val(); movie.html('<img src="/static/img/loading.gif">'); var request = $.getJSON('/movie/' + id + '/100', function(data) { var html = ''; html += '<img src="' + data.poster + '" class="img-polaroid">'; html += '<section class="movie-info">'; html += '<h2>' + data.title + '</h2>'; html += '<p>Genres: '; $.each(data.genres, function(index, value) { html += value; if (data.genres[index + 1]) { html += ' / '; } }); html += '</p>'; html += '<p>Rating: ' + data.vote_average + ' (' + data.vote_count + ' votes)</p>'; html += '<p>Release date: ' + data.release_date + '</p>'; html += '<p>' + data.overview + '</p>'; html += '</section>'; movie.html(html); }); request.fail(function(jqXHR, textStatus) { movie.html('<div class="alert alert-error">Bad request!</div>'); }); });
$('form').submit(function(event) { event.preventDefault(); var movie = $('#movie'), id = $('#search-id').val(); movie.html('<img src="/static/img/loading.gif">'); var request = $.getJSON('/movie/' + id + '/110', function(data) { var html = ''; html += '<img src="' + data.poster + '" class="img-polaroid">'; html += '<section class="movie-info">'; html += '<h2>' + data.title + '</h2>'; html += '<p>Genres: '; $.each(data.genres, function(index, value) { html += value; if (data.genres[index + 1]) { html += ' / '; } }); html += '</p>'; html += '<p>Rating: ' + data.vote_average + ' (' + data.vote_count + ' votes)</p>'; html += '<p>Release date: ' + data.release_date + '</p>'; html += '<p>' + data.overview + '</p>'; html += '</section>'; movie.html(html); }); request.fail(function(jqXHR, textStatus) { movie.html('<div class="alert alert-error">Bad request!</div>'); }); });
Check parent.children before splice, accommodate jest When used with jest, `parent.children` will be undefined. `console.log(module)`: { exports: [Function: requireFromString], filename: 'E:/Projects/repos/cosmiconfig/node_modules/require-from-string/index.js', id: 'E:/Projects/repos/cosmiconfig/node_modules/require-from-string/index.js', children: [], parent: { exports: {}, filename: 'mock.js', id: 'mockParent' }, paths: [ 'E:/Projects/repos/cosmiconfig/node_modules/require-from-string/node_modules', 'E:/Projects/repos/cosmiconfig/node_modules/node_modules', 'E:/Projects/repos/cosmiconfig/node_modules', 'E:/Projects/repos/node_modules', 'E:/Projects/node_modules', 'E:/node_modules' ], require: { [Function: bound requireModuleOrMock] cache: {}, extensions: {}, requireActual: [Function: bound requireModule], requireMock: [Function: bound requireMock], resolve: [Function] } }
'use strict'; var Module = require('module'); var path = require('path'); module.exports = function requireFromString(code, filename, opts) { if (typeof filename === 'object') { opts = filename; filename = undefined; } opts = opts || {}; filename = filename || ''; opts.appendPaths = opts.appendPaths || []; opts.prependPaths = opts.prependPaths || []; if (typeof code !== 'string') { throw new Error('code must be a string, not ' + typeof code); } var paths = Module._nodeModulePaths(path.dirname(filename)); var parent = module.parent; var m = new Module(filename, parent); m.filename = filename; m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths); m._compile(code, filename); var exports = m.exports; parent.children && parent.children.splice(parent.children.indexOf(m), 1); return exports; };
'use strict'; var Module = require('module'); var path = require('path'); module.exports = function requireFromString(code, filename, opts) { if (typeof filename === 'object') { opts = filename; filename = undefined; } opts = opts || {}; filename = filename || ''; opts.appendPaths = opts.appendPaths || []; opts.prependPaths = opts.prependPaths || []; if (typeof code !== 'string') { throw new Error('code must be a string, not ' + typeof code); } var paths = Module._nodeModulePaths(path.dirname(filename)); var parent = module.parent; var m = new Module(filename, parent); m.filename = filename; m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths); m._compile(code, filename); var exports = m.exports; parent.children.splice(parent.children.indexOf(m), 1); return exports; };
Use internal fingerprint for Design/CouplingBetweenObjects issues This is a similar fix to d419bbb2228d49bf23c8ed23c25295bf0f8b416b. This type of issue should use a more flexible fingerprint (path, rule, method name) instead of the source-based default fingerprint.
<?php namespace PHPMD; class Fingerprint { const OVERRIDE_RULES = [ "Controversial/CamelCaseVariableName", "Controversial/CamelCasePropertyName", "CyclomaticComplexity", "Design/CouplingBetweenObjects", "Design/LongClass", "Design/LongMethod", "Design/LongParameterList", "Design/NpathComplexity", "Design/NumberOfChildren", "Design/TooManyFields", "Design/TooManyMethods", "Design/TooManyPublicMethods", "Design/WeightedMethodCount", "ExcessivePublicCount", "Naming/ShortMethodName", ]; private $name; private $path; private $rule; public function __construct($path, $rule, $name) { $this->path = $path; $this->rule = $rule; $this->name = $name; } public function compute() { $fingerprint = null; if (in_array($this->rule, self::OVERRIDE_RULES)) { $fingerprint = md5($this->path . $this->rule . $this->name); } return $fingerprint; } }
<?php namespace PHPMD; class Fingerprint { const OVERRIDE_RULES = [ "Controversial/CamelCaseVariableName", "Controversial/CamelCasePropertyName", "CyclomaticComplexity", "Design/LongClass", "Design/LongMethod", "Design/LongParameterList", "Design/NpathComplexity", "Design/NumberOfChildren", "Design/TooManyFields", "Design/TooManyMethods", "Design/TooManyPublicMethods", "Design/WeightedMethodCount", "ExcessivePublicCount", "Naming/ShortMethodName", ]; private $name; private $path; private $rule; public function __construct($path, $rule, $name) { $this->path = $path; $this->rule = $rule; $this->name = $name; } public function compute() { $fingerprint = null; if (in_array($this->rule, self::OVERRIDE_RULES)) { $fingerprint = md5($this->path . $this->rule . $this->name); } return $fingerprint; } }
Fix typo in licence header.
<?php /* Plugin Name: Fortytwo - Two Factor Authentication plugin Plugin URI: https://www.fortytwo.com Description: Implement the fortytwo Two Factor Authentication service for login and register on wordpress. Version: 1.0.0-RC11 Author: Sebastien Lemarinel <sebastien.lemarinel@fortytwo.com> Author URI: https://www.fortytwo.com License: MIT */ // Load the composer autoload require dirname(__FILE__) . '/vendor/autoload.php'; // Workaround for the Doctrine annotation Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace( 'JMS\Serializer\Annotation', dirname(__FILE__) . "/vendor/jms/serializer/src" ); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Login(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Admin(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\UserProfile(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Register();
<?php /* Plugin Name: Fortytwo - Two Factor Authentication plugin Plugin URI: https://www.fortytwo.com Description: Implement the fortytwo Two Factor Authentication service for login and register on wordpress. Version: 1.0.0-RC11 Author: Sebastien Lemarinel <sebastien.lemarinel@fortytwo.com> Author URI: https://www.fortytwo.com License: GPL2 */ // Load the composer autoload require dirname(__FILE__) . '/vendor/autoload.php'; // Workaround for the Doctrine annotation Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace( 'JMS\Serializer\Annotation', dirname(__FILE__) . "/vendor/jms/serializer/src" ); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Login(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Admin(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\UserProfile(); new Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Controller\Register();
Rename category fields in shell reporter
#!/usr/bin/env python3 import json class ShellReporter: def report_categories(self, categories): to_dict = lambda x: { 'TOOL': '{:s}'.format(x.tool), 'CONTEXT': '{:s}'.format(x.context) } category_dict_list = list(map(to_dict, categories)) print(json.dumps(category_dict_list)) def report_job(self, job): category = '{:s}-{:s}'.format(job.tool, job.type) self._report_job(job.timestamp, '{:s}.STATUS'.format(category), '{:d} ({:s})'.format(job.status, 'SUCCESS' if job.status else 'FAILURE')) self._report_job(job.timestamp, '{:s}.DURATION'.format(category), job.duration) def _report_job(self, timestamp, metric_name, metric_value): print('timestamp: {:%Y:%m:%dT:%H:%M:%S:%z} - metric_name: {:s} - metric_value: {}'.format(timestamp, metric_name, metric_value))
#!/usr/bin/env python3 import json class ShellReporter: def report_categories(self, categories): to_dict = lambda x: { '{#TOOL}}': '{:s}'.format(x.tool), '{#TYPE}': '{:s}'.format(x.context) } category_dict_list = list(map(to_dict, categories)) print(json.dumps(category_dict_list)) def report_job(self, job): category = '{:s}-{:s}'.format(job.tool, job.type) self._report_job(job.timestamp, '{:s}.STATUS'.format(category), '{:d} ({:s})'.format(job.status, 'SUCCESS' if job.status else 'FAILURE')) self._report_job(job.timestamp, '{:s}.DURATION'.format(category), job.duration) def _report_job(self, timestamp, metric_name, metric_value): print('timestamp: {:%Y:%m:%dT:%H:%M:%S:%z} - metric_name: {:s} - metric_value: {}'.format(timestamp, metric_name, metric_value))
[pH7Tpl][Predefined] Split code into a describable method
<?php /*************************************************************************** * @title PH7 Template Engine * @desc Define functions (and helpers). * Predefined functions can save considerable resources and speeds up the code with respect to functions in variables assigned through the object's template engine (PH7Tpl). * * @author Pierre-Henry Soria <ph7software@gmail.com> * @category PH7 Template Engine * @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Predefined * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license CC-BY License - http://creativecommons.org/licenses/by/3.0/ ***************************************************************************/ namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Predefined; defined('PH7') or exit('Restricted access'); class Func extends Predefined { /** * {@inheritdoc} */ public function assign() { $this->dataFunction(); return $this; } private function dataFunction() { $this->addFunc('<ph:date value="(\w+)" ?/?>', 'date(\'$1\')'); } }
<?php /*************************************************************************** * @title PH7 Template Engine * @desc Define functions (and helpers). * Predefined functions can save considerable resources and speeds up the code with respect to functions in variables assigned through the object's template engine (PH7Tpl). * * @author Pierre-Henry Soria <ph7software@gmail.com> * @category PH7 Template Engine * @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Predefined * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license CC-BY License - http://creativecommons.org/licenses/by/3.0/ ***************************************************************************/ namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Predefined; defined('PH7') or exit('Restricted access'); class Func extends Predefined { /** * {@inheritdoc} */ public function assign() { $this->addFunc('<ph:date value="(\w+)" ?/?>', 'date(\'$1\')'); return $this; } }
Configure bundling for images and fonts
const path = require('path') const webpack = require('webpack') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { entry: [path.resolve(__dirname, '../client/index.js')], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] }, { test: /\.css/, loader: ExtractTextPlugin.extract('css') }, { test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/, loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]' } ], preLoaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader' }] }, output: { path: path.resolve(__dirname, '../public'), filename: 'client.js' }, plugins: [ new ExtractTextPlugin('style.css', { allChunks: true }), new webpack.ProvidePlugin({ fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch' }) ], resolve: { root: path.resolve(__dirname, '../client'), extensions: ['', '.js'] } }
const path = require('path') const webpack = require('webpack') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { entry: [path.resolve(__dirname, '../client/index.js')], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] }, { test: /\.css/, loader: ExtractTextPlugin.extract('css') } ], preLoaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader' }] }, output: { path: path.resolve(__dirname, '../public'), filename: 'client.js' }, plugins: [ new ExtractTextPlugin('style.css', { allChunks: true }), new webpack.ProvidePlugin({ fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch' }) ], resolve: { root: path.resolve(__dirname, '../client'), extensions: ['', '.js'] } }
Set file permissions to readable in export_signatures
import os import shutil from tempfile import mkstemp from django.core.management import call_command from celeryconf import app SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip')) @app.task def bug_update_status(): call_command('bug_update_status') @app.task def cleanup_old_crashes(): call_command('cleanup_old_crashes') @app.task def triage_new_crashes(): call_command('triage_new_crashes') @app.task def export_signatures(): fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip") os.close(fd) try: call_command('export_signatures', tmpf) os.chmod(tmpf, 0o644) shutil.copy(tmpf, SIGNATURES_ZIP) finally: os.unlink(tmpf)
import os import shutil from tempfile import mkstemp from django.core.management import call_command from celeryconf import app SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip')) @app.task def bug_update_status(): call_command('bug_update_status') @app.task def cleanup_old_crashes(): call_command('cleanup_old_crashes') @app.task def triage_new_crashes(): call_command('triage_new_crashes') @app.task def export_signatures(): fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip") os.close(fd) try: call_command('export_signatures', tmpf) shutil.copy(tmpf, SIGNATURES_ZIP) finally: os.unlink(tmpf)
Support DNS round-robin balancing through Route53 Our codegen actions for adding/updating A records in Route53 only support a single IP as a value. Changing to accept a comma-separated list, which will add an unweighted round-robin A record. Should also add WRR at some point probably, but I just don't care enough.
from lib import action class ActionManager(action.BaseAction): def run(self, **kwargs): action = kwargs['action'] del kwargs['action'] module_path = kwargs['module_path'] del kwargs['module_path'] if action == 'run_instances': kwargs['user_data'] = self.st2_user_data() if action == 'create_tags': kwargs['tags'] = self.split_tags(kwargs['tags']) if action in ('add_a', 'update_a'): kwargs['value'] = kwargs['value'].split(',') if 'cls' in kwargs.keys(): cls = kwargs['cls'] del kwargs['cls'] return self.do_method(module_path, cls, action, **kwargs) else: return self.do_function(module_path, action, **kwargs)
from lib import action class ActionManager(action.BaseAction): def run(self, **kwargs): action = kwargs['action'] del kwargs['action'] module_path = kwargs['module_path'] del kwargs['module_path'] if action == 'run_instances': kwargs['user_data'] = self.st2_user_data() if action == 'create_tags': kwargs['tags'] = self.split_tags(kwargs['tags']) if 'cls' in kwargs.keys(): cls = kwargs['cls'] del kwargs['cls'] return self.do_method(module_path, cls, action, **kwargs) else: return self.do_function(module_path, action, **kwargs)
Revert "enrollment api endpoint has been updated to accept trailing forward slashes"
""" URLs for the Enrollment API """ from django.conf import settings from django.conf.urls import patterns, url from .views import ( EnrollmentView, EnrollmentListView, EnrollmentCourseDetailView ) USERNAME_PATTERN = settings.USERNAME_PATTERN urlpatterns = patterns( 'enrollment.views', url( r'^enrollment/{username},{course_key}$'.format(username=USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url( r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'), url( r'^course/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails' ), )
""" URLs for the Enrollment API """ from django.conf import settings from django.conf.urls import patterns, url from .views import ( EnrollmentView, EnrollmentListView, EnrollmentCourseDetailView ) USERNAME_PATTERN = settings.USERNAME_PATTERN urlpatterns = patterns( 'enrollment.views', url( r'^enrollment/{username},{course_key}$'.format(username=USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url( r'^enrollment/{course_key}'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'), url( r'^course/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails' ), )
Revert "default to unversioned vendored jquery.js for ci" This reverts commit 4b5a84880f8317549140b5cfba96d61c14eba5d2.
(function() { // Insert a script tag pointing at the desired version of jQuery // Get the version from the url var jqueryRE = /[\\?&]jquery=([^&#]*)/, results = jqueryRE.exec( location.search ), version = "1.7.1", myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script" ).length - 1], baseUrl = myScriptTag.src.replace( /(.*)\/.*$/, "$1/" ), url; if( results ) { version = decodeURIComponent(results[results.length - 1].replace(/\+/g, " ")); } switch( version ) { // Local versions case "1.6.4": case "1.7.1": case "1.7.2": url = baseUrl + "jquery-" + version + ".js"; break; // CDN versions default: url = "http://code.jquery.com/jquery-"+version+".js"; break; } document.write( "<script src='" + url + "'></script>" ); if ( parseInt( version.replace( /\./g, "" ), 10 ) < 170 && window.define && window.define.amd ) { document.write( '<script>define( "jquery", [], function () { return jQuery; } );</script>' ); } }());
(function() { // Insert a script tag pointing at the desired version of jQuery // Get the version from the url var jqueryRE = /[\\?&]jquery=([^&#]*)/, results = jqueryRE.exec( location.search ), version = "", myScriptTag = document.getElementsByTagName( "script" )[document.getElementsByTagName( "script" ).length - 1], baseUrl = myScriptTag.src.replace( /(.*)\/.*$/, "$1/" ), url; if( results ) { version = decodeURIComponent(results[results.length - 1].replace(/\+/g, " ")); } switch( version ) { // Local versions case "1.6.4": case "1.7.1": case "1.7.2": url = baseUrl + "jquery-" + version + ".js"; break; default: url = baseUrl + "jquery.js"; break; } document.write( "<script src='" + url + "'></script>" ); if ( parseInt( version.replace( /\./g, "" ), 10 ) < 170 && window.define && window.define.amd ) { document.write( '<script>define( "jquery", [], function () { return jQuery; } );</script>' ); } }());
Remove comment, it’s a lie
package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } }
package uk.ac.ebi.atlas.bioentity.properties; import com.google.gson.JsonObject; // Used in bioentity-information.jsp public class PropertyLink { private String text; private String url; private int relevance; PropertyLink(String text, String url, int relevance) { this.text = text; this.url = url; this.relevance = relevance; } PropertyLink(String text, int relevance) { this(text, "", relevance); } public String getText() { return text; } public String getUrl() { return url; } public JsonObject toJson(){ JsonObject result = new JsonObject(); result.addProperty("text", text); result.addProperty("url", url); result.addProperty("relevance", relevance); return result; } }
[Misc] Clean up unused imports (was supposed to be done in branch).
package org.talend.dataprep.configuration; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Module; @Configuration @SuppressWarnings("InsufficientBranchCoverage") public class Serialization { @Autowired List<Module> modules; @Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); builder.indentOutput(false); builder.modules(modules); return builder; } }
package org.talend.dataprep.configuration; import java.util.List; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JSR310Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.Module; @Configuration @SuppressWarnings("InsufficientBranchCoverage") public class Serialization { @Autowired List<Module> modules; @Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); builder.indentOutput(false); // FIXME we should use jackson modules and remove home made LocalDateTimeModule //modules.add( new JavaTimeModule() ); //modules.add( new Jdk8Module() ); builder.modules(modules); return builder; } }
fix: Test Case for disabled role
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import unittest test_records = frappe.get_test_records('Role') class TestUser(unittest.TestCase): def test_disable_role(self): frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 1 role.save() self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" not in frappe.get_roles("test@example.com")) role = frappe.get_doc("Role", "_Test Role 3") role.disabled = 0 role.save() frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3") self.assertTrue("_Test Role 3" in frappe.get_roles("test@example.com"))
Divide by 1.2 as described in BH1750 datasheet. Additionally divide by 2 when in high-resolution mode2
var i2c = require('i2c'); var _ = require('lodash'); var utils = require('./utils'); var BH1750 = function (opts) { this.options = _.extend({}, { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }, opts); this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!utils.exists(cb)) { console.error("missing callback"); return; } this.wire.writeByte(this.options.command, function (err) { if (utils.exists(err)) { console.error("error write byte to BH1750 - command: ", self.options.command); } }); this.wire.readBytes(this.options.command, this.options.length, function (err, res) { var hi = res.readUInt8(0); var lo = res.readUInt8(1); var lux = ((hi << 8) + lo)/1.2; if (self.options.command = 0x11) { lux = lux/2; } cb.call(self, lux); }); }; module.exports = BH1750;
var i2c = require('i2c'); var _ = require('lodash'); var utils = require('./utils'); var BH1750 = function (opts) { this.options = _.extend({}, { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }, opts); this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!utils.exists(cb)) { console.error("missing callback"); return; } this.wire.writeByte(this.options.command, function (err) { if (utils.exists(err)) { console.error("error write byte to BH1750 - command: ", self.options.command); } }); this.wire.readBytes(this.options.command, this.options.length, function (err, res) { var hi = res.readUInt8(0); var lo = res.readUInt8(1); cb.call(self, ((hi << 8) + lo)); }); }; module.exports = BH1750;
Disable External Entity loading in XML
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\SamlBundle; use SAML2_Compat_ContainerSingleton; use Surfnet\SamlBundle\DependencyInjection\Compiler\SamlAttributeRegistrationCompilerPass; use Surfnet\SamlBundle\DependencyInjection\Compiler\SpRepositoryAliasCompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; class SurfnetSamlBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new SpRepositoryAliasCompilerPass()); $container->addCompilerPass(new SamlAttributeRegistrationCompilerPass()); } public function boot() { libxml_disable_entity_loader(true); $bridgeContainer = $this->container->get('surfnet_saml.saml2.bridge_container'); SAML2_Compat_ContainerSingleton::setContainer($bridgeContainer); } }
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\SamlBundle; use SAML2_Compat_ContainerSingleton; use Surfnet\SamlBundle\DependencyInjection\Compiler\SamlAttributeRegistrationCompilerPass; use Surfnet\SamlBundle\DependencyInjection\Compiler\SpRepositoryAliasCompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; class SurfnetSamlBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new SpRepositoryAliasCompilerPass()); $container->addCompilerPass(new SamlAttributeRegistrationCompilerPass()); } public function boot() { $bridgeContainer = $this->container->get('surfnet_saml.saml2.bridge_container'); SAML2_Compat_ContainerSingleton::setContainer($bridgeContainer); } }
Disable testing for index.html, needs ember build Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() # def test_index(self): # response = self.fetch('/') # self.assertEqual(200, response.code) # def test_channel(self): # response = self.fetch('/c/foo') # self.assertEqual(200, response.code) # def test_arbitrary(self): # response = self.fetch('/arbitrary-page') # self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code)
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() def test_index(self): response = self.fetch('/') self.assertEqual(200, response.code) def test_channel(self): response = self.fetch('/c/foo') self.assertEqual(200, response.code) def test_arbitrary(self): response = self.fetch('/arbitrary-page') self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code)
Append settings hash to URL
(function(Pebble, window) { var settings = {}; Pebble.addEventListener("ready", function(e) { settings = window.localStorage.getItem("settings"); if(settings !== '') { var options = JSON.parse(settings); Pebble.sendAppMessage(options); } }); Pebble.addEventListener("showConfiguration", function() { settings = window.localStorage.getItem("settings"); if(!settings) { settings = {}; } Pebble.openURL("http://rexmac.com/projects/pebble/chronocode/settings.html#" + encodeURIComponent(JSON.stringify(settings))); }); Pebble.addEventListener("webviewclosed", function(e) { var options = JSON.parse(decodeURIComponent(e.response)); if(Object.keys(options).length > 0) { window.localStorage.setItem("settings", JSON.stringify(options)); Pebble.sendAppMessage(options); } }) })(Pebble, window);
(function(Pebble, window) { var settings = {}; Pebble.addEventListener("ready", function(e) { settings = window.localStorage.getItem("settings"); if(settings !== '') { var options = JSON.parse(settings); Pebble.sendAppMessage(options); } }); Pebble.addEventListener("showConfiguration", function() { settings = window.localStorage.getItem("settings"); if(!settings) { settings = {}; } Pebble.openURL("http://rexmac.com/projects/pebble/chronocode/settings.html"); }); Pebble.addEventListener("webviewclosed", function(e) { var options = JSON.parse(decodeURIComponent(e.response)); if(Object.keys(options).length > 0) { window.localStorage.setItem("settings", JSON.stringify(options)); Pebble.sendAppMessage(options); } }) })(Pebble, window);
Fix incorrect usage of location replace code in reroute-verification initializer
import { getUrlParameter } from 'diesel/utils/url-parameters'; import Location from 'diesel/utils/location'; export function initialize(container, application) { application.deferReadiness(); var verificationCode = getUrlParameter(window.location, 'verification_code'); var invitationId = getUrlParameter(window.location, 'invitation_id'); var resetCode = getUrlParameter(window.location, 'reset_code'); var userId = getUrlParameter(window.location, 'user_id'); if (resetCode) { Location.replace(`/password/new/${resetCode}/${userId}`); } else if (invitationId) { Location.replace(`/claim/${invitationId}/${verificationCode}`); } else if (verificationCode) { Location.replace(`/verify/${verificationCode}`); } else { application.advanceReadiness(); } } export default { name: 'reroute-verification-code', initialize: initialize };
import { getUrlParameter } from '../utils/url-parameters'; import { replaceLocation } from '../utils/location'; export function initialize(container, application) { application.deferReadiness(); var verificationCode = getUrlParameter(window.location, 'verification_code'); var invitationId = getUrlParameter(window.location, 'invitation_id'); var resetCode = getUrlParameter(window.location, 'reset_code'); var userId = getUrlParameter(window.location, 'user_id'); if (resetCode) { replaceLocation(`/password/new/${resetCode}/${userId}`); } else if (invitationId) { replaceLocation(`/claim/${invitationId}/${verificationCode}`); } else if (verificationCode) { replaceLocation(`/verify/${verificationCode}`); } else { application.advanceReadiness(); } } export default { name: 'reroute-verification-code', initialize: initialize };
Use the correct process.config variable
var util = require('util'); var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.target_defaults.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
var util = require('util'); var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
Use same limit for on API requests
const fetch = require('node-fetch'); const baseURL = 'https://api.deutschebahn.com/bahnpark/v1'; class ParkingspaceLoader { constructor(APIToken) { this.APIToken = APIToken; } get fetchConfiguration() { const headers = { Authorization: `Bearer ${this.APIToken}`, }; const configuration = { method: 'GET', headers, }; return configuration; } spaceById(spaceId) { const url = `${baseURL}/spaces/${spaceId}`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } occupancyForId(spaceId) { const url = `${baseURL}/spaces/${spaceId}/occupancies`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } spacesForStationNumber(stationNumber) { const url = `${baseURL}/spaces?limit=1000`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } nearbyParkingspaces(latitude, longitude, radius) { const url = `${baseURL}/spaces?limit=1000`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()); } } module.exports = ParkingspaceLoader;
const fetch = require('node-fetch'); const baseURL = 'https://api.deutschebahn.com/bahnpark/v1'; class ParkingspaceLoader { constructor(APIToken) { this.APIToken = APIToken; } get fetchConfiguration() { const headers = { Authorization: `Bearer ${this.APIToken}`, }; const configuration = { method: 'GET', headers, }; return configuration; } spaceById(spaceId) { const url = `${baseURL}/spaces/${spaceId}`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } occupancyForId(spaceId) { const url = `${baseURL}/spaces/${spaceId}/occupancies`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } spacesForStationNumber(stationNumber) { const url = `${baseURL}/spaces?limit=1000`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()) } nearbyParkingspaces(latitude, longitude, radius) { const url = `${baseURL}/spaces?limit=100`; const configuration = this.fetchConfiguration; return fetch(url, configuration).then(res => res.json()); } } module.exports = ParkingspaceLoader;
Use json_build_object, rather than jsonb_build_object
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = json_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 16:20 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('councilmatic_core', '0040_mediaevent_meta'), ] operations = [ migrations.AddField( model_name='event', name='extras', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.RunSQL(''' UPDATE councilmatic_core_event SET extras = jsonb_build_object('guid', guid) WHERE guid IS NOT NULL ''', reverse_sql=''' UPDATE councilmatic_core_event SET guid = extras->'guid' WHERE extras->'guid' IS NOT NULL '''), migrations.RemoveField( model_name='event', name='guid', ), ]
Revert "Revert "log to file, don't email"" This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.
import logging from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from django.conf import settings logger = logging.getLogger('') class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) logger.error(warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN from corehq.util.soft_assert import soft_assert from django.conf import settings class HQCsrfViewMiddleWare(CsrfViewMiddleware): def _reject(self, request, reason): if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]: warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\ "Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\ "Read more here https://github.com/dimagi/commcare-hq/pull/9227".format( url=request.path ) _assert = soft_assert(notify_admins=True, exponential_backoff=True) _assert(False, warning) return self._accept(request) else: return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
Install tests along with the rest of the code
# coding=utf-8 from distutils.core import setup __version__ = 'unknown' with open('po_localization/version.py') as version_file: exec(version_file.read()) setup( name='po_localization', packages=['po_localization', 'po_localization.tests'], version=__version__, description='Localize Django applications without compiling .po files', author='Kevin Michel', author_email='kmichel.info@gmail.com', url='https://github.com/kmichel/po-localization', download_url='https://github.com/kmichel/po-localization/archive/v{}.tar.gz'.format(__version__), keywords=['django', 'localization'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Localization', ], requires=['django'], )
# coding=utf-8 from distutils.core import setup __version__ = 'unknown' with open('po_localization/version.py') as version_file: exec(version_file.read()) setup( name='po_localization', packages=['po_localization'], version=__version__, description='Localize Django applications without compiling .po files', author='Kevin Michel', author_email='kmichel.info@gmail.com', url='https://github.com/kmichel/po-localization', download_url='https://github.com/kmichel/po-localization/archive/v{}.tar.gz'.format(__version__), keywords=['django', 'localization'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Localization', ], requires=['django'], )
Use .get instead of accessing .data directly
var fill = require('flood-fill') module.exports = scan function scan(grid, opts) { opts = opts || {} var indexer = 'indexer' in opts ? functor(opts.indexer) : defaultIndexer , empty = opts.empty || defaultEmpty , limit = opts.limit || Infinity , length = grid.data.length , height = grid.shape[1] , width = grid.shape[0] , data = grid.data , metrics = [] , metric , idx = 0 , x, y top: for (x = 0; x < width; x += 1) for (y = 0; y < height; y += 1) { if (empty(grid.get(x, y))) { metric = fill(grid, x, y, indexer(idx++)) metric.start = [x, y] metrics.push(metric) if (idx > limit) break top } } return metrics } function functor(x) { if (typeof x === 'function') return x return function() { return x } } function defaultIndexer(x) { return x + 2 } function defaultEmpty(x) { return x === 0 }
var fill = require('flood-fill') module.exports = scan function scan(grid, opts) { opts = opts || {} var indexer = 'indexer' in opts ? functor(opts.indexer) : defaultIndexer , empty = opts.empty || defaultEmpty , limit = opts.limit || Infinity , length = grid.data.length , height = grid.shape[1] , width = grid.shape[0] , data = grid.data , metrics = [] , metric , idx = 0 , n = 0 , x, y top: for (x = 0; x < width; x += 1) for (y = 0; y < height; y += 1, n += 1) { if (empty(data[n])) { metric = fill(grid, x, y, indexer(idx++)) metric.start = [x, y] metrics.push(metric) if (idx > limit) break top } } return metrics } function functor(x) { if (typeof x === 'function') return x return function() { return x } } function defaultIndexer(x) { return x + 2 } function defaultEmpty(x) { return x === 0 }
BUG: Add the link to the element If the created element is not added to the current element, the download would not work on firefox
angular.module('clusterpost-list') .directive('clusterpostEsAdmin', function($routeParams,$location, clusterpostService){ function link($scope, $element, $attrs){ clusterpostService.getExecutionServerTokens() .then(function(res){ $scope.tokens = res.data; }) $scope.downloadToken = function(token){ var filename = "token.json"; var bb = new Blob([angular.toJson(token)], {type: 'text/plain'}); var pom = document.createElement('a'); $element.append(pom); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); } } return { restrict : 'E', link : link, scope:{ jobCallback: '=', appName: '=', downloadCallback: '=' }, templateUrl: './src/clusterpost-es-admin.directive.html' } });
angular.module('clusterpost-list') .directive('clusterpostEsAdmin', function($routeParams,$location, clusterpostService){ function link($scope,$attrs){ clusterpostService.getExecutionServerTokens() .then(function(res){ $scope.tokens = res.data; }) $scope.downloadToken = function(token){ var pom = document.createElement('a'); var filename = "token.json"; var pom = document.createElement('a'); var bb = new Blob([angular.toJson(token)], {type: 'text/plain'}); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); } } return { restrict : 'E', link : link, scope:{ jobCallback: '=', appName: '=', downloadCallback: '=' }, templateUrl: './src/clusterpost-es-admin.directive.html' } });
Set text of option tag When value attribute is set, display after selection becomes value value
'use strict'; import $ from 'jquery'; export default class BasisSelect { constructor() { this.select = $('[data-c="select"]'); this.select.each((i, e) => { const selectWrapper = $(e); const select = selectWrapper.find('select'); const label = selectWrapper.find('[data-c="select__label"]'); label.text(select.children('option:selected').text()); select.on('change', (event) => { label.text($(select[0].selectedOptions).text()); }); select.on('focusin', (event) => { selectWrapper.attr('aria-selected', 'true'); }); select.on('focusout', (event) => { selectWrapper.attr('aria-selected', 'false'); }); }); } }
'use strict'; import $ from 'jquery'; export default class BasisSelect { constructor() { this.select = $('[data-c="select"]'); this.select.each((i, e) => { const selectWrapper = $(e); const select = selectWrapper.find('select'); const label = selectWrapper.find('[data-c="select__label"]'); label.text(select.children('option:selected').val()); select.on('change', (event) => { label.text(select.val()); }); select.on('focusin', (event) => { selectWrapper.attr('aria-selected', 'true'); }); select.on('focusout', (event) => { selectWrapper.attr('aria-selected', 'false'); }); }); } }
Add currency symbol to price information response
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const fuzz = require('fuzzball') async function productPrice (query, user) { const [products] = await models.sequelize.query('SELECT * FROM Products') const queriedProducts = products .filter((product) => fuzz.partial_ratio(query, product.name) > 75) .map((product) => `${product.name}: ${product.price}¤`) return { action: 'response', body: queriedProducts.length > 0 ? queriedProducts.join(` `) : 'Sorry I couldn\'t find any products with that name' } } function testFunction (query, user) { return { action: 'response', body: '3be2e438b7f3d04c89d7749f727bb3bd' } } module.exports = { productPrice, testFunction }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const fuzz = require('fuzzball') async function productPrice (query, user) { const [products] = await models.sequelize.query('SELECT * FROM Products') const queriedProducts = products .filter((product) => fuzz.partial_ratio(query, product.name) > 75) .map((product) => `${product.name}: ${product.price}`) return { action: 'response', body: queriedProducts.length > 0 ? queriedProducts.join(` `) : 'Sorry I couldn\'t find any products with that name' } } function testFunction (query, user) { return { action: 'response', body: '3be2e438b7f3d04c89d7749f727bb3bd' } } module.exports = { productPrice, testFunction }
Fix LoadHook dropping snapshot incorrectly.
package me.nallar.modpatcher; import me.nallar.javatransformer.api.JavaTransformer; class ModPatcherLoadHook { private static final int API_VERSION = 1; //Keep in sync with version in ModPatcher.java private static final String VERSION = "@MOD_VERSION@"; static void loadHook(ModPatcher.Version requiredVersion, String modPatcherRelease, int apiVersion) { PatcherLog.info("Loaded ModPatcher. Version: @MOD_VERSION@ API version: " + API_VERSION); if (API_VERSION != apiVersion) { PatcherLog.warn("API version mismatch. Expected " + API_VERSION + ", got " + apiVersion); PatcherLog.warn("API was loaded from: " + JavaTransformer.pathFromClass(ModPatcher.class)); } ModPatcher.Version current = ModPatcher.Version.of(VERSION); if (requiredVersion != ModPatcher.Version.LATEST && current.compareTo(requiredVersion) < 0) { String autoUpdate = "\nWill auto-update on next start."; if (ModPatcher.neverUpdate()) autoUpdate = ""; else JavaTransformer.pathFromClass(ModPatcherTransformer.class).toFile().deleteOnExit(); throw new RuntimeException("ModPatcher outdated. Have version: " + VERSION + ", requested version: " + requiredVersion + autoUpdate); } } }
package me.nallar.modpatcher; import me.nallar.javatransformer.api.JavaTransformer; class ModPatcherLoadHook { private static final int API_VERSION = 1; //Keep in sync with version in ModPatcher.java private static final String VERSION = "@MOD_VERSION@".replace("-SNAPSHOT", ""); static void loadHook(ModPatcher.Version requiredVersion, String modPatcherRelease, int apiVersion) { PatcherLog.info("Loaded ModPatcher. Version: @MOD_VERSION@ API version: " + API_VERSION); if (API_VERSION != apiVersion) { PatcherLog.warn("API version mismatch. Expected " + API_VERSION + ", got " + apiVersion); PatcherLog.warn("API was loaded from: " + JavaTransformer.pathFromClass(ModPatcher.class)); } ModPatcher.Version current = ModPatcher.Version.of(VERSION); if (requiredVersion != ModPatcher.Version.LATEST && current.compareTo(requiredVersion) < 0) { String autoUpdate = "\nWill auto-update on next start."; if (ModPatcher.neverUpdate()) autoUpdate = ""; else JavaTransformer.pathFromClass(ModPatcherTransformer.class).toFile().deleteOnExit(); throw new RuntimeException("ModPatcher outdated. Have version: " + VERSION + ", requested version: " + requiredVersion + autoUpdate); } } }
[Eigen] Add alternative site assocation path.
var artsyEigenWebAssociation = require('artsy-eigen-web-association'); var express = require('express'); var https = require('https'); var http = require('http'); var morgan = require('morgan'); var path = require('path'); var fs = require('fs'); var app = express(); app.use(morgan('combined')); app.use('/(.well-known/)?apple-app-site-association', artsyEigenWebAssociation); app.use(function(req, res, next) { res.setHeader('Strict-Transport-Security', 'max-age=0'); res.redirect(301, 'https://www.artsy.net' + req.url); }); http.createServer(app).listen(80); https.createServer({ key: fs.readFileSync('/srv/www/artsy_wwwify/shared/config/ssl.key').toString(), cert: fs.readFileSync('/srv/www/artsy_wwwify/shared/config/ssl.crt').toString() }, app).listen(443);
var artsyEigenWebAssociation = require('artsy-eigen-web-association'); var express = require('express'); var https = require('https'); var http = require('http'); var morgan = require('morgan'); var path = require('path'); var fs = require('fs'); var app = express(); app.use(morgan('combined')); app.use('/apple-app-site-association', artsyEigenWebAssociation); app.use(function(req, res, next) { res.setHeader('Strict-Transport-Security', 'max-age=0'); res.redirect(301, 'https://www.artsy.net' + req.url); }); http.createServer(app).listen(80); https.createServer({ key: fs.readFileSync('/srv/www/artsy_wwwify/shared/config/ssl.key').toString(), cert: fs.readFileSync('/srv/www/artsy_wwwify/shared/config/ssl.crt').toString() }, app).listen(443);
Add back the stable_build variable which is needed in the _revert_settings() function. Woops.
from fabric.api import * from fabric.contrib.files import sed import random import string import time # Custom Code Enigma modules import Drupal import common.MySQL # Small function to revert db @task @roles('app_primary') def _revert_db(repo, branch, build, buildtype, site): print "===> Reverting the database..." drush_runtime_location = "/var/www/live.%s.%s/www/sites/%s" % (repo, branch, site) drush_output = Drupal.drush_status(repo, branch, build, buildtype, site, drush_runtime_location) db_name = Drupal.get_db_name(repo, branch, build, buildtype, site, drush_output) common.MySQL.mysql_revert_db(db_name, build) # Function to revert settings.php change for when a build fails and database is reverted @task @roles('app_all') def _revert_settings(repo, branch, build, buildtype, site, alias): print "===> Reverting the settings..." with settings(warn_only=True): stable_build = run("readlink /var/www/live.%s.%s" % (repo, branch)) if sudo('sed -i.bak "s:/var/www/.*\.settings\.php:%s/www/sites/%s/%s.settings.php:g" %s' % (stable_build, site, buildtype, settings_file)).failed: print "===> Could not revert settings.php. Manual intervention required." else: print "===> Reverted settings.php"
from fabric.api import * from fabric.contrib.files import sed import random import string import time # Custom Code Enigma modules import Drupal import common.MySQL # Small function to revert db @task @roles('app_primary') def _revert_db(repo, branch, build, buildtype, site): print "===> Reverting the database..." drush_runtime_location = "/var/www/live.%s.%s/www/sites/%s" % (repo, branch, site) drush_output = Drupal.drush_status(repo, branch, build, buildtype, site, drush_runtime_location) db_name = Drupal.get_db_name(repo, branch, build, buildtype, site, drush_output) common.MySQL.mysql_revert_db(db_name, build) # Function to revert settings.php change for when a build fails and database is reverted @task @roles('app_all') def _revert_settings(repo, branch, build, buildtype, site, alias): print "===> Reverting the settings..." with settings(warn_only=True): if sudo('sed -i.bak "s:/var/www/.*\.settings\.php:%s/www/sites/%s/%s.settings.php:g" %s' % (stable_build, site, buildtype, settings_file)).failed: print "===> Could not revert settings.php. Manual intervention required." else: print "===> Reverted settings.php"
Fix declaration of ClearMask bitmasks.
package gfx // ClearMask represents a bitmask to choose which buffers to clear during a // framebuffer clearing operation. It must be one of the predefined constants. type ClearMask int // Clearing masks to select the color, depth, and stencil buffers. They can be // bitwise OR'd together to select multiple: // // colorAndDepth := ColorBufer|DepthBuffer // const ( ColorBuffer ClearMask = 1 << iota DepthBuffer StencilBuffer ) // Clearable represents the clearing state and API of a framebuffer object. type Clearable interface { // ClearColor sets the color to clear the color buffer to upon a call to // the Clear method. ClearColor(r, g, b, a float32) // ClearDepth sets the value to clear the depth buffer to upon a depth // buffer clearing operation (a call to Clear with the DepthBuffer clear // mask) ClearDepth(depth float32) // ClearStencil sets the value to clear the stencil buffer to upon a // stencil buffer clearing operation (a call to Clear with the // StencilBuffer clear mask) ClearStencil(stencil int) // Clear clears the buffers selected by the bitmask to their respective // clear values. Multiple bitmasks can be OR'd together to select multiple // buffers to clear at once: // // // Clear both(!) the color and depth buffers in one call. // Clear(ColorBuffer|DepthBuffer) // Clear(m ClearMask) }
package gfx // ClearMask represents a bitmask to choose which buffers to clear during a // framebuffer clearing operation. It must be one of the predefined constants. type ClearMask int // Clearing masks to select the color, depth, and stencil buffers. They can be // bitwise OR'd together to select multiple: // // colorAndDepth := ColorBufer|DepthBuffer // const ( ColorBuffer ClearMask = iota DepthBuffer StencilBuffer ) // Clearable represents the clearing state and API of a framebuffer object. type Clearable interface { // ClearColor sets the color to clear the color buffer to upon a call to // the Clear method. ClearColor(r, g, b, a float32) // ClearDepth sets the value to clear the depth buffer to upon a depth // buffer clearing operation (a call to Clear with the DepthBuffer clear // mask) ClearDepth(depth float32) // ClearStencil sets the value to clear the stencil buffer to upon a // stencil buffer clearing operation (a call to Clear with the // StencilBuffer clear mask) ClearStencil(stencil int) // Clear clears the buffers selected by the bitmask to their respective // clear values. Multiple bitmasks can be OR'd together to select multiple // buffers to clear at once: // // // Clear both(!) the color and depth buffers in one call. // Clear(ColorBuffer|DepthBuffer) // Clear(m ClearMask) }
Remove space from generated unit-tests
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %> // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %> import hbs from 'htmlbars-inline-precompile';<% } %> moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', { <% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'], unit: true<% } %> }); test('it renders', function(assert) { <% if (testType === 'integration' ) { %>// Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{<%= componentPathName %>}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#<%= componentPathName %>}} template block text {{/<%= componentPathName %>}} `); assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %> // Creates the component instance /*let component =*/ this.subject(); // Renders the component to the page this.render(); assert.equal(this.$().text().trim(), '');<% } %> });
Use request library to hit the giphy api, passing serialized params object.
'use strict'; /** * @description * A tool that downloads a given number of pug images to the directory where it is run. * * @example * node pugbalm 5 // download 5 pugs */ var request = require('request'), _ = require('lodash'), baseUrl = 'http://api.giphy.com/v1/gifs/search', apiKey = 'dc6zaTOxFJmzC', params; /* * @jsdoc function * @name serializeParams * @param {object} * Object containing request parameters. * @returns {string} * Accepts a params object and returns a serialized string to be appended to a base URL. */ params = { q: 'pugs', api_key: apiKey, }; function serializeParams(params) { var first = true; return _.reduce(params, function(result, n, key) { if (first) { first = false; return result + '?' + key + '=' + n; } else { return result + '&' + key + '=' + n; } },''); } request(baseUrl + serializeParams(params), function(error, response, body) { if (!error && response.statusCode === 200) { debugger; } });
'use strict'; /** * @description * A tool that downloads a given number of pug images to the directory where it is run. * * @example * node pugbalm 5 // download 5 pugs */ var request = require('request'), _ = require('lodash'), apiKey = 'dc6zaTOxFJmzC', params; /* * @jsdoc function * @name serializeParams * @param {object} * Object containing request parameters. * @returns {string} * Accepts a params object and returns a serialized string to be appended to a base URL. */ params = { q: 'pugs', api_key: apiKey, }; function serializeParams(params) { return _.reduce(params, function(result, n, key) { return result + key + n; },''); } console.log(serializeParams(params));
Remove unused |date| array variables
import plotly as py import plotly.graph_objs as go from datetime import datetime from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h dt = datetime.combine(date, datetime.min.time()) sleep_durations.append(sleep_total) nap_durations.append(nap_total) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
import plotly as py import plotly.graph_objs as go from datetime import datetime from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] sleep_dates = [] nap_durations = [] nap_dates = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap = r delta_h = (wake - rest).seconds / 3600 if is_nap: nap_total += delta_h else: sleep_total += delta_h dt = datetime.combine(date, datetime.min.time()) sleep_durations.append(sleep_total) sleep_dates.append(dt) nap_durations.append(nap_total) nap_dates.append(dt) dates = list(raw_data.keys()) sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration') nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration') data = go.Data([sleep_trace, nap_trace]) layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates), yaxis={'title': 'Hours Slept', 'dtick': 1}) figure = go.Figure(data=data, layout=layout) py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
[selenium] ENHANCE - improve Close Window icon
package org.museautomation.selenium.steps; import org.museautomation.core.*; import org.museautomation.core.context.*; import org.museautomation.core.step.*; import org.museautomation.core.step.descriptor.*; /** * @author Christopher L Merrill (see LICENSE.txt for license details) */ @MuseTypeId("close-window") @MuseStepName("Close Window") @MuseInlineEditString("Close current window") @MuseStepIcon("glyph:FontAwesome:WINDOW_CLOSE_ALT") @MuseStepTypeGroup("Selenium.Window") @MuseStepShortDescription("Close the current browser tab and/or window") @MuseStepLongDescription("Closes the current browser tab or window. If it is the last tab/window opened, it will shutdown the browser.") @SuppressWarnings("unused") // discovered and instantiated via reflection public class CloseWindow extends BrowserStep { @SuppressWarnings("unused") // called via reflection public CloseWindow(StepConfiguration config, MuseProject project) { super(config); } @Override public StepExecutionResult executeImplementation(StepExecutionContext context) throws MuseExecutionError { getDriver(context).close(); return new BasicStepExecutionResult(StepExecutionStatus.COMPLETE); } public final static String TYPE_ID = CloseWindow.class.getAnnotation(MuseTypeId.class).value(); }
package org.museautomation.selenium.steps; import org.museautomation.core.*; import org.museautomation.core.context.*; import org.museautomation.core.resource.*; import org.museautomation.core.step.*; import org.museautomation.core.step.descriptor.*; import org.museautomation.core.values.descriptor.*; /** * @author Christopher L Merrill (see LICENSE.txt for license details) */ @MuseTypeId("close-window") @MuseStepName("Close Window") @MuseInlineEditString("Close current window") @MuseStepIcon("glyph:FontAwesome:WINDOW_CLOSE") @MuseStepTypeGroup("Selenium.Window") @MuseStepShortDescription("Close the current browser tab and/or window") @MuseStepLongDescription("Closes the current browser tab or window. If it is the last tab/window opened, it will shutdown the browser.") public class CloseWindow extends BrowserStep { @SuppressWarnings("unused") // called via reflection public CloseWindow(StepConfiguration config, MuseProject project) { super(config); } @Override public StepExecutionResult executeImplementation(StepExecutionContext context) throws MuseExecutionError { getDriver(context).close(); return new BasicStepExecutionResult(StepExecutionStatus.COMPLETE); } public final static String TYPE_ID = CloseWindow.class.getAnnotation(MuseTypeId.class).value(); }
Fix tests for Django 1.8
import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.loader.get_template_from_string( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
Add guard for parallel kwarg on 32-bit Windows
import sys from hypothesis import given from hypothesis.strategies import integers from numba import jit import numpy as np # Parallel not supported on 32-bit Windows parallel = not (sys.platform == 'win32') @jit(nopython=True, parallel=True) def get(n): return np.ones((n,1), dtype=np.float64) @given(integers(min_value=10, max_value=100000)) def test_all_ones(x): """ We found one of the scaling tests failing on OS X with numba 0.35, but it passed on other platforms, and passed consistently with numba 0.36. The issue appears to be the same as numba#2609 https://github.com/numba/numba/issues/2609 so we've taken the minimal repro from that issue and are using it as a unit-test here. """ result = get(x) expected = np.ones((x, 1), dtype=np.float64) assert np.allclose(expected, result) if __name__ == '__main__': import pytest pytest.main([__file__])
from hypothesis import given from hypothesis.strategies import integers from numba import jit import numpy as np @jit(nopython=True, parallel=True) def get(n): return np.ones((n,1), dtype=np.float64) @given(integers(min_value=10, max_value=100000)) def test_all_ones(x): """ We found one of the scaling tests failing on OS X with numba 0.35, but it passed on other platforms, and passed consistently with numba 0.36. The issue appears to be the same as numba#2609 https://github.com/numba/numba/issues/2609 so we've taken the minimal repro from that issue and are using it as a unit-test here. """ result = get(x) expected = np.ones((x, 1), dtype=np.float64) assert np.allclose(expected, result) if __name__ == '__main__': import pytest pytest.main([__file__])
Load current tab from url hash
export class Tabs { initEventListeners () { this.loadTab() $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.href) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.href.split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } loadTab () { let url = document.location.toString() if (url.match('#')) { let anchor = '#' + url.split('#')[1] if ($('.nav-tabs a[href=' + anchor + ']').length > 0) { $('.nav-tabs a[href=' + anchor + ']').tab('show') } } } }
export class Tabs { initEventListeners () { $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.href) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.href.split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } }
Make figure a bit better
# -*- coding: utf-8 -*- """ pylatex.graphics ~~~~~~~~~~~~~~~~ This module implements the class that deals with graphics. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from .utils import fix_filename from .base_classes import BaseLaTeXNamedContainer from .package import Package from .command import Command class Figure(BaseLaTeXNamedContainer): """A class that represents a Graphic.""" def __init__(self, data=None, position=None): packages = [Package('graphicx')] super().__init__('figure', data=data, packages=packages, options=position) def add_image(self, filename, width=r'0.8\textwidth', placement=r'\centering'): if placement is not None: self.append(placement) if width is not None: width = 'width=' + str(width) self.append(Command('includegraphics', options=width, arguments=fix_filename(filename))) def add_caption(self, caption): """Add a caption to the figure""" self.append(Command('caption', caption))
# -*- coding: utf-8 -*- """ pylatex.graphics ~~~~~~~~~~~~~~~~ This module implements the class that deals with graphics. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from .utils import fix_filename from .base_classes import BaseLaTeXNamedContainer from .package import Package from .command import Command class Figure(BaseLaTeXNamedContainer): """A class that represents a Graphic.""" def __init__(self, data=None, position=None): packages = [Package('graphicx')] super().__init__('figure', data=data, packages=packages, options=position) def add_image(self, filename, width=r'0.8\textwidth', placement=r'\centering'): if placement is not None: self.append(placement) self.append(Command('includegraphics', options='width=' + width, arguments=fix_filename(filename))) def add_caption(self, caption): """Add a caption to the figure""" self.append(Command('caption', caption))
Set specific branch to go to in GitHub
import sublime import sublime_plugin import webbrowser def cleanPackage(pkgURI): pkg = pkgURI.split('.com/')[1] return pkg class GoDocGetCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view for region in view.sel(): selected = view.substr(region) if "github.corp" in selected: # if corporate go to page on master branch pkg = cleanPackage(selected) res = pkg.split('/') res.insert(2, 'tree/master') pkg = '/'.join(res) webbrowser.open('https://github.corp.dyndns.com/' + pkg) elif "github" in selected: # if public package go to doc pkg = cleanPackage(selected) webbrowser.open('https://godoc.org/github.com/' + pkg) else: # default to golang proper webbrowser.open('https://golang.org/pkg/' + selected)
import sublime import sublime_plugin import webbrowser def cleanPackage(pkgURI): pkg = pkgURI.split('.com/')[1] return pkg class GoDocGetCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view for region in view.sel(): selected = view.substr(region) if "github.corp" in selected: # if corporate go to page pkg = cleanPackage(selected) webbrowser.open('https://github.corp.dyndns.com/' + pkg) elif "github" in selected: # if public package go to doc pkg = cleanPackage(selected) webbrowser.open('https://godoc.org/github.com/' + pkg) else: # default to golang proper webbrowser.open('https://golang.org/pkg/' + selected)
Disable entry of cities outside of database. Add a try-except to prevent entry of city name which is not in the database.
from django import forms from django.conf import settings from moviealert.base.widgets import CalendarWidget from .models import TaskList, RegionData class MovieForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MovieForm, self).__init__(*args, **kwargs) self.fields['movie_date'] = forms.DateField( widget=CalendarWidget(attrs={"readonly": "readonly", "style": "background:white;"}), input_formats=settings.ALLOWED_DATE_FORMAT) self.fields["city"] = forms.CharField( widget=forms.TextInput(attrs={"id": "txtSearch"})) self.fields["city"].label = "City Name" def clean(self): cleaned_data = super(MovieForm, self).clean() try: cleaned_data['city'] = RegionData.objects.get( bms_city=cleaned_data['city']) except RegionData.DoesNotExist: self.add_error("city", "Select only values from autocomplete!") class Meta: model = TaskList exclude = ("username", "task_completed", "notified", "movie_found",)
from django import forms from django.conf import settings from moviealert.base.widgets import CalendarWidget from .models import TaskList, RegionData class MovieForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MovieForm, self).__init__(*args, **kwargs) self.fields['movie_date'] = forms.DateField( widget=CalendarWidget(attrs={"readonly": "readonly", "style": "background:white;"}), input_formats=settings.ALLOWED_DATE_FORMAT) self.fields["city"] = forms.CharField( widget=forms.TextInput(attrs={"id": "txtSearch"})) self.fields["city"].label = "City Name" def clean(self): cleaned_data = super(MovieForm, self).clean() cleaned_data['city'] = RegionData.objects.get( bms_city=cleaned_data['city']) class Meta: model = TaskList exclude = ("username", "task_completed", "notified", "movie_found",)
Add my own public IP address to INTERNAL_IPS for `obi` testing.
# Debug-toolbar related INSTALLED_APPS += ('debug_toolbar', ) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) INTERNAL_IPS = ( '127.0.0.1', # leto.licorn.org '82.236.133.193', ) DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel', 'debug_toolbar.panels.template.TemplateDebugPanel', 'debug_toolbar.panels.logger.LoggingPanel', 'debug_toolbar.panels.sql.SQLDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.signals.SignalDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.version.VersionDebugPanel', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'ENABLE_STACKTRACES' : True, #'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar, #'EXTRA_SIGNALS': ['myproject.signals.MySignal'], #'HIDE_DJANGO_SQL': False, #'TAG': 'div', }
# Debug-toolbar related INSTALLED_APPS += ('debug_toolbar', ) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', ) INTERNAL_IPS = ('127.0.0.1', ) DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel', 'debug_toolbar.panels.template.TemplateDebugPanel', 'debug_toolbar.panels.logger.LoggingPanel', 'debug_toolbar.panels.sql.SQLDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.signals.SignalDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.version.VersionDebugPanel', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'ENABLE_STACKTRACES' : True, #'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar, #'EXTRA_SIGNALS': ['myproject.signals.MySignal'], #'HIDE_DJANGO_SQL': False, #'TAG': 'div', }
Add hash for schedule slot color
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { Link } from 'react-router-dom'; import ScheduleSlotTime from './ScheduleSlotTime'; function ScheduleSlot(props) { const slot = props.slot; const show = props.slot.show; const scheduleSlotClasses = cx( 'ScheduleSlot', `ScheduleSlot--tone-${show.tone === 'dark' ? 'dark' : 'light'}`, { 'ScheduleSlot--overnight': slot.is_overnight, 'ScheduleSlot--on-air': props.onAir, } ); return ( <div className={scheduleSlotClasses} style={{ width: props.calculateWidth(slot.duration) }} > <Link className="ScheduleSlot__inner" style={{ backgroundColor: `#${show.brandColor}` }} to={`/shows/${show.slug}`} > <ScheduleSlotTime slot={slot} onAir={props.onAir} index={props.index} /> <div className="ScheduleSlot__title"> {show.name} </div> </Link> </div> ); } ScheduleSlot.propTypes = { calculateWidth: PropTypes.func.isRequired, onAir: PropTypes.bool.isRequired, slot: PropTypes.object.isRequired, index: PropTypes.number.isRequired, }; export default ScheduleSlot;
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { Link } from 'react-router-dom'; import ScheduleSlotTime from './ScheduleSlotTime'; function ScheduleSlot(props) { const slot = props.slot; const show = props.slot.show; const scheduleSlotClasses = cx( 'ScheduleSlot', `ScheduleSlot--tone-${show.tone === 'dark' ? 'dark' : 'light'}`, { 'ScheduleSlot--overnight': slot.is_overnight, 'ScheduleSlot--on-air': props.onAir, } ); return ( <div className={scheduleSlotClasses} style={{ width: props.calculateWidth(slot.duration) }} > <Link className="ScheduleSlot__inner" style={{ backgroundColor: show.brandColor }} to={`/shows/${show.slug}`} > <ScheduleSlotTime slot={slot} onAir={props.onAir} index={props.index} /> <div className="ScheduleSlot__title"> {show.name} </div> </Link> </div> ); } ScheduleSlot.propTypes = { calculateWidth: PropTypes.func.isRequired, onAir: PropTypes.bool.isRequired, slot: PropTypes.object.isRequired, index: PropTypes.number.isRequired, }; export default ScheduleSlot;
Add sparse-avg suffix to metrics name This enables us to see this metric even when specifying a time window of more than 24h in logmet. Signed-off-by: Alexander Egurnov <7763625750474092f7412e5c40b7d702fa97cda8@de.ibm.com>
package main_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/cloudfoundry-incubator/cf-test-helpers/generator" "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" ) var _ = Describe("Pushing an app", func() { It("stops the time for pushing an app", func() { for index := 0; index < loopCount; index++ { startTime := time.Now() appName := generator.PrefixedRandomName("APP") Expect( cf.Cf("push", appName, "-p", "assets/dora").Wait(cfPushTimeout)). To(Exit(0)) statsdClient.Timing(asSparseMetric("cf-push"), time.Since(startTime).Seconds()*1000) } }) }) func asSparseMetric(metricName string) string { return metricsPrefix + metricName + ".sparse-avg" }
package main_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/cloudfoundry-incubator/cf-test-helpers/generator" "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" ) var _ = Describe("Pushing an app", func() { It("stops the time for pushing an app", func() { for index := 0; index < loopCount; index++ { startTime := time.Now() appName := generator.PrefixedRandomName("APP") Expect( cf.Cf("push", appName, "-p", "assets/dora").Wait(cfPushTimeout)). To(Exit(0)) statsdClient.Timing(metricsPrefix+"cf-push", time.Since(startTime).Seconds()*1000) } }) })
Remove this, use only enable, for Machine learning persist (I114).
package roart.iclij.config; public class MLConfig { // load before evolve or use private Boolean load; // enable evolve or use private Boolean enable; public Boolean getLoad() { return load; } public void setLoad(Boolean load) { this.load = load; } public Boolean getEnable() { return enable; } public void setEnable(Boolean enable) { this.enable = enable; } public void merge(MLConfig other) { if (other == null) { return; } if (other.load != null) { this.load = other.load; } if (other.enable != null) { this.enable = other.enable; } } }
package roart.iclij.config; public class MLConfig { // load before evolve or use private Boolean load; // enable evolve or use private Boolean enable; // ml persistence private Boolean persistml; public Boolean getLoad() { return load; } public void setLoad(Boolean load) { this.load = load; } public Boolean getEnable() { return enable; } public void setEnable(Boolean enable) { this.enable = enable; } public Boolean getPersistml() { return persistml; } public void setPersistml(Boolean persistml) { this.persistml = persistml; } public void merge(MLConfig other) { if (other == null) { return; } if (other.load != null) { this.load = other.load; } if (other.enable != null) { this.enable = other.enable; } } }
Clean up dependencies (no importlib)
#!/usr/bin/env python import os from setuptools import setup, find_packages from version import get_git_version VERSION, SOURCE_LABEL = get_git_version() PROJECT = 'yakonfig' AUTHOR = 'Diffeo, Inc.' AUTHOR_EMAIL = 'support@diffeo.com' URL = 'http://github.com/diffeo/yakonfig' DESC = 'load a configuration dictionary for a large application' def read_file(file_name): with open(os.path.join(os.path.dirname(__file__), file_name), 'r') as f: return f.read() setup( name=PROJECT, version=VERSION, description=DESC, license=read_file('LICENSE.txt'), long_description=read_file('README.md'), # source_label=SOURCE_LABEL, author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, packages=find_packages(), classifiers=[ 'Programming Language :: Python :: 2.7', 'Development Status :: 3 - Alpha', 'Topic :: Utilities', # MIT/X11 license http://opensource.org/licenses/MIT 'License :: OSI Approved :: MIT License', ], install_requires=[ 'pyyaml', 'six', ], )
#!/usr/bin/env python import os from setuptools import setup, find_packages from version import get_git_version VERSION, SOURCE_LABEL = get_git_version() PROJECT = 'yakonfig' AUTHOR = 'Diffeo, Inc.' AUTHOR_EMAIL = 'support@diffeo.com' URL = 'http://github.com/diffeo/yakonfig' DESC = 'load a configuration dictionary for a large application' def read_file(file_name): with open(os.path.join(os.path.dirname(__file__), file_name), 'r') as f: return f.read() setup( name=PROJECT, version=VERSION, description=DESC, license=read_file('LICENSE.txt'), long_description=read_file('README.md'), # source_label=SOURCE_LABEL, author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, packages=find_packages(), classifiers=[ 'Programming Language :: Python :: 2.7', 'Development Status :: 3 - Alpha', 'Topic :: Utilities', # MIT/X11 license http://opensource.org/licenses/MIT 'License :: OSI Approved :: MIT License', ], tests_require=[ 'pexpect', ], install_requires=[ 'importlib', 'pyyaml', 'six', ], )
Update doc upload task w/ static hostname
from fabric.api import task, sudo, env, local, hosts from fabric.contrib.project import rsync_project from fabric.contrib.console import confirm @task @hosts("paramiko.org") def upload_docs(): target = "/var/www/paramiko.org" staging = "/tmp/paramiko_docs" sudo("mkdir -p %s" % staging) sudo("chown -R %s %s" % (env.user, staging)) sudo("rm -rf %s/*" % target) rsync_project(local_dir='docs/', remote_dir=staging, delete=True) sudo("cp -R %s/* %s/" % (staging, target)) @task def build_docs(): local("epydoc --no-private -o docs/ paramiko") @task def clean(): local("rm -rf build dist docs") local("rm -f MANIFEST *.log demos/*.log") local("rm -f paramiko/*.pyc") local("rm -f test.log") local("rm -rf paramiko.egg-info") @task def test(): local("python ./test.py") @task def release(): confirm("Only hit Enter if you remembered to update the version!") build_docs() local("python setup.py sdist register upload") upload_docs()
from fabric.api import task, sudo, env, local from fabric.contrib.project import rsync_project from fabric.contrib.console import confirm @task def upload_docs(): target = "/var/www/paramiko.org" staging = "/tmp/paramiko_docs" sudo("mkdir -p %s" % staging) sudo("chown -R %s %s" % (env.user, staging)) sudo("rm -rf %s/*" % target) rsync_project(local_dir='docs/', remote_dir=staging, delete=True) sudo("cp -R %s/* %s/" % (staging, target)) @task def build_docs(): local("epydoc --no-private -o docs/ paramiko") @task def clean(): local("rm -rf build dist docs") local("rm -f MANIFEST *.log demos/*.log") local("rm -f paramiko/*.pyc") local("rm -f test.log") local("rm -rf paramiko.egg-info") @task def test(): local("python ./test.py") @task def release(): confirm("Only hit Enter if you remembered to update the version!") build_docs() local("python setup.py sdist register upload") upload_docs()
Use Ninja not NinjaDefault. Log filtered authenticity requests.
package ninja; import ninja.utils.NinjaConstant; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author svenkubiak * */ public class AuthenticityFilter implements Filter { static private final Logger logger = LoggerFactory.getLogger(AuthenticityFilter.class); private final Ninja ninja; @Inject public AuthenticityFilter(Ninja ninja) { this.ninja = ninja; } @Override public Result filter(FilterChain filterChain, Context context) { String authenticityToken = context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN); if (!context.getSession().getAuthenticityToken().equals(authenticityToken)) { logger.warn("Authenticity token mismatch. Request from {} is forbidden!", context.getRemoteAddr()); return ninja.getForbiddenResult(context); } return filterChain.next(context); } }
package ninja; import ninja.utils.NinjaConstant; import com.google.inject.Inject; /** * * @author svenkubiak * */ public class AuthenticityFilter implements Filter { private NinjaDefault ninjaDefault; @Inject public AuthenticityFilter(NinjaDefault ninjaDefault) { this.ninjaDefault = ninjaDefault; } @Override public Result filter(FilterChain filterChain, Context context) { String authenticityToken = context.getParameter(NinjaConstant.AUTHENTICITY_TOKEN); if (!context.getSession().getAuthenticityToken().equals(authenticityToken)) { return ninjaDefault.getForbiddenResult(context); } return filterChain.next(context); } }
Make test data more unique to avoid overlap
const DOMAIN = 'foo.bar'; export const UNKNOWN = { status: 999, statusText: 'Unknown - something unexpected happened.', }; export const ERR = new Error('Set sail for fail!'); export const INVALID_HEADER = 'baz'; export const RATE_LIMITED = 'quux'; export const UNEXPECTED = 'qux'; export const ACCOUNT_BREACHED = 'foo123'; export const ACCOUNT_CLEAN = 'bar123'; export const BREACH_FOUND = 'foo456'; export const BREACH_NOT_FOUND = 'bar456'; export const EMAIL_PASTED = 'foo789@bar.com'; export const EMAIL_CLEAN = 'baz789@qux.com'; export const EMAIL_INVALID = 'foobar'; export const OPTS_DOM = { domain: DOMAIN }; export const OPTS_TRUNC = { truncate: true }; export const OPTS_DOM_TRUNC = { domain: DOMAIN, truncate: true }; export const RESPONSE_OBJ = {}; export const RESPONSE_ARY = []; export const RESPONSE_CLEAN = null;
const DOMAIN = 'foo.bar'; export const UNKNOWN = { status: 999, statusText: 'Unknown - something unexpected happened.', }; export const ERR = new Error('Set sail for fail!'); export const INVALID_HEADER = 'baz'; export const RATE_LIMITED = 'quux'; export const UNEXPECTED = 'qux'; export const ACCOUNT_BREACHED = 'foo'; export const ACCOUNT_CLEAN = 'bar'; export const BREACH_FOUND = 'foo'; export const BREACH_NOT_FOUND = 'bar'; export const EMAIL_PASTED = 'foo@bar.com'; export const EMAIL_CLEAN = 'baz@qux.com'; export const EMAIL_INVALID = 'foobar'; export const OPTS_DOM = { domain: DOMAIN }; export const OPTS_TRUNC = { truncate: true }; export const OPTS_DOM_TRUNC = { domain: DOMAIN, truncate: true }; export const RESPONSE_OBJ = {}; export const RESPONSE_ARY = []; export const RESPONSE_CLEAN = null;
Return 502 when NCBI unavailable
""" Provides request handlers for managing and viewing analyses. """ import aiohttp import aiohttp.client_exceptions import virtool.genbank import virtool.http.proxy import virtool.http.routes from virtool.api.utils import bad_gateway, json_response, not_found routes = virtool.http.routes.Routes() @routes.get("/api/genbank/{accession}") async def get(req): """ Retrieve the Genbank data associated with the given accession and transform it into a Virtool-style sequence document. """ accession = req.match_info["accession"] session = req.app["client"] settings = req.app["settings"] try: data = await virtool.genbank.fetch(settings, session, accession) if data is None: return not_found() return json_response(data) except aiohttp.client_exceptions.ClientConnectorError: return bad_gateway("Could not reach NCBI")
""" Provides request handlers for managing and viewing analyses. """ import aiohttp import aiohttp.web import virtool.genbank import virtool.http.proxy import virtool.http.routes from virtool.api.utils import bad_gateway, json_response, not_found routes = virtool.http.routes.Routes() @routes.get("/api/genbank/{accession}") async def get(req): """ Retrieve the Genbank data associated with the given accession and transform it into a Virtool-style sequence document. """ accession = req.match_info["accession"] session = req.app["client"] settings = req.app["settings"] try: data = await virtool.genbank.fetch(settings, session, accession) if data is None: return not_found() return json_response(data) except aiohttp.client_exceptions.ClientConnectorError: return bad_gateway("Could not reach Genbank")
Fix ordering and breadcrumb generation for interactive doc.
import { hierarchy } from "d3-hierarchy"; const JSON_PATH = "http://rawgit.com/interlockjs/interlock/master/docs/compilation.json"; function orderChildren (datum) { if (datum.children) { datum.children = datum.children.map((child, idx) => { child = orderChildren(child); child.position = idx; return child; }); } return datum; } function addAnscestors (node, anscestors) { if (node.children) { node.children = node.children.map((child, idx) => { const childAnscestors = anscestors.concat(node); child = addAnscestors(child, childAnscestors); return child; }); } node.anscestors = anscestors; return node; } module.exports = () => fetch(JSON_PATH) .then(response => response.json()) .then(data => { data = orderChildren(data); return addAnscestors(hierarchy(data), []) .sort((a, b) => b.data.position > a.data.position) .sum(d => d.size) });
import { hierarchy } from "d3-hierarchy"; const JSON_PATH = "http://rawgit.com/interlockjs/interlock/master/docs/compilation.json"; function orderChildren (node, anscestors) { if (node.children) { node.children = node.children.map((child, idx) => { const childAnscestors = anscestors.concat(node); child = orderChildren(child, childAnscestors); child.position = idx; return child; }); } node.anscestors = anscestors; return node; } module.exports = () => fetch(JSON_PATH) .then(response => response.json()) .then(data => orderChildren(hierarchy(data), []) .sort((a, b) => b.data.position - a.data.position) .sum(d => d.size) );
Hide stuff user code shouldn't access
/* * * k6 - a next-generation load testing tool * Copyright (C) 2016 Load Impact * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package js2 import ( "github.com/dop251/goja" "github.com/spf13/afero" ) // Provides APIs for use in the init context. type InitContext struct { // Filesystem to load files and scripts from. Fs afero.Fs `js:"-"` Pwd string `js:"-"` // Cache of loaded modules. Modules map[string]*goja.Program `js:"-"` } func (i *InitContext) Require(mod string) goja.Value { return goja.Undefined() }
/* * * k6 - a next-generation load testing tool * Copyright (C) 2016 Load Impact * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package js2 import ( "github.com/dop251/goja" "github.com/spf13/afero" ) // Provides APIs for use in the init context. type InitContext struct { // Filesystem to load files and scripts from. Fs afero.Fs Pwd string // Cache of loaded modules. Modules map[string]*goja.Program } func (i *InitContext) Require(mod string) goja.Value { return goja.Undefined() }
Remove old entries (~2 months, keep 100000 entries)
import redis import json import time class DHTStorage(): def __init__(self, key): self.redis = redis.StrictRedis(host='localhost', port=6379, db=0) self.key = key def get_key(self, name): return "%s:%s" % (self.key, name) def send(self, name, data): pushData = {'time': time.time(), 'value': data} self.redis.lpush(self.get_key(name), json.dumps(pushData)) def add_humidity(self, value): self.send('humidity', value) self.remove_old('humidity') def add_temperature(self, value): self.send('temperature', value) self.remove_old('temperature') def get_data(self, name, start=0, end=200): return self.redis.lrange(name, start, end) def get_temperature(self, start=0, end=200): return self.get_data(self.get_key('temperature'), start, end) def get_humidity(self, start=0, end=200): return self.get_data(self.get_key('humidity'), start, end) def remove_old(self, name, len=100000): self.redis.ltrim(self.get_key(name), 0, len)
import redis import json import time class DHTStorage(): def __init__(self, key): self.redis = redis.StrictRedis(host='localhost', port=6379, db=0) self.key = key def get_key(self, name): return "%s:%s" % (self.key, name) def send(self, name, data): pushData = {'time': time.time(), 'value': data} self.redis.lpush(self.get_key(name), json.dumps(pushData)) def add_humidity(self, value): self.send('humidity', value) def add_temperature(self, value): self.send('temperature', value) def get_data(self, name, start=0, end=200): return self.redis.lrange(name, start, end) def get_temperature(self, start=0, end=200): return self.get_data(self.get_key('temperature'), start, end) def get_humidity(self, start=0, end=200): return self.get_data(self.get_key('humidity'), start, end)
Add call static helper method to service context
<?php /** * */ namespace Arc5\Facade; use Mvc5\App; use Mvc5\Service\Context; use Mvc5\Service\Facade; use Mvc5\Service\Service as _Service; trait Service { /** * */ use Facade { call as public; param as public; plugin as public; service as public; shared as public; trigger as public; } /** * @param _Service $service * @return callable|_Service */ static function bind(_Service $service) { return Context::bind($service); } /** * @param $config * @param callable|null $provider * @param bool $scope * @return callable|_Service */ static function context($config = [], callable $provider = null, $scope = true) { return static::bind(new App($config, $provider, $scope)); } /** * @param $name * @param array $args * @return mixed */ static function __callStatic($name, array $args) { return static::service()->call($name, $args); } }
<?php /** * */ namespace Arc5\Facade; use Mvc5\App; use Mvc5\Service\Context; use Mvc5\Service\Facade; use Mvc5\Service\Service as _Service; trait Service { /** * */ use Facade { call as public; param as public; plugin as public; service as public; shared as public; trigger as public; } /** * @param _Service $service * @return callable|_Service */ static function bind(_Service $service) { return Context::bind($service); } /** * @param $config * @param callable|null $provider * @param bool $scope * @return callable|_Service */ static function context($config = [], callable $provider = null, $scope = true) { return static::bind(new App($config, $provider, $scope)); } }
Add celeryd prefetch multiplier setting
import os REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379') BROKER_URL = os.getenv( 'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT) CELERYD_TASK_TIME_LIMIT = 10800 CELERY_TRACK_STARTED = True CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend' CELERYBEAT_MAX_LOOP_INTERVAL = 5 CELERY_TIMEZONE = os.getenv('DJANGO_TIME_ZONE', 'America/Sao_Paulo') CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYD_LOG_FORMAT = "[%(asctime)s: %(processName)s %(name)s %(levelname)s] %(message)s" CELERY_ALWAYS_EAGER = False CELERYD_LOG_COLOR = False CELERYD_PREFETCH_MULTIPLIER = 1
import os REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379') BROKER_URL = os.getenv( 'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT) CELERYD_TASK_TIME_LIMIT = 10800 CELERY_TRACK_STARTED = True CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend' CELERYBEAT_MAX_LOOP_INTERVAL = 5 CELERY_TIMEZONE = os.getenv('DJANGO_TIME_ZONE', 'America/Sao_Paulo') CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYD_LOG_FORMAT = "[%(asctime)s: %(processName)s %(name)s %(levelname)s] %(message)s" CELERY_ALWAYS_EAGER = False CELERYD_LOG_COLOR = False
Add getCommit() function for tags
<?php require_once(__DIR__ . '/../GitHubObject.php'); class GitHubTag extends GitHubObject { /* (non-PHPdoc) * @see GitHubObject::getAttributes() */ protected function getAttributes() { return array_merge(parent::getAttributes(), array( 'name' => 'string', 'zipball_url' => 'string', 'tarball_url' => 'string', 'commit' => 'string', )); } /** * @var string */ protected $name; /** * @var string */ protected $zipball_url; /** * @var string */ protected $tarball_url; /** * @return string */ public function getName() { return $this->name; } /** * @return string */ public function getZipballUrl() { return $this->zipball_url; } /** * @return string */ public function getTarballUrl() { return $this->tarball_url; } /** * @return string */ public function getCommit() { return $this->commit; } }
<?php require_once(__DIR__ . '/../GitHubObject.php'); class GitHubTag extends GitHubObject { /* (non-PHPdoc) * @see GitHubObject::getAttributes() */ protected function getAttributes() { return array_merge(parent::getAttributes(), array( 'name' => 'string', 'zipball_url' => 'string', 'tarball_url' => 'string', )); } /** * @var string */ protected $name; /** * @var string */ protected $zipball_url; /** * @var string */ protected $tarball_url; /** * @return string */ public function getName() { return $this->name; } /** * @return string */ public function getZipballUrl() { return $this->zipball_url; } /** * @return string */ public function getTarballUrl() { return $this->tarball_url; } }
Use componentDidUpdate() intead of deprecated componentWillReceiveProps()
import React, { PureComponent } from 'react' import makeAwareness from 'awareness' // Returns a new stateful component, given the specified state handlers and a pure component to render with export default ( Pure, handlersIn, { onChange, adjustArgs } = {} ) => class Organism extends PureComponent { static initialStateForProps(props) { return handlersIn.initial(props) } get currentState() { return this.props.getState ? this.props.getState() : this.state } alterState = (stateChanger) => { // Can either be a plain object or a callback to transform the existing state (this.props.setState || this.setState).call( this, stateChanger, // Call onChange once updated with current version of state onChange ? () => { onChange(this.currentState) } : undefined ) } awareness = makeAwareness(this.alterState, handlersIn, { getProps: () => this.props, adjustArgs }) state = this.awareness.state componentDidMount() { this.awareness.loadAsync(this.props, null, this.currentState) } componentDidUpdate(prevProps, prevState) { this.awareness.loadAsync(this.props, prevProps, this.currentState) } render() { // Render the pure component, passing both props and state, plus handlers bundled together return <Pure { ...this.props } { ...this.currentState } handlers={ this.awareness.handlers } /> } }
import React, { PureComponent } from 'react' import makeAwareness from 'awareness' // Returns a new stateful component, given the specified state handlers and a pure component to render with export default ( Pure, handlersIn, { onChange, adjustArgs } = {} ) => class Organism extends PureComponent { static initialStateForProps(props) { return handlersIn.initial(props) } get currentState() { return this.props.getState ? this.props.getState() : this.state } alterState = (stateChanger) => { // Can either be a plain object or a callback to transform the existing state (this.props.setState || this.setState).call( this, stateChanger, // Call onChange once updated with current version of state onChange ? () => { onChange(this.currentState) } : undefined ) } awareness = makeAwareness(this.alterState, handlersIn, { getProps: () => this.props, adjustArgs }) state = this.awareness.state componentDidMount() { this.awareness.loadAsync(this.props, null, this.currentState) } componentWillReceiveProps(nextProps) { this.awareness.loadAsync(nextProps, this.props, this.currentState) } render() { // Render the pure component, passing both props and state, plus handlers bundled together return <Pure { ...this.props } { ...this.currentState } handlers={ this.awareness.handlers } /> } }
Update price change indicator code to be more readable
import React from "react"; import classes from "./ShortSGonksRow.module.css"; const ShortSGonksRow = (props) => { console.log(props); const getDiffIndicator = () => { const priceDelta = props.datapoints[props.datapoints.length - 1] - props.datapoints[props.datapoints.length - 2]; const diff = priceDelta > 0 ? "+" : priceDelta < 0 ? "-" : "="; const style = diff == "+" ? { color: "green" } : diff == "-" ? { color: "red" } : { color: "orange" }; return ( <div className={classes.ChangeIndicator} style={style}> {diff} </div> ); }; return ( <div {...props} className={classes.Row}> {getDiffIndicator()} <div className={classes.SearchTerm}>{props.searchterm}</div> <div className={classes.CurrentPrice}>$t{props.currentprice}</div> </div> ); }; export default ShortSGonksRow;
import React from "react"; import classes from "./ShortSGonksRow.module.css"; const ShortSGonksRow = (props) => { console.log(props); const getDiffIndicator = () => { const diff = props.datapoints[props.datapoints.length - 1] > props.datapoints[props.datapoints.length - 2] ? "+" : props.datapoints[props.datapoints.length - 1] < props.datapoints[props.datapoints.length - 2] ? "-" : "="; const style = diff == "+" ? { color: "green" } : diff == "-" ? { color: "red" } : { color: "orange" }; return ( <div className={classes.ChangeIndicator} style={style}> {diff} </div> ); }; return ( <div {...props} className={classes.Row}> {getDiffIndicator()} <div className={classes.SearchTerm}>{props.searchterm}</div> <div className={classes.CurrentPrice}>$t{props.currentprice}</div> </div> ); }; export default ShortSGonksRow;
Print execution result for docker.
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('container_id', nargs=1) parser.add_argument('work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) print(container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"])) Command = DockerExecutor
import logging import docker from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase log = logging.getLogger() class DockerExecutor(DjangoCmdBase): def add_arguments(self, parser): # Positional arguments """ :param: in the args it could be: /usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help NO need to add '"' as "/usr/local/bin/python /home/richard/codes/django-dev-server/manage.py help" :return: """ parser.add_argument('container_id', nargs=1) parser.add_argument('work_dir', nargs='?', default=None) parser.add_argument('path_and_params', nargs='+') def msg_loop(self): print(self.options["path_and_params"]) client = docker.from_env() container = client.containers.get(self.options["container_id"][0]) container.exec_run(" ".join(self.options["path_and_params"]), workdir=self.options["work_dir"]) Command = DockerExecutor
FIX to ignore directories, not just their contents Using eGit in eclipse, the trailing slash is causing folders to not be excluded.
<?php namespace GDM\SSAutoGitIgnore; use Composer\Script\Event; class UpdateScript { public static function Go(Event $event) { $event->getIO()->writeError('<info>Generating .gitignore: </info>', false); $gi = new GitIgnoreEditor(getcwd() . '/.gitignore'); $packageInfo = new SSPackageInfo($event->getComposer()); $ignores = array(); foreach ($packageInfo->GetSSModules() as $value) { $ignores[] = "/" . $value["path"] ;//. "/"; } sort($ignores); $gi->setLines($ignores); $gi->save(); $event->getIO()->writeError('<info>Done - Set to ignore '.count($ignores).' packages</info>'); } }
<?php namespace GDM\SSAutoGitIgnore; use Composer\Script\Event; class UpdateScript { public static function Go(Event $event) { $event->getIO()->writeError('<info>Generating .gitignore: </info>', false); $gi = new GitIgnoreEditor(getcwd() . '/.gitignore'); $packageInfo = new SSPackageInfo($event->getComposer()); $ignores = array(); foreach ($packageInfo->GetSSModules() as $value) { $ignores[] = "/" . $value["path"] . "/"; } sort($ignores); $gi->setLines($ignores); $gi->save(); $event->getIO()->writeError('<info>Done - Set to ignore '.count($ignores).' packages</info>'); } }
Update the max pool size from 10 to 500
const config = require('./config') module.exports = { web: { client: 'mssql', connection: { host: config.DATABASE_SERVER, user: config.WEB_APP_DATABASE_USERNAME, password: config.WEB_APP_DATABASE_PASSWORD, database: config.DATABASE, options: { encrypt: true } }, debug: false, pool: { max: 500 } }, integrationTests: { client: 'mssql', connection: { host: config.DATABASE_SERVER, user: config.MIGRATION_APP_DATABASE_USERNAME, password: config.MIGRATION_APP_DATABASE_PASSWORD, database: config.DATABASE, options: { encrypt: true } }, debug: false } }
const config = require('./config') module.exports = { web: { client: 'mssql', connection: { host: config.DATABASE_SERVER, user: config.WEB_APP_DATABASE_USERNAME, password: config.WEB_APP_DATABASE_PASSWORD, database: config.DATABASE, options: { encrypt: true } }, debug: false }, integrationTests: { client: 'mssql', connection: { host: config.DATABASE_SERVER, user: config.MIGRATION_APP_DATABASE_USERNAME, password: config.MIGRATION_APP_DATABASE_PASSWORD, database: config.DATABASE, options: { encrypt: true } }, debug: false } }
Use type casting instead of resolve() since we know it is actually ResolvedDependency
package com.github.blindpirate.gogradle.task; import com.github.blindpirate.gogradle.build.BuildManager; import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency; import com.github.blindpirate.gogradle.core.dependency.tree.DependencyTreeNode; import org.gradle.api.tasks.TaskAction; import javax.inject.Inject; import static com.github.blindpirate.gogradle.build.Configuration.BUILD; public class InstallBuildDependenciesTask extends AbstractGolangTask { @Inject private BuildManager buildManager; public InstallBuildDependenciesTask() { dependsOn(GolangTaskContainer.RESOLVE_BUILD_DEPENDENCIES_TASK_NAME); } @TaskAction public void installDependencies() { DependencyTreeNode rootNode = getTask(ResolveBuildDependenciesTask.class).getDependencyTree(); rootNode.flatten() .stream() .map(dependency -> (ResolvedDependency) dependency) .forEach((dependency) -> buildManager.installDependency(dependency, BUILD)); } }
package com.github.blindpirate.gogradle.task; import com.github.blindpirate.gogradle.build.BuildManager; import com.github.blindpirate.gogradle.core.dependency.GolangDependency; import com.github.blindpirate.gogradle.core.dependency.tree.DependencyTreeNode; import org.gradle.api.tasks.TaskAction; import javax.inject.Inject; import static com.github.blindpirate.gogradle.build.Configuration.BUILD; public class InstallBuildDependenciesTask extends AbstractGolangTask { @Inject private BuildManager buildManager; public InstallBuildDependenciesTask() { dependsOn(GolangTaskContainer.RESOLVE_BUILD_DEPENDENCIES_TASK_NAME); } @TaskAction public void installDependencies() { DependencyTreeNode rootNode = getTask(ResolveBuildDependenciesTask.class).getDependencyTree(); rootNode.flatten() .stream() .map(GolangDependency::resolve) .forEach((dependency) -> buildManager.installDependency(dependency, BUILD)); } }
Use call_user_func_array for older PHP functions
<?php /** * This file is part of TwigView. * ** (c) 2015 Cees-Jan Kiewiet * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WyriHaximus\CakePHP\Tests\TwigView\Lib\Twig\Extension; use WyriHaximus\TwigView\Lib\Twig\Extension\Strings; final class StringsTest extends AbstractExtensionTest { public function setUp() { $this->extension = new Strings(); parent::setUp(); } public function testSubstr() { $string = 'abc'; $callable = $this->getFilter('substr')->getCallable(); $result = call_user_func_array($callable, [$string, -1]); $this->assertSame('c', $result); } public function testTokenize() { $string = 'a,b,c'; $callable = $this->getFilter('tokenize')->getCallable(); $result = call_user_func_array($callable, [$string]); $this->assertSame(['a', 'b', 'c'], $result); } }
<?php /** * This file is part of TwigView. * ** (c) 2015 Cees-Jan Kiewiet * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WyriHaximus\CakePHP\Tests\TwigView\Lib\Twig\Extension; use WyriHaximus\TwigView\Lib\Twig\Extension\Strings; final class StringsTest extends AbstractExtensionTest { public function setUp() { $this->extension = new Strings(); parent::setUp(); } public function testSubstr() { $string = 'abc'; $callable = $this->getFilter('substr')->getCallable(); $result = $callable($string, -1); $this->assertSame('c', $result); } public function testTokenize() { $string = 'a,b,c'; $callable = $this->getFilter('tokenize')->getCallable(); $result = $callable($string); $this->assertSame(['a', 'b', 'c'], $result); } }
bears/julia: Add Skip Condition for JuliaBear Add prerequisite_command and prerequisite_fail_msg to JuliaBear. Fixes https://github.com/coala-analyzer/coala-bears/issues/222
from coalib.bearlib.abstractions.Lint import Lint from coalib.bears.LocalBear import LocalBear from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class JuliaLintBear(LocalBear, Lint): executable = 'julia' arguments = '-e \'import Lint.lintfile; lintfile({filename})\'' prerequisite_command = ['julia', '-e', 'import Lint.lintfile'] prerequisite_fail_msg = 'Run `Pkg.add("Lint")` from Julia to install Lint.' output_regex = r'(^.*\.jl):(?P<line>\d+) (?P<severity>.)\d+ (?P<message>.*)' use_stdout = True severity_map = { "E": RESULT_SEVERITY.MAJOR, "W": RESULT_SEVERITY.NORMAL, "I": RESULT_SEVERITY.INFO } def run(self, filename, file): ''' Lints Julia code using ``Lint.jl``. https://github.com/tonyhffong/Lint.jl ''' return self.lint(filename, file)
from coalib.bearlib.abstractions.Lint import Lint from coalib.bears.LocalBear import LocalBear from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class JuliaLintBear(LocalBear, Lint): executable = 'julia' arguments = '-e \'import Lint.lintfile; lintfile({filename})\'' output_regex = r'(^.*\.jl):(?P<line>\d+) (?P<severity>.)\d+ (?P<message>.*)' use_stdout = True severity_map = { "E": RESULT_SEVERITY.MAJOR, "W": RESULT_SEVERITY.NORMAL, "I": RESULT_SEVERITY.INFO } def run(self, filename, file): ''' Lints Julia code using ``Lint.jl``. https://github.com/tonyhffong/Lint.jl ''' return self.lint(filename, file)
Create a properly configured SSL Context
from twisted.internet.ssl import CertificateOptions, ContextFactory from txsni.only_noticed_pypi_pem_after_i_wrote_this import ( certificateOptionsFromPileOfPEM ) class SNIMap(ContextFactory, object): def __init__(self, mapping): self.mapping = mapping try: self.context = self.mapping['DEFAULT'].getContext() except KeyError: self.context = CertificateOptions().getContext() self.context.set_tlsext_servername_callback( self.selectContext ) def getContext(self): return self.context def selectContext(self, connection): connection.set_context( self.mapping[connection.get_servername()] .getContext() ) class HostDirectoryMap(object): def __init__(self, directoryPath): self.directoryPath = directoryPath def __getitem__(self, hostname): filePath = self.directoryPath.child(hostname + ".pem") if filePath.isfile(): return certificateOptionsFromPileOfPEM(filePath.getContent()) else: raise KeyError("no pem file for " + hostname)
from OpenSSL.SSL import Context, TLSv1_METHOD from twisted.internet.ssl import ContextFactory from txsni.only_noticed_pypi_pem_after_i_wrote_this import ( certificateOptionsFromPileOfPEM ) class SNIMap(ContextFactory, object): def __init__(self, mapping): self.mapping = mapping try: self.context = self.mapping['DEFAULT'].getContext() except KeyError: self.context = Context(TLSv1_METHOD) self.context.set_tlsext_servername_callback( self.selectContext ) def getContext(self): return self.context def selectContext(self, connection): connection.set_context( self.mapping[connection.get_servername()] .getContext() ) class HostDirectoryMap(object): def __init__(self, directoryPath): self.directoryPath = directoryPath def __getitem__(self, hostname): filePath = self.directoryPath.child(hostname + ".pem") if filePath.isfile(): return certificateOptionsFromPileOfPEM(filePath.getContent()) else: raise KeyError("no pem file for " + hostname)
Add direction to network objects
package net.mueller_martin.turirun.network; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.EndPoint; public class TurirunNetwork { public static final int tcpPort = 1337; public static final int udpPort = 7331; // This registers objects that are going to be sent over the network public static void register(EndPoint endPoint) { Kryo kryo = endPoint.getKryo(); kryo.register(Register.class); kryo.register(Character.class); kryo.register(AddCharacter.class); kryo.register(RemoveCharacter.class); kryo.register(UpdateCharacter.class); kryo.register(MoveCharacter.class); } public static class Register { public String nick; public int type; } public static class Character { public String nick; public int type, id, direction; public float x, y; }; public static class AddCharacter { public Character character; } public static class RemoveCharacter { public int id; } public static class UpdateCharacter { public int id, direction; public float x, y; } public static class MoveCharacter { public float x, y, direction; } }
package net.mueller_martin.turirun.network; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.EndPoint; public class TurirunNetwork { public static final int tcpPort = 1337; public static final int udpPort = 7331; // This registers objects that are going to be sent over the network public static void register(EndPoint endPoint) { Kryo kryo = endPoint.getKryo(); kryo.register(Register.class); kryo.register(Character.class); kryo.register(AddCharacter.class); kryo.register(RemoveCharacter.class); kryo.register(UpdateCharacter.class); kryo.register(MoveCharacter.class); } public static class Register { public String nick; public int type; } public static class Character { public String nick; public int type, id; public float x, y; }; public static class AddCharacter { public Character character; } public static class RemoveCharacter { public int id; } public static class UpdateCharacter { public int id; public float x, y; } public static class MoveCharacter { public float x, y; } }
Fix module data import on links server notice
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implements class SnoLinks(ModuleData): implements(IPlugin, IModuleData) name = "ServerNoticeLinks" def actions(self): return [ ("serverconnect", 1, self.announceConnect), ("serverquit", 1, self.announceQuit), ("servernoticetype", 1, self.checkSnoType) ] def announceConnect(self, server): message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name) self.ircd.runActionStandard("sendservernotice", "links", message) def announceQuit(self, server, reason): message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason) self.ircd.runActionStandard("sendservernotice", "links", message) def checkSnoType(self, user, typename): if typename == "links": return True return False snoLinks = SnoLinks()
from twisted.plugin import IPlugin from txircd.modbase import IModuleData, ModuleData from zope.interface import implements class SnoLinks(ModuleData): implements(IPlugin, IModuleData) name = "ServerNoticeLinks" def actions(self): return [ ("serverconnect", 1, self.announceConnect), ("serverquit", 1, self.announceQuit), ("servernoticetype", 1, self.checkSnoType) ] def announceConnect(self, server): message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name) self.ircd.runActionStandard("sendservernotice", "links", message) def announceQuit(self, server, reason): message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason) self.ircd.runActionStandard("sendservernotice", "links", message) def checkSnoType(self, user, typename): if typename == "links": return True return False snoLinks = SnoLinks()
Allow https for twitter urls and use version 1 api
<?php /* * This file is part of the Omlex library. * * (c) Michael H. Arieli <excelwebzone@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Omlex\Provider; use Omlex\Provider; /** * @author Evert Harmeling <evert.harmeling@freshheads.com> */ class Twitter extends Provider { /** * {@inheritdoc} */ public function __construct($endpoint = null, array $schemes = array(), $url = null, $name = null) { return parent::__construct( 'https://api.twitter.com/1/statuses/oembed.json', array( 'http://twitter.com/*/status/*', 'https://twitter.com/*/status/*', ), 'http://twitter.com', 'Twitter' ); } }
<?php /* * This file is part of the Omlex library. * * (c) Michael H. Arieli <excelwebzone@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Omlex\Provider; use Omlex\Provider; /** * @author Evert Harmeling <evert.harmeling@freshheads.com> */ class Twitter extends Provider { /** * {@inheritdoc} */ public function __construct($endpoint = null, array $schemes = array(), $url = null, $name = null) { return parent::__construct( 'https://api.twitter.com/1.1/statuses/oembed.json', array( 'http://twitter.com/*/status/*' ), 'http://twitter.com', 'Twitter' ); } }
Add `metafields()` method to `Image` resource.
from ..base import ShopifyResource from ..resources import Metafield from six.moves import urllib import base64 import re class Image(ShopifyResource): _prefix_source = "/admin/products/$product_id/" def __getattr__(self, name): if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]: return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src) else: return super(Image, self).__getattr__(name) def attach_image(self, data, filename=None): self.attributes["attachment"] = base64.b64encode(data) if filename: self.attributes["filename"] = filename def metafields(self): if self.is_new(): return [] query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' } return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params))
from ..base import ShopifyResource import base64 import re class Image(ShopifyResource): _prefix_source = "/admin/products/$product_id/" def __getattr__(self, name): if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]: return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src) else: return super(Image, self).__getattr__(name) def attach_image(self, data, filename=None): self.attributes["attachment"] = base64.b64encode(data) if filename: self.attributes["filename"] = filename
Fix spawn painting encode for 1.4.7-1.6.5
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_4__1_5__1_6; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleSpawnPainting; import protocolsupport.protocol.packet.middleimpl.PacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class SpawnPainting extends MiddleSpawnPainting<RecyclableCollection<PacketData>> { @Override public RecyclableCollection<PacketData> toData(ProtocolVersion version) { switch (direction) { case 0: { position.modifyZ(-1); break; } case 1: { position.modifyX(1); break; } case 2: { position.modifyZ(1); break; } case 3: { position.modifyX(-1); break; } } PacketData serializer = PacketData.create(ClientBoundPacket.PLAY_SPAWN_PAINTING_ID, version); serializer.writeInt(entityId); serializer.writeString(type); serializer.writeLegacyPositionI(position); serializer.writeInt(direction); return RecyclableSingletonList.create(serializer); } }
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_4__1_5__1_6; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.packet.ClientBoundPacket; import protocolsupport.protocol.packet.middle.clientbound.play.MiddleSpawnPainting; import protocolsupport.protocol.packet.middleimpl.PacketData; import protocolsupport.utils.recyclable.RecyclableCollection; import protocolsupport.utils.recyclable.RecyclableSingletonList; public class SpawnPainting extends MiddleSpawnPainting<RecyclableCollection<PacketData>> { @Override public RecyclableCollection<PacketData> toData(ProtocolVersion version) { switch (direction) { case 0: { position.modifyZ(-1); break; } case 1: { position.modifyX(1); break; } case 2: { position.modifyZ(1); break; } case 3: { position.modifyX(-1); break; } } PacketData serializer = PacketData.create(ClientBoundPacket.PLAY_SPAWN_PAINTING_ID, version); serializer.writeInt(entityId); serializer.writeString(type); serializer.writeLegacyPositionI(position); return RecyclableSingletonList.create(serializer); } }
Use the `ember-data` initializer as a target instead of the soon to be deprecated `store` initializer
import Ember from 'ember'; import DS from 'ember-data'; import WithLoggerMixin from '../mixins/with-logger'; import {LEVELS} from '../mixins/with-logger'; import StoreMixin from '../mixins/store'; import SailsSocketService from '../services/sails-socket'; var get$ = Ember.get; DS.Store.reopen(StoreMixin); export function initialize(container, application) { var methods, minLevel, shouldLog; methods = {}; minLevel = get$(application, 'SAILS_LOG_LEVEL'); shouldLog = false; LEVELS.forEach(function (level) { if (level === minLevel) { shouldLog = true; } if (!shouldLog) { methods[level] = Ember.K; } }); WithLoggerMixin.reopen(methods); application.register('service:sails-socket', SailsSocketService); application.register('config:ember-data-sails', get$(application, 'emberDataSails') || {}, {instantiate: false}); // setup injections application.inject('adapter', 'sailsSocket', 'service:sails-socket'); application.inject('serializer', 'config', 'config:ember-data-sails'); application.inject('route', 'sailsSocket', 'service:sails-socket'); application.inject('controller', 'sailsSocket', 'service:sails-socket'); } var EmberDataSailsInitializer = { name: 'ember-data-sails', before: 'ember-data', initialize: initialize }; export default EmberDataSailsInitializer;
import Ember from 'ember'; import DS from 'ember-data'; import WithLoggerMixin from '../mixins/with-logger'; import {LEVELS} from '../mixins/with-logger'; import StoreMixin from '../mixins/store'; import SailsSocketService from '../services/sails-socket'; var get$ = Ember.get; DS.Store.reopen(StoreMixin); export function initialize(container, application) { var methods, minLevel, shouldLog; methods = {}; minLevel = get$(application, 'SAILS_LOG_LEVEL'); shouldLog = false; LEVELS.forEach(function (level) { if (level === minLevel) { shouldLog = true; } if (!shouldLog) { methods[level] = Ember.K; } }); WithLoggerMixin.reopen(methods); application.register('service:sails-socket', SailsSocketService); application.register('config:ember-data-sails', get$(application, 'emberDataSails') || {}, {instantiate: false}); // setup injections application.inject('adapter', 'sailsSocket', 'service:sails-socket'); application.inject('serializer', 'config', 'config:ember-data-sails'); application.inject('route', 'sailsSocket', 'service:sails-socket'); application.inject('controller', 'sailsSocket', 'service:sails-socket'); } var EmberDataSailsInitializer = { name: 'ember-data-sails', before: 'store', initialize: initialize }; export default EmberDataSailsInitializer;
Add invoicing_plan with quarterly and yearly options
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-27 18:30 from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounting', '0031_billingaccount_billing_admin_emails'), ] operations = [ migrations.AddField( model_name='billingaccount', name='invoicing_plan', field=models.CharField( choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')], default='MONTHLY', max_length=25 ) ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-27 18:30 from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounting', '0031_billingaccount_billing_admin_emails'), ] operations = [ migrations.AddField( model_name='billingaccount', name='invoicing_plan', field=models.CharField( choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')], default='MONTHLY', max_length=25 ), ), ]