text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove unnecessary logic in Action helper
var _ = require('lodash-node'); var Action = function(name, two, three, four) { var options, run, helpers; var run = two; var options = three; var presets = { name: name, description: name + ' description', inputs: { required: [], optional: [] }, blockedConnectionTypes: [], outputExample: {}, run: function(api, conn, next){ this.api = api; this.connection = conn; this.json = this.connection.response; this.next = function(success) { next(conn, success); }; this.params = conn.params; run.apply(this, arguments); } }; return _.merge(presets, options); }; module.exports = Action;
var _ = require('lodash-node'); var Action = function(name, two, three, four) { var options, run, helpers; // Syntax .extend('action#method', function() { ... }, {}) if ( typeof two == 'function' ) { options = {}; run = two; helpers = three; } // Syntax .extend('action#method', {}, function() { ... }, {}) if ( typeof three == 'function' ) { options = two; run = three; helpers = four; } var presets = { name: name, description: name + ' description', inputs: { required: [], optional: [] }, blockedConnectionTypes: [], outputExample: {}, run: function(api, conn, next){ this.api = api; this.connection = conn; this.next = function(success) { next(conn, success); }; this.json = conn.response; this.params = conn.params; run.apply(this, arguments); } }; return _.merge(presets, options, helpers); }; module.exports = Action;
Fix build on PHP 7
<?php /** * @license http://opensource.org/licenses/mit-license.php MIT * @link https://github.com/nicoSWD * @since 0.3.4 * @author Nicolas Oelgart <nico@oelgart.com> */ namespace nicoSWD\Rules; use SplObjectStorage; /** * Class Stack * @package nicoSWD\Rules */ final class Stack extends SplObjectStorage { /** * @return \nicoSWD\Rules\Tokens\BaseToken */ public function current() { return parent::current(); } /** * @return Stack */ public function getClone() { $stackClone = clone $this; $stackClone->rewind(); // This is ugly and needs to be fixed while ($stackClone->key() < $this->key()) { $stackClone->next(); } return $stackClone; } }
<?php /** * @license http://opensource.org/licenses/mit-license.php MIT * @link https://github.com/nicoSWD * @since 0.3.4 * @author Nicolas Oelgart <nico@oelgart.com> */ namespace nicoSWD\Rules; use SplObjectStorage; /** * Class Stack * @package nicoSWD\Rules */ final class Stack extends SplObjectStorage { /** * @return \nicoSWD\Rules\Tokens\BaseToken */ public function current() { return parent::current(); } /** * @return Stack */ public function getClone() { $stackClone = clone $this; // This is ugly and needs to be fixed while ($stackClone->key() < $this->key()) { $stackClone->next(); } return $stackClone; } }
Disable Internet Banking method if Omise extension is either disabled or uninstalled.
<?php class ModelPaymentOmiseOffsite extends Model { public function getMethod($address, $total) { if ($this->config->get('omise_status') != 1) { return false; } $this->load->language('payment/omise_offsite'); if ($this->config->get('omise_offsite_payment_title') != "") $payment_title = $this->config->get('omise_offsite_payment_title'); else $payment_title = $this->language->get('text_title'); return array( 'code' => 'omise_offsite', 'title' => $payment_title, 'terms' => '', 'sort_order' => $this->config->get('omise_offsite_sort_order') ); } }
<?php class ModelPaymentOmiseOffsite extends Model { public function getMethod($address, $total) { $this->load->language('payment/omise_offsite'); if ($this->config->get('omise_offsite_payment_title') != "") $payment_title = $this->config->get('omise_offsite_payment_title'); else $payment_title = $this->language->get('text_title'); return array( 'code' => 'omise_offsite', 'title' => $payment_title, 'terms' => '', 'sort_order' => $this->config->get('omise_offsite_sort_order') ); } }
Make sure that you are logged out at the end of a backend test
<?php namespace Backend\Core\Tests; use Backend\Core\Engine\Authentication as Authentication; use Common\WebTestCase; use Symfony\Bundle\FrameworkBundle\Client; abstract class BackendWebTestCase extends WebTestCase { /** * Make sure we are no longer logged-in */ protected function tearDown(): void { $client = $this->getProvidedData()[0] ?? null; if ($client instanceof Client) { $this->logout($client); } } protected function setUp(): void { parent::setUp(); if (!defined('APPLICATION')) { define('APPLICATION', 'Backend'); } } protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void { // make sure we aren't logged in with the client $this->logout($client); $this->assertGetsRedirected( $client, $url, '/private/en/authentication?querystring=' . rawurlencode($url), $method ); } }
<?php namespace Backend\Core\Tests; use Common\WebTestCase; use Symfony\Bundle\FrameworkBundle\Client; abstract class BackendWebTestCase extends WebTestCase { protected function setUp(): void { parent::setUp(); if (!defined('APPLICATION')) { define('APPLICATION', 'Backend'); } } protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void { // make sure we aren't logged in with the client $this->logout($client); $this->assertGetsRedirected( $client, $url, '/private/en/authentication?querystring=' . rawurlencode($url), $method ); } }
Change the re const name to uppercase.
"""CVMFS Servcice.""" import os import re import cherrypy import html from natsort import natsorted VERSION_RE = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$") @cherrypy.popargs('appid') class CVMFSAppVersions(object): """ CVMFS App Version checking service. CVMFS Service to get the list of versions available on CVMFS for a given app. """ def __init__(self, cvmfs_root, valid_apps): """Initialise.""" self.cvmfs_root = cvmfs_root self.valid_apps = valid_apps @cherrypy.expose def index(self, appid=None): """Return the index page.""" print "IN CVMFSAppVersion: appid=(%s)" % appid if appid not in self.valid_apps: print "Invalid app type %s" % appid return '' html_ = html.HTML() _, dirs, _ = os.walk(os.path.join(self.cvmfs_root, appid)).next() for dir_ in natsorted(dirs): for version in VERSION_RE.findall(dir_): html_.option(version) return str(html_)
"""CVMFS Servcice.""" import os import re import cherrypy import html from natsort import natsorted version_re = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$") @cherrypy.popargs('appid') class CVMFSAppVersions(object): """ CVMFS App Version checking service. CVMFS Service to get the list of versions available on CVMFS for a given app. """ def __init__(self, cvmfs_root, valid_apps): """Initialise.""" self.cvmfs_root = cvmfs_root self.valid_apps = valid_apps @cherrypy.expose def index(self, appid=None): """Return the index page.""" print "IN CVMFSAppVersion: appid=(%s)" % appid if appid not in self.valid_apps: print "Invalid app type %s" % appid return '' html_ = html.HTML() _, dirs, _ = os.walk(os.path.join(self.cvmfs_root, appid)).next() for dir_ in natsorted(dirs): for version in version_re.findall(dir_): html_.option(version) return str(html_)
Allow the median method to overwrite in-memory intermediate Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu>
import argparse import astropy.io.fits as fits import numpy as np import sys METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True), "average": lambda x: np.average(x, axis=0), "sum": lambda x: np.sum(x, axis=0)} def stack_fits_data(filenames): fits_files = [] for f in filenames: fits_files.append(fits.open(f)) stack = np.array([f[0].data for f in fits_files]) for f in fits_files: f.close() return stack def create_parser(subparsers): parser_combine = subparsers.add_parser("combine", help="combine help") parser_combine.add_argument("-m", "--method", choices=["median", "average", "sum"], required=True) parser_combine.add_argument("-o", "--output", metavar="OUTFILE", default=sys.stdout.buffer) parser_combine.add_argument("file", nargs="+") parser_combine.set_defaults(func=main) def main(args): image_stack = stack_fits_data(args.file) result = METHOD_MAP[args.method](image_stack) hdu = fits.PrimaryHDU(result) hdu.writeto(args.output)
import argparse import astropy.io.fits as fits import numpy as np import sys METHOD_MAP = {"median": lambda x: np.median(x, axis=0), "average": lambda x: np.average(x, axis=0), "sum": lambda x: np.sum(x, axis=0)} def stack_fits_data(filenames): fits_files = [] for f in filenames: fits_files.append(fits.open(f)) stack = np.array([f[0].data for f in fits_files]) for f in fits_files: f.close() return stack def create_parser(subparsers): parser_combine = subparsers.add_parser("combine", help="combine help") parser_combine.add_argument("-m", "--method", choices=["median", "average", "sum"], required=True) parser_combine.add_argument("-o", "--output", metavar="OUTFILE", default=sys.stdout.buffer) parser_combine.add_argument("file", nargs="+") parser_combine.set_defaults(func=main) def main(args): image_stack = stack_fits_data(args.file) result = METHOD_MAP[args.method](image_stack) hdu = fits.PrimaryHDU(result) hdu.writeto(args.output)
Load middleware before we fork. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
import logging from optparse import make_option from django.core.management.base import NoArgsCommand from ...utils import get_backend, get_middleware class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--pidfile', action='store', dest='pidfile', default=None, help="Fork and write pidfile to this file."), ) def handle_noargs(self, **options): level = { '0': logging.WARNING, '1': logging.INFO, '2': logging.DEBUG, }[options['verbosity']] logging.basicConfig(level=level, format='%(levelname).1s: %(message)s') logging.info("Starting queue runner") backend = get_backend() logging.info("Started backend %s", backend) get_middleware() logging.info("Loaded middleware") while True: try: logging.debug("Checking backend for items") job = backend.dequeue(1) except KeyboardInterrupt: return if job is not None: job.run()
import logging from optparse import make_option from django.core.management.base import NoArgsCommand from ...utils import get_backend class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--pidfile', action='store', dest='pidfile', default=None, help="Fork and write pidfile to this file."), ) def handle_noargs(self, **options): level = { '0': logging.WARNING, '1': logging.INFO, '2': logging.DEBUG, }[options['verbosity']] logging.basicConfig(level=level, format='%(levelname).1s: %(message)s') logging.info("Starting queue runner") backend = get_backend() logging.info("Started backend %s", backend) while True: try: logging.debug("Checking backend for items") job = backend.dequeue(1) except KeyboardInterrupt: return if job is not None: job.run()
Fix for broken container security test
from tests.base import BaseTest from tenable_io.api.models import ScTestJob class TestScTestJobsApi(BaseTest): def test_status(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' test_job = client.sc_test_jobs_api.status(jobs[0].job_id) assert isinstance(test_job, ScTestJob), u'The method returns type.' def test_by_image(self, client, image): job = client.sc_test_jobs_api.by_image(image['id']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_by_image_digest(self, client, image): job = client.sc_test_jobs_api.by_image_digest(image['digest']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_list(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
from tests.base import BaseTest from tenable_io.api.models import ScTestJob class TestScTestJobsApi(BaseTest): def test_status(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' test_job = client.sc_test_jobs_api.status(jobs[0].job_id) assert isinstance(test_job, ScTestJob), u'The method returns type.' def test_by_image(self, client, image): job = client.sc_test_jobs_api.by_image(image['id']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_by_image_digest(self, client, image): job = client.sc_test_jobs_api.by_image(image['digest']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_list(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
Fix naming of writeFile tests
var path = require('path'), fs = require('fs'), crypto = require('crypto'); describe("writeFile functionality", function() { var _this = this; require('./harness.js')(_this); it("creates a directory", function(done) { var fname = "testDir"; var resolved = path.resolve(_this.tempdir, fname); crypto.pseudoRandomBytes(128 * 1024, function(err, data) { if (err) throw err; _this.wd.writeFile(fname, data, function(err) { expect(err).toBe(null); fs.readFile(resolved, function(err, rdata) { if (err) throw err; expect(rdata.toString()).toBe(data.toString()); done(); }); }); }); }); });
var path = require('path'), fs = require('fs'), crypto = require('crypto'); describe("readFile functionality", function() { var _this = this; require('./harness.js')(_this); it("creates a directory", function(done) { var fname = "testDir"; var resolved = path.resolve(_this.tempdir, fname); crypto.pseudoRandomBytes(128 * 1024, function(err, data) { if (err) throw err; _this.wd.writeFile(fname, data, function(err) { expect(err).toBe(null); fs.readFile(resolved, function(err, rdata) { if (err) throw err; expect(rdata.toString()).toBe(data.toString()); done(); }); }); }); }); });
Change modules images file name
import gulp from "gulp"; import plumber from "gulp-plumber"; import changed from "gulp-changed"; import imagemin from "gulp-imagemin"; import rename from "gulp-rename"; import gulpIf from "gulp-if"; import path from "path"; import logger from "gulplog"; import { plumberConfig, imageminConfig } from "../config"; import { isDevelopment } from "../util/env"; function renameFileByModuleName(file) { const { dirname, basename, extname } = file; const dirNameArr = dirname.split(path.sep).filter(i => i !== "images") || []; const newDirname = path.join(...dirNameArr); const prevFileName = path.join(dirname, basename + extname); const nextFileName = path.join(newDirname, basename + extname); logger.info(`File "${prevFileName}" renamed to "${nextFileName}"`); file.dirname = newDirname; } export const moduleImages = () => { return gulp .src("**/*.{png,jpg,jpeg,gif,svg,webp}", { cwd: "source/modules/*/images" }) .pipe(plumber(plumberConfig)) .pipe(rename(renameFileByModuleName)) .pipe(changed("dest/assets/images")) .pipe(gulpIf(!isDevelopment, imagemin(imageminConfig.images))) .pipe(gulp.dest("dest/assets/images")); };
import gulp from "gulp"; import plumber from "gulp-plumber"; import changed from "gulp-changed"; import imagemin from "gulp-imagemin"; import rename from "gulp-rename"; import gulpIf from "gulp-if"; import path from "path"; import logger from "gulplog"; import { plumberConfig, imageminConfig } from "../config"; import { isDevelopment } from "../util/env"; function renameFileByModuleName(file) { const f = path.parse(file.dirname); const nextBasename = f.dir + "__" + file.basename; const prevFileName = file.basename + file.extname; const nextFileName = nextBasename + file.extname; file.dirname = ""; file.basename = nextBasename; logger.info(`File "${prevFileName}" renamed to "${nextFileName}"`); } export const moduleImages = () => { return gulp .src("**/*.{png,jpg,jpeg,gif,svg,webp}", { cwd: "source/modules/*/images" }) .pipe(plumber(plumberConfig)) .pipe(rename(renameFileByModuleName)) .pipe(changed("dest/assets/images")) .pipe(gulpIf(!isDevelopment, imagemin(imageminConfig.images))) .pipe(gulp.dest("dest/assets/images")); };
Replace validateAll with validate function
Tinytest.add('Validators - Order', function(test) { Astro.classes = []; ValidatorItem = Astro.Class({ name: 'ValidatorItem', fields: [ 'first', 'second', 'third' ], validators: { 'first': Validators.string(), 'second': Validators.string(), 'third': Validators.string() }, validationOrder: [ 'third', 'second', 'first' ] }); var validatorItem = new ValidatorItem(); validatorItem.validate(); var errors = validatorItem.getValidationErrors(); test.isTrue(_.has(errors, 'third'), 'The "third" validator should be run first'); validatorItem.validate(false); var keys = _.keys(validatorItem.getValidationErrors()); test.equal(keys, ['third', 'second', 'first'], 'Validators should be run in the following order ' + '"third", "second", "first"' ); });
Tinytest.add('Validators - Order', function(test) { Astro.classes = []; ValidatorItem = Astro.Class({ name: 'ValidatorItem', fields: [ 'first', 'second', 'third' ], validators: { 'first': Validators.string(), 'second': Validators.string(), 'third': Validators.string() }, validationOrder: [ 'third', 'second', 'first' ] }); var validatorItem = new ValidatorItem(); validatorItem.validate(); var errors = validatorItem.getValidationErrors(); test.isTrue(_.has(errors, 'third'), 'The "third" validator should be run first'); validatorItem.validateAll(); var keys = _.keys(validatorItem.getValidationErrors()); test.equal(keys, ['third', 'second', 'first'], 'Validators should be run in the following order ' + '"third", "second", "first"' ); });
Add autocommit to 1 to avoid select cache ¿WTF?
import MySQLdb class database(object): def __init__(self): config = {} execfile("config.py",config) self.db = MySQLdb.connect(config["host"],config["user"],config["password"],config["database"]) self.db.autocommit(True) def insert(self,txt): dbc = self.db.cursor() try: dbc.execute("insert into " + txt) dbc.close() self.db.commit() except Exception as e: print(e) return False return True def update(self,txt): dbc = self.db.cursor() try: dbc.execute("update from " + txt) dbc.close() self.db.commit() except Exception as e: print(e) return False return True def select(self,txt): dbc = self.db.cursor() try: dbc.execute("select " + txt) result = dbc.fetchall() except Exception as e: print(e) result = None dbc.close() return result
import MySQLdb class database(object): def __init__(self): config = {} execfile("config.py",config) self.db = MySQLdb.connect(config["host"],config["user"],config["password"],config["database"]) def insert(self,txt): dbc = self.db.cursor() try: dbc.execute("insert into " + txt) dbc.close() self.db.commit() except Exception as e: print(e) return False return True def update(self,txt): dbc = self.db.cursor() try: dbc.execute("update from " + txt) dbc.close() self.db.commit() except Exception as e: print(e) return False return True def select(self,txt): dbc = self.db.cursor() try: dbc.execute("select " + txt) result = dbc.fetchall() except Exception as e: print(e) result = None dbc.close() return result
Use ITaskManager instead of TaskManager.
package org.strategoxt.imp.metatooling.building; import org.metaborg.runtime.task.ITaskEngine; import org.metaborg.runtime.task.TaskManager; import org.spoofax.interpreter.library.index.IIndex; import org.spoofax.interpreter.library.index.IndexManager; import org.spoofax.interpreter.library.index.notification.NotificationCenter; public class AntResetProject { public static void main(String[] args) { final String projectPath = args[0]; final TaskManager taskManager = TaskManager.getInstance(); final ITaskEngine taskEngine = taskManager.getTaskEngine(projectPath); if(taskEngine != null) taskEngine.reset(); final IndexManager indexManager = IndexManager.getInstance(); final IIndex index = indexManager.getIndex(args[0]); if(index != null) index.clearAll(); NotificationCenter.notifyNewProject(indexManager.getProjectURIFromAbsolute(projectPath)); } }
package org.strategoxt.imp.metatooling.building; import org.metaborg.runtime.task.TaskEngine; import org.metaborg.runtime.task.TaskManager; import org.spoofax.interpreter.library.index.IIndex; import org.spoofax.interpreter.library.index.IndexManager; import org.spoofax.interpreter.library.index.notification.NotificationCenter; public class AntResetProject { public static void main(String[] args) { final String projectPath = args[0]; final TaskManager taskManager = TaskManager.getInstance(); final TaskEngine taskEngine = taskManager.getTaskEngine(projectPath); if(taskEngine != null) taskEngine.reset(); final IndexManager indexManager = IndexManager.getInstance(); final IIndex index = indexManager.getIndex(args[0]); if(index != null) index.clearAll(); NotificationCenter.notifyNewProject(indexManager.getProjectURIFromAbsolute(projectPath)); } }
Fix undefined errors when constructing Undo() with no arguments
(function(Fontclod) { "use strict"; function Undo(options) { options = options || {}; this.stack = options.stack || []; this._index = options.index || 0; this._data = options.data || {}; } // Undo.step(1) Undo.step(-10) Undo.prototype.step = function(n) { this._index = Math.max(0, Math.min(this._index + n, this.data.length)); }; // Undo.seek(index) Undo.prototype.seek = function(i) { this._index = i; }; Undo.prototype.push = function(data) { var diff = this.diff(data); if (Object.keys(diff).length) this.stack.push(diff); }; Undo.prototype.diff = function(data) { var i, key, diff = {}, keys = Object.keys(data); for (i=0, key=keys[0]; i<keys.length; key=keys[++i]) { if (this._data[key] != data[key]) diff[key] = data[key]; } this._data = data; return diff; }; Fontclod.Undo = Undo; })(Fontclod);
(function(Fontclod) { "use strict"; function Undo(options) { this.index = options.index || 0; this.stack = options.stack || []; this._data = options.data || {}; } // Undo.step(1) Undo.step(-10) Undo.prototype.step = function(n) {}; // Undo.seek(index) Undo.prototype.seek = function(i) {}; Undo.prototype.push = function(data) { var diff = this.diff(data); if (Object.keys(diff).length) this.stack.push(diff); }; Undo.prototype.diff = function(data) { var i, key, diff = {}, keys = Object.keys(data); for (i=0, key=keys[0]; i<keys.length; key=keys[++i]) { if (this._data[key] != data[key]) diff[key] = data[key]; } this._data = data; return diff; }; Fontclod.Undo = Undo; })(Fontclod);
tests: Update Tags cases for new behaviour See also: #193
import responses from requests.exceptions import HTTPError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.gitlab.suppress_http_error = False self.assertRaises(HTTPError, self.gitlab.delete_repository_tag, 5, 'test') self.gitlab.suppress_http_error = True
import responses from gitlab.exceptions import HttpError from gitlab_tests.base import BaseTest from response_data.tags import * class TestDeleteRepositoryTag(BaseTest): @responses.activate def test_delete_repository_tag(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json=delete_repository_tag, status=200, content_type='application/json') self.assertEqual(delete_repository_tag, self.gitlab.delete_repository_tag(5, 'test')) @responses.activate def test_delete_repository_tag_exception(self): responses.add( responses.DELETE, self.gitlab.api_url + '/projects/5/repository/tags/test', json='{"message":"No such tag"}', status=404, content_type='application/json') self.assertRaises(HttpError, self.gitlab.delete_repository_tag, 5, 'test')
Mark internal methods as internal We've missed those ones on previous versions... Signed-off-by: Luís Cobucci <7945d1712249176a02d684a84999e19c759a1347@gmail.com>
<?php declare(strict_types=1); namespace Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer; use function hash_equals; use function hash_hmac; use function strlen; abstract class Hmac implements Signer { final public function sign(string $payload, Key $key): string { $actualKeyLength = 8 * strlen($key->contents()); $expectedKeyLength = $this->minimumBitsLengthForKey(); if ($actualKeyLength < $expectedKeyLength) { throw InvalidKeyProvided::tooShort($expectedKeyLength, $actualKeyLength); } return hash_hmac($this->algorithm(), $payload, $key->contents(), true); } final public function verify(string $expected, string $payload, Key $key): bool { return hash_equals($expected, $this->sign($payload, $key)); } /** @internal */ abstract public function algorithm(): string; /** * @internal * * @return positive-int */ abstract public function minimumBitsLengthForKey(): int; }
<?php declare(strict_types=1); namespace Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer; use function hash_equals; use function hash_hmac; use function strlen; abstract class Hmac implements Signer { final public function sign(string $payload, Key $key): string { $actualKeyLength = 8 * strlen($key->contents()); $expectedKeyLength = $this->minimumBitsLengthForKey(); if ($actualKeyLength < $expectedKeyLength) { throw InvalidKeyProvided::tooShort($expectedKeyLength, $actualKeyLength); } return hash_hmac($this->algorithm(), $payload, $key->contents(), true); } final public function verify(string $expected, string $payload, Key $key): bool { return hash_equals($expected, $this->sign($payload, $key)); } abstract public function algorithm(): string; /** @return positive-int */ abstract public function minimumBitsLengthForKey(): int; }
Fix problem in previous version I was accidentally allowing the current hash's quint to match its triple
import sys import itertools import re from md5 import md5 puzzle_input = 'yjdafjpo' def key(n): return md5(puzzle_input + str(n)).hexdigest() def otp_keys(horizon): lookahead = {k: -1 for k in '0123456789abcdef'} def update_lookahead(n): for quint in re.finditer(r'(.)\1{4}', key(n)): lookahead[quint.group(1)] = n for i in xrange(1, horizon): update_lookahead(i) for i in itertools.count(): update_lookahead(i + horizon) triple = re.search(r'(.)\1{2}', key(i)) if triple: if lookahead[triple.group(1)] > i: yield i if __name__ == '__main__': keys = otp_keys(1000) for ret in enumerate(keys): print ret
import sys import itertools import re from md5 import md5 puzzle_input = 'abc' # 'yjdafjpo' def key(n): return md5(puzzle_input + str(n)).hexdigest() def otp_keys(horizon): lookahead = {k: -1 for k in '0123456789abcdef'} def update_lookahead(n): for quint in re.finditer(r'(.)\1{4}', key(n)): lookahead[quint.group(1)] = n for i in xrange(1, horizon): update_lookahead(i) for i in itertools.count(): update_lookahead(i + horizon) triple = re.search(r'(.)\1{2}', key(i)) if triple: if lookahead[triple.group(1)] >= i: yield i if __name__ == '__main__': keys = otp_keys(1000) for ret in enumerate(keys): print ret
Handle application erroring to not break the server
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] return subdirs def find_html_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [(o,os.path.sep.join([curdir,o,'html'])) for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'html']))] return dict(subdirs) def import_app(app): try: importlib.import_module(app) except Exception as e: logging.error("Couldn't load app: {0}, error: {1}".format(app, e)) MODULES = {} _html_dirs = find_html_dirs() [ MODULES.update({m_name:{'module': import_app('.'.join(['apps',m_name])), 'html':_html_dirs.get(m_name)}}) for m_name in find_module_dirs() ]
## module loader, goes to see which submodules have 'html' directories ## and declares them at the toplevel import os,importlib def find_module_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))] return subdirs def find_html_dirs(): curdir = os.path.dirname(os.path.abspath(__file__)) subdirs = [(o,os.path.sep.join([curdir,o,'html'])) for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'html']))] return dict(subdirs) MODULES = {} _html_dirs = find_html_dirs() [ MODULES.update({m_name:{'module':importlib.import_module('.'.join(['apps',m_name])), 'html':_html_dirs.get(m_name)}}) for m_name in find_module_dirs() ]
Remove old and incorrect workflow docs
'use strict'; module.exports = { _safeGetEnvString: safeGetEnvString, load, populateEnvironmentVariables, }; /** * Module dependencies. */ const { check, mapValuesDeep } = require('./utils'); const { flow } = require('lodash'); const read = require('read-data'); /** * Assemble a configuration * * @return {Object} */ function load() { return flow(read.sync, populateEnvironmentVariables)('character.yml'); } /** * Populate configuration secrets with values from environment variables * * @param {Object} config * @return {Object} Configuration populated with values from environment variables */ function populateEnvironmentVariables(config) { return mapValuesDeep(config, safeGetEnvString); } /** * Read an environment variable and throw if it is undefined (in production) * * @param {string} name Environment variable name * @return {string} Value of the environment variable */ function safeGetEnvString(name) { if (typeof name === 'string' && name.startsWith('$')) { const variable = name.substring(1, name.length); // using soft assert so that Character can continue in limited mode with an invalid config if ( check( process.env[variable], `Missing environment variable \`${variable}\``, ) ) { return process.env[variable].trim(); } else { return undefined; } } else { return name; } }
/** * Configuration library * * On start-up: * - load a configuration file * - validate the configuration * - populate configuration secrets from environment variables * * On configuration: * - register authenticators */ 'use strict'; module.exports = { _safeGetEnvString: safeGetEnvString, load, populateEnvironmentVariables, }; /** * Module dependencies. */ const { check, mapValuesDeep } = require('./utils'); const { flow } = require('lodash'); const read = require('read-data'); /** * Assemble a configuration * * @return {Object} */ function load() { return flow(read.sync, populateEnvironmentVariables)('character.yml'); } /** * Populate configuration secrets with values from environment variables * * @param {Object} config * @return {Object} Configuration populated with values from environment variables */ function populateEnvironmentVariables(config) { return mapValuesDeep(config, safeGetEnvString); } /** * Read an environment variable and throw if it is undefined (in production) * * @param {string} name Environment variable name * @return {string} Value of the environment variable */ function safeGetEnvString(name) { if (typeof name === 'string' && name.startsWith('$')) { const variable = name.substring(1, name.length); // using soft assert so that Character can continue in limited mode with an invalid config if ( check( process.env[variable], `Missing environment variable \`${variable}\``, ) ) { return process.env[variable].trim(); } else { return undefined; } } else { return name; } }
Set to work with libs package
from libs.ABE_ADCPi import ADCPi from libs.ABE_helpers import ABEHelpers import datetime, time import os, sys """ ================================================ ABElectronics ADC Pi 8-Channel ADC data-logger demo Version 1.0 Created 11/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format Requires python smbus to be installed run with: python demo-read_voltage.py ================================================ Initialise the ADC device using the default addresses and sample rate, change this value if you have changed the address selection jumpers Sample rate can be 12,14, 16 or 18 """ i2c_helper = ABEHelpers() bus = i2c_helper.get_smbus() adc = ADCPi(bus, 0x68, 0x69, 18) while True: # read from 8 adc channels and print it to terminal print("%02f %02f %02f %02f %02f %02f %02f %02f" % (adc.read_voltage(1), adc.read_voltage(2), adc.read_voltage(3), adc.read_voltage(4), adc.read_voltage(5), adc.read_voltage(6), adc.read_voltage(7), adc.read_voltage(8))) # wait 1 second before reading the pins again #time.sleep(1)
from ABE_ADCPi import ADCPi from ABE_helpers import ABEHelpers import datetime, time import os, sys """ ================================================ ABElectronics ADC Pi 8-Channel ADC data-logger demo Version 1.0 Created 11/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format Requires python smbus to be installed run with: python demo-read_voltage.py ================================================ Initialise the ADC device using the default addresses and sample rate, change this value if you have changed the address selection jumpers Sample rate can be 12,14, 16 or 18 """ i2c_helper = ABEHelpers() bus = i2c_helper.get_smbus() adc = ADCPi(bus, 0x68, 0x69, 18) while True: # read from 8 adc channels and print it to terminal print("%02f %02f %02f %02f %02f %02f %02f %02f" % (adc.read_voltage(1), adc.read_voltage(2), adc.read_voltage(3), adc.read_voltage(4), adc.read_voltage(5), adc.read_voltage(6), adc.read_voltage(7), adc.read_voltage(8))) # wait 1 second before reading the pins again #time.sleep(1)
Revert "renamed component to better reflect its responsibility" This reverts commit 8bfe160
import React, {Component} from 'react' import {Redirect, Route, Switch} from 'react-router-dom' import Users from "./users/Users"; import Groups from "./groups/Groups"; import MainMenu from "./MainMenu"; import Home from "./Home"; import Folders from "./folders/Folders"; class MainContainer extends Component { render() { return ( <div> <MainMenu/> <Switch> <Route exact path="/" component={Home}/> <Route path="/users" component={Users}/> <Route path="/groups" component={Groups}/> <Route path="/folders" component={Folders}/> <Redirect to="/"/> </Switch> </div> ); } } export default MainContainer;
import React, {Component} from 'react' import {Redirect, Route, Switch} from 'react-router-dom' import Users from "./users/Users"; import GroupRoutes from "./groups/GroupRoutes"; import MainMenu from "./MainMenu"; import Home from "./Home"; import Folders from "./folders/Folders"; class MainContainer extends Component { render() { return ( <div> <MainMenu/> <Switch> <Route exact path="/" component={Home}/> <Route path="/users" component={Users}/> <Route path="/groups" component={GroupRoutes}/> <Route path="/folders" component={Folders}/> <Redirect to="/"/> </Switch> </div> ); } } export default MainContainer;
Use an integer for hash cost factor
<?php /* * User Login for CouchCMS (https://github.com/cheesypoof/UserLoginForCouchCMS) * Copyright (c) 2014 Increment Web Services (http://incrementwebservices.com/) * Released under the MIT License (https://github.com/cheesypoof/UserLoginForCouchCMS/blob/master/LICENSE) */ if ( !defined( 'K_ADMIN' ) ) { require_once( K_COUCH_DIR . '/addons/password-compatibility.php' ); // Password hashing strength // Leave this alone define( 'USER_PASSWORD_HASH_COST_FACTOR', 10 ); // Life of remember cookies // 2 weeks in seconds define( 'USER_REMEMBER_COOKIE_EXPIRE', 1209600 ); // Enter a random value to make your remember cookies more secure // Changing this invalidates all remember cookies define( 'USER_REMEMBER_COOKIE_SECRET_KEY', '3]UbHj!Q=E?cNN}B(@P,&x(t' ); // Start session if ( !session_id() ) @session_start(); // Check if visitor is logged in or trying to log in with remember cookie if ( isset( $_SESSION['user_id'] ) || isset( $_COOKIE['remember'] ) ) { define( 'AUTHENTICATE', isset( $_SESSION['user_id'] ) ? 'session' : 'cookie' ); // Prevent Couch caching $_GET['nc'] = 1; } }
<?php /* * User Login for CouchCMS (https://github.com/cheesypoof/UserLoginForCouchCMS) * Copyright (c) 2014 Increment Web Services (http://incrementwebservices.com/) * Released under the MIT License (https://github.com/cheesypoof/UserLoginForCouchCMS/blob/master/LICENSE) */ if ( !defined( 'K_ADMIN' ) ) { require_once( K_COUCH_DIR . '/addons/password-compatibility.php' ); // Password hashing strength // Leave this alone define( 'USER_PASSWORD_HASH_COST_FACTOR', '10' ); // Life of remember cookies // 2 weeks in seconds define( 'USER_REMEMBER_COOKIE_EXPIRE', 1209600 ); // Enter a random value to make your remember cookies more secure // Changing this invalidates all remember cookies define( 'USER_REMEMBER_COOKIE_SECRET_KEY', '3]UbHj!Q=E?cNN}B(@P,&x(t' ); // Start session if ( !session_id() ) @session_start(); // Check if visitor is logged in or trying to log in with remember cookie if ( isset( $_SESSION['user_id'] ) || isset( $_COOKIE['remember'] ) ) { define( 'AUTHENTICATE', isset( $_SESSION['user_id'] ) ? 'session' : 'cookie' ); // Prevent Couch caching $_GET['nc'] = 1; } }
HOTFIX: Handle possible error in resource creation
/** * Module dependencies */ var util = require( 'util' ), actionUtil = require( './_util/actionUtil' ), pluralize = require('pluralize'); /** * Create Record * * post /:modelIdentity * * An API call to create and return a single model instance from the data adapter * using the specified criteria. * */ module.exports = function createRecord(req, res) { var Model = actionUtil.parseModel(req); var data = actionUtil.parseValues(req, Model); // Create new instance of model using data from params Model.create(data) .exec( (err, newInstance) => { if (err) return res.negotiate(err) var Q = Model.findOne(newInstance.id); Q.exec( (err, newRecord) => { var id = newRecord.id; delete newRecord.id; res.status(201); return res.json({ data: { id: id.toString(), type: pluralize(req.options.model || req.options.controller), attributes: newRecord } }); }); }); };
/** * Module dependencies */ var util = require( 'util' ), actionUtil = require( './_util/actionUtil' ), pluralize = require('pluralize'); /** * Create Record * * post /:modelIdentity * * An API call to create and return a single model instance from the data adapter * using the specified criteria. * */ module.exports = function createRecord(req, res) { var Model = actionUtil.parseModel(req); var data = actionUtil.parseValues(req, Model); // Create new instance of model using data from params Model.create(data) .exec( (err, newInstance) => { var Q = Model.findOne(newInstance.id); Q.exec( (err, newRecord) => { var id = newRecord.id; delete newRecord.id; res.status(201); return res.json({ data: { id: id.toString(), type: pluralize(req.options.model || req.options.controller), attributes: newRecord } }); }); }); };
Remove pre-release flag as 2.x is mainline now
# Global configuration information used across all the # translations of documentation. # # Import the base theme configuration from cakephpsphinx.config.all import * # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = '2.x' # The search index version. search_version = 'chronos-2' # The marketing display name for the book. version_name = '' # Project name shown in the black header bar project = 'Chronos' # Other versions that display in the version picker menu. version_list = [ {'name': '1.x', 'number': '/chronos/1.x', 'title': '1.x'}, {'name': '2.x', 'number': '/chronos/2.x', 'title': '2.x', 'current': True}, ] # Languages available. languages = ['en', 'fr', 'ja', 'pt'] # The GitHub branch name for this version of the docs # for edit links to point at. branch = '2.x' # Current version being built version = '2.x' # Language in use for this directory. language = 'en' show_root_link = True repository = 'cakephp/chronos' source_path = 'docs/' hide_page_contents = ('search', '404', 'contents')
# Global configuration information used across all the # translations of documentation. # # Import the base theme configuration from cakephpsphinx.config.all import * # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = '2.x' # The search index version. search_version = 'chronos-2' # The marketing display name for the book. version_name = '' # Project name shown in the black header bar project = 'Chronos' # Other versions that display in the version picker menu. version_list = [ {'name': '1.x', 'number': '/chronos/1.x', 'title': '1.x'}, {'name': '2.x', 'number': '/chronos/2.x', 'title': '2.x', 'current': True}, ] # Languages available. languages = ['en', 'fr', 'ja', 'pt'] # The GitHub branch name for this version of the docs # for edit links to point at. branch = '2.x' # Current version being built version = '2.x' # Language in use for this directory. language = 'en' show_root_link = True repository = 'cakephp/chronos' source_path = 'docs/' is_prerelease = True hide_page_contents = ('search', '404', 'contents')
Update stats after every identification.
import inatjs from "inaturalistjs"; import { loadingDiscussionItem, fetchCurrentObservation } from "./current_observation_actions"; import { fetchObservationsStats } from "./observations_stats_actions"; const POST_IDENTIFICATION = "post_identification"; function postIdentification( params ) { return function ( dispatch ) { const body = Object.assign( {}, params ); body.user_id = 1; return inatjs.identifications.create( body ) .then( response => { dispatch( fetchObservationsStats( ) ); return response; } ); }; } function agreeWithCurrentObservation( ) { return function ( dispatch, getState ) { const o = getState( ).currentObservation.observation; dispatch( loadingDiscussionItem( ) ); return dispatch( postIdentification( { observation_id: o.id, taxon_id: o.taxon.id } ) ).then( ( ) => { dispatch( fetchCurrentObservation( ) ); } ); }; } export { postIdentification, POST_IDENTIFICATION, agreeWithCurrentObservation };
import inatjs from "inaturalistjs"; import { loadingDiscussionItem, fetchCurrentObservation } from "./current_observation_actions"; const POST_IDENTIFICATION = "post_identification"; function postIdentification( params ) { return function ( ) { const body = Object.assign( {}, params ); body.user_id = 1; return inatjs.identifications.create( body ); }; } function agreeWithCurrentObservation( ) { return function ( dispatch, getState ) { const o = getState( ).currentObservation.observation; dispatch( loadingDiscussionItem( ) ); return dispatch( postIdentification( { observation_id: o.id, taxon_id: o.taxon.id } ) ).then( ( ) => { dispatch( fetchCurrentObservation( ) ); } ); }; } export { postIdentification, POST_IDENTIFICATION, agreeWithCurrentObservation };
Revert "NoErrorsPlugin is not needed with hot/only-dev-server" This reverts commit 770f167bb66187231c45222a231afb25f5ea6230.
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ "webpack-dev-server/client?http://0.0.0.0:8080", 'webpack/hot/only-dev-server', './src/scripts/router' ], devtool: "eval", debug: true, output: { path: path.join(__dirname, "public"), filename: 'bundle.js' }, resolveLoader: { modulesDirectories: ['node_modules'] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.IgnorePlugin(/vertx/) // https://github.com/webpack/webpack/issues/353 ], resolve: { extensions: ['', '.js', '.cjsx', '.coffee'] }, module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css']}, { test: /\.cjsx$/, loaders: ['react-hot', 'coffee', 'cjsx']}, { test: /\.coffee$/, loader: 'coffee' } ] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ "webpack-dev-server/client?http://0.0.0.0:8080", 'webpack/hot/only-dev-server', './src/scripts/router' ], devtool: "eval", debug: true, output: { path: path.join(__dirname, "public"), filename: 'bundle.js' }, resolveLoader: { modulesDirectories: ['node_modules'] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.IgnorePlugin(/vertx/) // https://github.com/webpack/webpack/issues/353 ], resolve: { extensions: ['', '.js', '.cjsx', '.coffee'] }, module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css']}, { test: /\.cjsx$/, loaders: ['react-hot', 'coffee', 'cjsx']}, { test: /\.coffee$/, loader: 'coffee' } ] } };
Add missing entry points and classifiers.
#!/usr/bin/env python from __future__ import with_statement from setuptools import setup, find_packages from buildkit import * META = get_metadata('neuemux/version.py') setup( name='neuemux', version=META['version'], description='EPP reverse proxy daemons', long_description=read('README'), url='https://github.com/kgaughan/neuemux/', license='MIT', packages=find_packages(exclude='tests'), zip_safe=False, install_requires=read_requirements('requirements.txt'), include_package_data=True, entry_points={ 'console_scripts': [ 'epp-proxyd = neuemux.proxyd:main', 'epp-muxd = neuemux.muxd:main', ], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: System :: Networking', ], author=META['author'], author_email=META['email'] )
#!/usr/bin/env python from __future__ import with_statement from setuptools import setup, find_packages from buildkit import * META = get_metadata('neuemux/version.py') setup( name='neuemux', version=META['version'], description='EPP reverse proxy daemons', long_description=read('README'), url='https://github.com/kgaughan/neuemux/', license='MIT', packages=find_packages(exclude='tests'), zip_safe=False, install_requires=read_requirements('requirements.txt'), include_package_data=True, entry_points={ 'console_scripts': [ ], }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], author=META['author'], author_email=META['email'] )
Add pending() scope to pitch model
<?php class Pitch extends Eloquent { protected $table = 'pitches'; protected $fillable = ['name', 'email', 'blurb', 'status', 'notes', 'author_id', 'story_id']; /** * Class constants */ const UNSEEN = 10; const REVIEW = 20; const REJECTED = 30; const ACCEPTED = 40; const WAITING = 60; const PUBLISHED = 70; static public $statusList = [ Pitch::UNSEEN => 'Unseen', Pitch::REVIEW => 'In Review', Pitch::REJECTED => 'Rejected', Pitch::ACCEPTED => 'Accepted', Pitch::WAITING => 'Waiting for Rev', Pitch::PUBLISHED => 'Published' ]; /** * Pitch belongsTo Author */ public function author() { return $this->belongsTo('Author'); } /** * Pitch belongsTo Story */ public function story() { return $this->belongsTo('Story'); } public function scopePending($query) { return $query->whereIn('status', [ Pitch::UNSEEN, Pitch::REVIEW, Pitch::ACCEPTED, Pitch::WAITING ]); } }
<?php class Pitch extends Eloquent { protected $table = 'pitches'; protected $fillable = ['name', 'email', 'blurb']; /** * Class constants */ const UNSEEN = 10; const REVIEW = 20; const REJECTED = 30; const ACCEPTED = 40; const WAITING = 60; const PUBLISHED = 70; static public $statusList = [ Pitch::UNSEEN => 'Unseen', Pitch::REVIEW => 'In Review', Pitch::REJECTED => 'Rejected', Pitch::ACCEPTED => 'Accepted', Pitch::WAITING => 'Waiting for Rev', Pitch::PUBLISHED => 'Published' ]; /** * Pitch belongsTo Author */ function author() { return $this->belongsTo('Author'); } /** * Pitch belongsTo Story */ function story() { return $this->belongsTo('Story'); } }
Fix KeyError on test with axis
# -*- coding: utf-8 -*- import datetime from openfisca_tunisia import TunisiaTaxBenefitSystem from openfisca_tunisia.scenarios import init_single_entity tax_benefit_system = TunisiaTaxBenefitSystem() def check_1_parent(year = 2011): scenario = init_single_entity( tax_benefit_system.new_scenario(), axes = [[ dict( count = 3, name = 'salaire_imposable', max = 100000, min = 0, ) ]], period = year, parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)), ) simulation = scenario.new_simulation() revenu_disponible = simulation.calculate('revenu_disponible', period = year) def test_1_parent(): for year in range(2009, 2011): yield check_1_parent, year if __name__ == '__main__': import logging import sys logging.basicConfig(level = logging.ERROR, stream = sys.stdout) test_1_parent() # test_1_parent_2_enfants() # test_1_parent_2_enfants_1_column()
# -*- coding: utf-8 -*- import datetime from openfisca_tunisia import TunisiaTaxBenefitSystem from openfisca_tunisia.scenarios import init_single_entity tax_benefit_system = TunisiaTaxBenefitSystem() def check_1_parent(year = 2011): scenario = init_single_entity( tax_benefit_system.new_scenario(), axes = [dict( count = 3, name = 'salaire_imposable', max = 100000, min = 0, )], period = year, parent1 = dict(date_naissance = datetime.date(year - 40, 1, 1)), ) simulation = scenario.new_simulation() revenu_disponible = simulation.calculate('revenu_disponible', period = year) def test_1_parent(): for year in range(2009, 2011): yield check_1_parent, year if __name__ == '__main__': import logging import sys logging.basicConfig(level = logging.ERROR, stream = sys.stdout) test_1_parent() # test_1_parent_2_enfants() # test_1_parent_2_enfants_1_column()
Add Python 3 compatibility to Android symbol checker Make the script that checks for undefined Android symbols compatible with both Python 2 and Python 3, to allow for future updates to the default system Python on our build machines. I'd like to land this before https://github.com/servo/saltfs/pull/249. We currently use Ubuntu 14.04 (an LTS release); Ubuntu is aiming for Python 3 as the default Python in the next LTS release, 16.04, and I'd like to have any scripts be ready for the transition.
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. import sys import re import subprocess symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$") allowed_symbols = frozenset([b'unshare', b'malloc_usable_size']) actual_symbols = set() objdump_output = subprocess.check_output([ 'arm-linux-androideabi-objdump', '-T', 'target/arm-linux-androideabi/debug/libservo.so'] ).split(b'\n') for line in objdump_output: m = symbol_regex.search(line) if m is not None: actual_symbols.add(m.group(2)) difference = actual_symbols - allowed_symbols if len(difference) > 0: human_readable_difference = ", ".join(str(s) for s in difference) print("Unexpected dynamic symbols in binary: {0}".format(human_readable_difference)) sys.exit(-1)
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. import sys import re import subprocess symbol_regex = re.compile("D \*UND\*\t(.*) (.*)$") allowed_symbols = frozenset(['unshare', 'malloc_usable_size']) actual_symbols = set() objdump_output = subprocess.check_output([ 'arm-linux-androideabi-objdump', '-T', 'target/arm-linux-androideabi/debug/libservo.so'] ).split('\n') for line in objdump_output: m = symbol_regex.search(line) if m is not None: actual_symbols.add(m.group(2)) difference = actual_symbols - allowed_symbols if len(difference) > 0: human_readable_difference = ", ".join(str(s) for s in difference) print("Unexpected dynamic symbols in binary: {0}".format(human_readable_difference)) sys.exit(-1)
Comment out encryption by default ine xample
"use strict"; const SqsConsumer = require('aws-sdk-ext').sqs.SqsConsumer, // SqsConsumer = require('../../lib').sqs.SqsConsumer, winston = require('winston'), promisify = require('es6-promisify'), config = require('config'), utils = require('aws-sdk-ext').utils; class SqsConsumerExample extends SqsConsumer { handle(msgBody) { winston.info(`SqsExample::${this.name}:: Handled message: ${JSON.stringify(msgBody)}`); } } /** * Create consumer * * @type {SqsConsumerExample} */ const consumer = new SqsConsumerExample({ name: 'sqs-consumer-example', // This is name of consumer and not queue name conf: { }, // Override conf/default.yaml settings here sqs: null // If not specified, it will automatically be created. }); consumer.on('running', () => { winston.info("SqsExample:: Sending test message"); return consumer.sendMessage({"id": 1, "test": "test"} /*, {"secretKey": "Secret Value"} */) .catch(err => { winston.error(err); throw err; }); }); consumer.on('stopped', () => { winston.info(`SqsExample::${consumer.name}:: Consumer stopped`); }); consumer.start(); // We stop the consumer after 20s. // In actual application, you can stop the queue on SIGINT utils.wait(20000).then(() => consumer.stop());
"use strict"; const SqsConsumer = require('aws-sdk-ext').sqs.SqsConsumer, // SqsConsumer = require('../../lib').sqs.SqsConsumer, winston = require('winston'), promisify = require('es6-promisify'), config = require('config'), utils = require('aws-sdk-ext').utils; class SqsConsumerExample extends SqsConsumer { handle(msgBody) { winston.info(`SqsExample::${this.name}:: Handled message: ${JSON.stringify(msgBody)}`); } } /** * Create consumer * * @type {SqsConsumerExample} */ const consumer = new SqsConsumerExample({ name: 'sqs-consumer-example', // This is name of consumer and not queue name conf: { }, // Override conf/default.yaml settings here sqs: null // If not specified, it will automatically be created. }); consumer.on('running', () => { winston.info("SqsExample:: Sending test message"); return consumer.sendMessage({"id": 1, "test": "test"}, {"secretKey": "Secret Value"}) .catch(err => { winston.error(err); throw err; }); }); consumer.on('stopped', () => { winston.info(`SqsExample::${consumer.name}:: Consumer stopped`); }); consumer.start(); // We stop the consumer after 20s. // In actual application, you can stop the queue on SIGINT utils.wait(20000).then(() => consumer.stop());
Handle list of media/collections that aren't clickable
import PropTypes from 'prop-types'; import React from 'react'; import { Col } from 'react-flexbox-grid/lib'; import { DeleteButton } from './IconButton'; const SourceOrCollectionWidget = (props) => { const { object, onDelete, onClick, children } = props; const isCollection = object.tags_id !== undefined; const typeClass = isCollection ? 'collection' : 'source'; const objectId = object.id || (isCollection ? object.tags_id : object.media_id); const name = isCollection ? (object.name || object.label || object.tag) : (object.name || object.label || object.url); // link the text if there is a click handler defined let text = name; if (onClick) { text = (<a href="#" onClick={onClick}>{name}</a>); } return ( <div className={`media-widget ${typeClass}`} key={`media-widget${objectId}`} > <Col> {text} {children} </Col> <Col> {onDelete && <DeleteButton onClick={onDelete} />} </Col> </div> ); }; SourceOrCollectionWidget.propTypes = { object: PropTypes.object.isRequired, onDelete: PropTypes.func, onClick: PropTypes.func, children: PropTypes.node, }; export default SourceOrCollectionWidget;
import PropTypes from 'prop-types'; import React from 'react'; import { Col } from 'react-flexbox-grid/lib'; import { DeleteButton } from './IconButton'; const SourceOrCollectionWidget = (props) => { const { object, onDelete, onClick, children } = props; const isCollection = object.tags_id !== undefined; const typeClass = isCollection ? 'collection' : 'source'; const objectId = object.id || (isCollection ? object.tags_id : object.media_id); const name = isCollection ? (object.name || object.label || object.tag) : (object.name || object.label || object.url); return ( <div className={`media-widget ${typeClass}`} key={`media-widget${objectId}`} > <Col> <a href="#" onClick={onClick}>{name}</a> {children} </Col> <Col> <DeleteButton onClick={onDelete} /> </Col> </div> ); }; SourceOrCollectionWidget.propTypes = { object: PropTypes.object.isRequired, onDelete: PropTypes.func, onClick: PropTypes.func, children: PropTypes.node, }; export default SourceOrCollectionWidget;
Make sure that magic quotes are disabled for PHP < 5.4
<?php // PHP 5.3.3 minimum if (version_compare(PHP_VERSION, '5.3.3', '<')) { die('This software require PHP 5.3.3 minimum'); } // Checks for PHP < 5.4 if (version_compare(PHP_VERSION, '5.4.0', '<')) { // Short tags must be enabled for PHP < 5.4 if (! ini_get('short_open_tag')) { die('This software require to have short tags enabled if you have PHP < 5.4 ("short_open_tag = On")'); } // Magic quotes are deprecated since PHP 5.4 if (get_magic_quotes_gpc()) { die('This software require to have "Magic quotes" disabled, it\'s deprecated since PHP 5.4 ("magic_quotes_gpc = Off")'); } } // Check extension: PDO Sqlite if (! extension_loaded('pdo_sqlite')) { die('PHP extension required: pdo_sqlite'); } // Check extension: mbstring if (! extension_loaded('mbstring')) { die('PHP extension required: mbstring'); } // Check if /data is writeable if (! is_writable('data')) { die('The directory "data" must be writeable by your web server user'); } // Include password_compat for PHP < 5.5 if (version_compare(PHP_VERSION, '5.5.0', '<')) { require __DIR__.'/vendor/password.php'; }
<?php // PHP 5.3 minimum if (version_compare(PHP_VERSION, '5.3.3', '<')) { die('This software require PHP 5.3.3 minimum'); } // Short tags must be enabled for PHP < 5.4 if (version_compare(PHP_VERSION, '5.4.0', '<')) { if (! ini_get('short_open_tag')) { die('This software require to have short tags enabled, check your php.ini => "short_open_tag = On"'); } } // Check extension: PDO Sqlite if (! extension_loaded('pdo_sqlite')) { die('PHP extension required: pdo_sqlite'); } // Check extension: mbstring if (! extension_loaded('mbstring')) { die('PHP extension required: mbstring'); } // Check if /data is writeable if (! is_writable('data')) { die('The directory "data" must be writeable by your web server user'); } // Include password_compat for PHP < 5.5 if (version_compare(PHP_VERSION, '5.5.0', '<')) { require __DIR__.'/vendor/password.php'; }
Update date prop name now that we're proxying
// @flow import * as React from 'react' import moment from 'moment-timezone' import {Alert} from 'react-native' import {Column, Row} from '../components/layout' import {ListRow, Detail, Title} from '../components/list' import type {UpdateType} from './types' type Props = { onPress: string => any, update: UpdateType, } export class UpdatesRow extends React.PureComponent<Props> { _onPress = () => { if (!this.props.update.link) { Alert.alert('There is nowhere to go for this update') return } this.props.onPress(this.props.update.link) } render() { const {update} = this.props const posted = moment(update.datePublished).format('MMM Do YYYY') return ( <ListRow arrowPosition="center" onPress={this._onPress}> <Row alignItems="center"> <Column flex={1}> <Title lines={2}>{posted}</Title> <Detail lines={3}>{update.title}</Detail> </Column> </Row> </ListRow> ) } }
// @flow import * as React from 'react' import moment from 'moment-timezone' import {Alert} from 'react-native' import {Column, Row} from '../components/layout' import {ListRow, Detail, Title} from '../components/list' import type {UpdateType} from './types' type Props = { onPress: string => any, update: UpdateType, } export class UpdatesRow extends React.PureComponent<Props> { _onPress = () => { if (!this.props.update.link) { Alert.alert('There is nowhere to go for this update') return } this.props.onPress(this.props.update.link) } render() { const {update} = this.props const posted = moment(update.date).format('MMM Do YYYY') return ( <ListRow arrowPosition="center" onPress={this._onPress}> <Row alignItems="center"> <Column flex={1}> <Title lines={2}>{posted}</Title> <Detail lines={3}>{update.title}</Detail> </Column> </Row> </ListRow> ) } }
Add Rushing Jade Wind to CHI_SPENDERS[] constant
import SPELLS from 'common/SPELLS'; export const ABILITIES_AFFECTED_BY_MASTERY = [ SPELLS.TIGER_PALM.id, SPELLS.BLACKOUT_KICK.id, SPELLS.FISTS_OF_FURY_CAST.id, SPELLS.RISING_SUN_KICK.id, SPELLS.CHI_WAVE_TALENT.id, SPELLS.FIST_OF_THE_WHITE_TIGER_TALENT.id, SPELLS.SPINNING_CRANE_KICK.id, SPELLS.FLYING_SERPENT_KICK.id, SPELLS.CRACKLING_JADE_LIGHTNING.id, SPELLS.WHIRLING_DRAGON_PUNCH_TALENT.id, SPELLS.TOUCH_OF_DEATH.id, SPELLS.CHI_BURST_TALENT.id, SPELLS.RUSHING_JADE_WIND_TALENT_WINDWALKER.id, ]; export const CHI_SPENDERS = [ SPELLS.BLACKOUT_KICK.id, SPELLS.RISING_SUN_KICK.id, SPELLS.FISTS_OF_FURY_CAST.id, SPELLS.SPINNING_CRANE_KICK.id, SPELLS.RUSHING_JADE_WIND_TALENT_WINDWALKER.id, ]; export default CHI_SPENDERS;
import SPELLS from 'common/SPELLS'; export const ABILITIES_AFFECTED_BY_MASTERY = [ SPELLS.TIGER_PALM.id, SPELLS.BLACKOUT_KICK.id, SPELLS.FISTS_OF_FURY_CAST.id, SPELLS.RISING_SUN_KICK.id, SPELLS.CHI_WAVE_TALENT.id, SPELLS.FIST_OF_THE_WHITE_TIGER_TALENT.id, SPELLS.SPINNING_CRANE_KICK.id, SPELLS.FLYING_SERPENT_KICK.id, SPELLS.CRACKLING_JADE_LIGHTNING.id, SPELLS.WHIRLING_DRAGON_PUNCH_TALENT.id, SPELLS.TOUCH_OF_DEATH.id, SPELLS.CHI_BURST_TALENT.id, SPELLS.RUSHING_JADE_WIND_TALENT_WINDWALKER.id, ]; export const CHI_SPENDERS = [ SPELLS.BLACKOUT_KICK.id, SPELLS.RISING_SUN_KICK.id, SPELLS.FISTS_OF_FURY_CAST.id, SPELLS.SPINNING_CRANE_KICK.id, ]; export default CHI_SPENDERS;
Add rendering of game to DOM
var Game = require('./models/game'), gameRenderElement, bowlingGame, bowlingBtn, renderGame, onFinish, onBowl, onLoad; // Create instance of bowling game bowlingGame = new Game(); /** * Render the game state to the appropriate element * @method renderGame */ renderGame = function () { gameRenderElement.innerHTML = bowlingGame.getHTML(); }; /** * Set up bowling game on document load * @method onLoad */ onLoad = function () { bowlingGame.init(); gameRenderElement = document.getElementById('game'); bowlingBtn = document.getElementById('bowling-btn'); bowlingBtn.addEventListener('click', onBowl, false); }; /** * Roll a bowling pin * @method onBowl */ onBowl = function () { bowlingGame.roll(); renderGame(); if (bowlingGame.isFinished()) { onFinish(); } }; /** * Complete the game * @method onFinish */ onFinish = function () { // Get rid of the "Bowl" button bowlingBtn.parentNode.removeChild(bowlingBtn); console.log('Finished with a score of ' + bowlingGame.getScore()); }; // Attach listener to DOM load event document.addEventListener('DOMContentLoaded', onLoad);
var Game = require('./models/game'), bowlingGame, bowlingBtn, onFinish, onBowl, onLoad; // Create instance of bowling game bowlingGame = new Game(); /** * Set up bowling game on document load * @method onLoad */ onLoad = function () { bowlingGame.init(); bowlingBtn = document.getElementById('bowling-btn'); bowlingBtn.addEventListener('click', onBowl, false); }; /** * Roll a bowling pin * @method onBowl */ onBowl = function () { bowlingGame.roll(); if (bowlingGame.isFinished()) { onFinish(); } }; /** * Complete the game * @method onFinish */ onFinish = function () { // Get rid of the "Bowl" button bowlingBtn.parentNode.removeChild(bowlingBtn); console.log('Finished with a score of ' + bowlingGame.getScore()); }; // Attach listener to DOM load event document.addEventListener('DOMContentLoaded', onLoad);
Add newline at end of file
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class Google_Http_RequestTest extends PHPUnit_Framework_TestCase { public function testBaseComponentDefault() { $request = new Google_Http_Request("https://api.example.com/base"); $this->assertEquals("https://api.example.com", $request->getBaseComponent()); } public function testBaseComponentExplicitStripsSlashes() { $request = new Google_Http_Request("https://api.example.com/base"); $request->setBaseComponent("https://other.example.com/"); $this->assertEquals("https://other.example.com", $request->getBaseComponent()); } public function testBaseComponentWithPathExplicitStripsSlashes() { $request = new Google_Http_Request("https://api.example.com/base"); $request->setBaseComponent("https://other.example.com/path/"); $this->assertEquals("https://other.example.com/path", $request->getBaseComponent()); } }
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class Google_Http_RequestTest extends PHPUnit_Framework_TestCase { public function testBaseComponentDefault() { $request = new Google_Http_Request("https://api.example.com/base"); $this->assertEquals("https://api.example.com", $request->getBaseComponent()); } public function testBaseComponentExplicitStripsSlashes() { $request = new Google_Http_Request("https://api.example.com/base"); $request->setBaseComponent("https://other.example.com/"); $this->assertEquals("https://other.example.com", $request->getBaseComponent()); } public function testBaseComponentWithPathExplicitStripsSlashes() { $request = new Google_Http_Request("https://api.example.com/base"); $request->setBaseComponent("https://other.example.com/path/"); $this->assertEquals("https://other.example.com/path", $request->getBaseComponent()); } }
Add addMasterListItems to customerInvoice reducer
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ /** * Method using a factory pattern variant to get a reducer * for a particular page or page style. * * For a new page - create a constant object with the * methods from reducerMethods which are composed to create * a reducer. Add to PAGE_REDUCERS. * * Each key value pair in a reducer object should be in the form * action type: reducer function, returning a new state object * */ import { filterData, editTotalQuantity, focusNextCell, selectRow, deselectRow, deselectAll, focusCell, sortData, openBasicModal, closeBasicModal, addMasterListItems, } from './reducerMethods'; /** * Used for actions that should be in all pages using a data table. */ const BASE_TABLE_PAGE_REDUCER = { focusNextCell, focusCell, sortData, }; const customerInvoice = { ...BASE_TABLE_PAGE_REDUCER, filterData, editTotalQuantity, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, addMasterListItems, }; const PAGE_REDUCERS = { customerInvoice, }; const getReducer = page => { const reducer = PAGE_REDUCERS[page]; return (state, action) => { const { type } = action; if (!reducer[type]) return state; return reducer[type](state, action); }; }; export default getReducer;
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ /** * Method using a factory pattern variant to get a reducer * for a particular page or page style. * * For a new page - create a constant object with the * methods from reducerMethods which are composed to create * a reducer. Add to PAGE_REDUCERS. * * Each key value pair in a reducer object should be in the form * action type: reducer function, returning a new state object * */ import { filterData, editTotalQuantity, focusNextCell, selectRow, deselectRow, deselectAll, focusCell, sortData, openBasicModal, closeBasicModal, } from './reducerMethods'; /** * Used for actions that should be in all pages using a data table. */ const BASE_TABLE_PAGE_REDUCER = { focusNextCell, focusCell, sortData, }; const customerInvoice = { ...BASE_TABLE_PAGE_REDUCER, filterData, editTotalQuantity, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, }; const PAGE_REDUCERS = { customerInvoice, }; const getReducer = page => { const reducer = PAGE_REDUCERS[page]; return (state, action) => { const { type } = action; if (!reducer[type]) return state; return reducer[type](state, action); }; }; export default getReducer;
Update file comment block for the command `secret:generate`
<?php /** * This file is part of the PHPLucidFrame library. * The script executes the command `php lucidframe secret:generate [options]` * * @package LucidFrame\Console * @since PHPLucidFrame v 1.11.0 * @copyright Copyright (c), PHPLucidFrame. * @author Sithu K. <cithukyaw@gmail.com> * @link http://phplucidframe.sithukyaw.com * @license http://www.opensource.org/licenses/mit-license.php MIT License * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE.txt */ _consoleCommand('secret:generate') ->setDescription('Generate a secret hash key') ->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5') ->addOption('data', 'd', 'Secret text to be hashed.') ->setDefinition(function(\LucidFrame\Console\Command $cmd) { $data = $cmd->getOption('data'); if (!$data) { $data = time(); } $secret = hash($cmd->getOption('method'), $data) . "\n"; $file = INC . '.secret'; file_put_contents($file, $secret); }) ->register();
<?php /** * This file is part of the PHPLucidFrame library. * The script executes the command `php lucidframe secret:generate` * * @package LucidFrame\Console * @since PHPLucidFrame v 1.11.0 * @copyright Copyright (c), PHPLucidFrame. * @author Sithu K. <cithukyaw@gmail.com> * @link http://phplucidframe.sithukyaw.com * @license http://www.opensource.org/licenses/mit-license.php MIT License * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE.txt */ _consoleCommand('secret:generate') ->setDescription('Generate a secret hash key') ->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5') ->addOption('data', 'd', 'Secret text to be hashed.') ->setDefinition(function(\LucidFrame\Console\Command $cmd) { $data = $cmd->getOption('data'); if (!$data) { $data = time(); } $secret = hash($cmd->getOption('method'), $data) . "\n"; $file = INC . '.secret'; file_put_contents($file, $secret); }) ->register();
Fix packaging of data files
from setuptools import setup, find_packages setup( name="openslides-gui", version="1.0.0dev1", description="GUI frontend for openslides", long_description="", # TODO url='http://openslides.org', author='OpenSlides-Team, see AUTHORS', author_email='support@openslides.org', license='MIT', keywords='OpenSlides', classifiers=[ # TODO: fill those ], packages=find_packages(), install_requires=[ "openslides", "wxPython-Phoenix", "psutil", ], package_data={ "openslides_gui": [ "data/openslides.ico", "data/openslides-logo_wide.png", ], }, entry_points={ "gui_scripts": [ "openslides-gui=openslides_gui.gui:main", ], } )
from setuptools import setup, find_packages setup( name="openslides-gui", version="1.0.0dev1", description="GUI frontend for openslides", long_description="", # TODO url='http://openslides.org', author='OpenSlides-Team, see AUTHORS', author_email='support@openslides.org', license='MIT', keywords='OpenSlides', classifiers=[ # TODO: fill those ], packages=find_packages(), include_package_data=True, install_requires=[ "openslides", "wxPython-Phoenix", "psutil", ], package_data={ "openslides_gui": [ "data/openslides.ico", "data/openslides-logo_wide.png", ], }, entry_points={ "gui_scripts": [ "openslides-gui=openslides_gui.gui:main", ], } )
Remove debug segments on Dom
(function(){ angular .module('linguine', [ 'flash', 'ui.router', 'ui.bootstrap', 'linguine.corpora', 'angularSpinner', 'linguine.analysis' ]) .config(config); function config($stateProvider, $locationProvider, $urlRouterProvider, $compileProvider){ $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); $compileProvider.debugInfoEnabled(false); $stateProvider .state('linguine', { url: '', abstract: true, template: '<div ui-view />' }) .state('linguine.index', { url: '/', templateUrl: 'templates/home/index', controller: 'IndexController' }); } })();
(function(){ angular .module('linguine', [ 'flash', 'ui.router', 'ui.bootstrap', 'linguine.corpora', 'angularSpinner', 'linguine.analysis' ]) .config(config); function config($stateProvider, $locationProvider, $urlRouterProvider){ $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); $stateProvider .state('linguine', { url: '', abstract: true, template: '<div ui-view />' }) .state('linguine.index', { url: '/', templateUrl: 'templates/home/index', controller: 'IndexController' }); } })();
Make the packaging process include the tests.
from distutils.core import setup import os setup(name='django-flashpolicies', version='1.3.1', description='Flash cross-domain policies for Django sites', long_description=open(os.path.join(os.path.dirname(__file__), 'README')).read(), author='James Bennett', author_email='james@b-list.org', url='http://bitbucket.org/ubernostrum/django-flashpolicies/overview/', download_url='http://bitbucket.org/ubernostrum/django-flashpolicies/downloads/django-flashpolicies-1.3.tar.gz', packages=['flashpolicies', 'flashpolicies.tests'], classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
from distutils.core import setup import os setup(name='django-flashpolicies', version='1.3', description='Flash cross-domain policies for Django sites', long_description=open(os.path.join(os.path.dirname(__file__), 'README')).read(), author='James Bennett', author_email='james@b-list.org', url='http://bitbucket.org/ubernostrum/django-flashpolicies/overview/', download_url='http://bitbucket.org/ubernostrum/django-flashpolicies/downloads/django-flashpolicies-1.3.tar.gz', packages=['flashpolicies'], classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
Load footer plugin at hook.mounted.Isolate footer to an article element.
(($docsify)=>{ if(!$docsify){console.err("$docsify no exist.")} if ($docsify) { $docsify.plugins = [].concat(docsifyFooter(), $docsify.plugins) } function docsifyFooter() { return function(hook, vm) { hook.mounted(function() { var section = document.querySelector("section.content"); var footer = "<hr/><footer>Set your footer in docsify config (window.$docsify.footer)</footer>"; if(typeof $docsify.footer === "function"){ footer = $docsify.footer(); }else if($docsify.footer){ footer = $docsify.footer; } var article = document.createElement("article"); article.setAttribute("footer",""); article.className = "markdown-section"; article.innerHTML = footer; section.appendChild(article); }) }; } })(window.$docsify);
(($docsify)=>{ if(!$docsify){console.err("$docsify no exist.")} if ($docsify) { $docsify.plugins = [].concat(docsifyFooter(), $docsify.plugins) } function docsifyFooter() { return function(hook, vm) { hook.afterEach(function(html,next) { var footer = "<hr/><footer>Set your footer in docsify config (window.$docsify.footer)</footer>"; if(typeof $docsify.footer === "function"){ footer = $docsify.footer(); }else if($docsify.footer){ footer = $docsify.footer; } next (html + footer); }) }; } })(window.$docsify);
Remove auto start in loop with "while True".
import logging.config import sys import os import serial from amber.hokuyo.hokuyo_common import HokuyoController from amber.tools import serial_port, config __author__ = 'paoolo' LOGGER_NAME = 'AmberPipes' pwd = os.path.dirname(os.path.abspath(__file__)) config.add_config_ini('%s/hokuyo.ini' % pwd) logging.config.fileConfig('%s/hokuyo.ini' % pwd) SERIAL_PORT = config.HOKUYO_SERIAL_PORT BAUD_RATE = config.HOKUYO_BAUD_RATE TIMEOUT = 0.1 if __name__ == '__main__': logger = logging.getLogger(LOGGER_NAME) serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT) port = serial_port.SerialPort(serial) controller = HokuyoController(sys.stdin, sys.stdout, port) controller()
import logging.config import sys import os import time import serial from amber.hokuyo.hokuyo_common import HokuyoController from amber.tools import serial_port, config __author__ = 'paoolo' LOGGER_NAME = 'AmberPipes' pwd = os.path.dirname(os.path.abspath(__file__)) config.add_config_ini('%s/hokuyo.ini' % pwd) logging.config.fileConfig('%s/hokuyo.ini' % pwd) SERIAL_PORT = config.HOKUYO_SERIAL_PORT BAUD_RATE = config.HOKUYO_BAUD_RATE TIMEOUT = 0.1 if __name__ == '__main__': logger = logging.getLogger(LOGGER_NAME) serial = serial.Serial(port=SERIAL_PORT, baudrate=BAUD_RATE, timeout=TIMEOUT) port = serial_port.SerialPort(serial) while True: # noinspection PyBroadException try: controller = HokuyoController(sys.stdin, sys.stdout, port) controller() except BaseException as e: logger.error('error: %s' % str(e)) time.sleep(5)
Add @Transactional to the save method.
/* * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics * * 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.search.nibrs.stagingdata.service; import javax.transaction.Transactional; import org.search.nibrs.stagingdata.model.segment.ArrestReportSegment; import org.search.nibrs.stagingdata.repository.segment.ArrestReportSegmentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Service to process Group B Arrest Report. * */ @Service public class ArrestReportService { @Autowired ArrestReportSegmentRepository arrestReportSegmentRepository; @Transactional public ArrestReportSegment saveArrestReportSegment(ArrestReportSegment arrestReportSegment){ return arrestReportSegmentRepository.save(arrestReportSegment); } public ArrestReportSegment findArrestReportSegment(Integer id){ return arrestReportSegmentRepository.findOne(id); } }
/* * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics * * 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.search.nibrs.stagingdata.service; import org.search.nibrs.stagingdata.model.segment.ArrestReportSegment; import org.search.nibrs.stagingdata.repository.segment.ArrestReportSegmentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Service to process Group B Arrest Report. * */ @Service public class ArrestReportService { @Autowired ArrestReportSegmentRepository arrestReportSegmentRepository; public ArrestReportSegment saveArrestReportSegment(ArrestReportSegment arrestReportSegment){ return arrestReportSegmentRepository.save(arrestReportSegment); } public ArrestReportSegment findArrestReportSegment(Integer id){ return arrestReportSegmentRepository.findOne(id); } }
Set clobber as false on clone dir. Add ncp module link on clone dir documentation
/** * Node modules */ const path = require('path'); const util = require('util'); const ncp = util.promisify(require('ncp').ncp); /** * FileSystem helper. * * @class FileSystem * @package Helpers * @author Patrick Ferreira <paatrickferreira@gmail.com> */ class FileSystem { /** * Checks if a file is an image based on a list of valid extensions. * * @static * @param {string} file * @returns {boolean} * * @memberof FileSystem */ static isImage(file) { const ext = file.split('.').pop().toLocaleLowerCase(); const validExtensions = ['png', 'jpg', 'jpeg']; return validExtensions.includes(ext); } /** * Clones the origial dir with a "-tinyme-optimized" prefix at the same level of the * original dir. * * @static * @param {string} dir * @param {string} [prefix='tinyme-optimized'] * @returns {string} * * @see {@link https://github.com/AvianFlu/ncp} for NCP module information. * @memberof FileSystem */ static async cloneDir(dir, prefix = 'tinyme-optimized') { const originalDir = path.resolve(dir); const clonedDir = `${originalDir}-${prefix}`; try { await ncp(originalDir, clonedDir, { clobber: false }); } catch (err) { throw new Error('Could not clone given dir'); } return clonedDir; } } module.exports = FileSystem;
/** * Node modules */ const path = require('path'); const util = require('util'); const ncp = util.promisify(require('ncp').ncp); /** * FileSystem helper. * * @class FileSystem * @package Helpers * @author Patrick Ferreira <paatrickferreira@gmail.com> */ class FileSystem { /** * Checks if a file is an image based on a list of valid extensions. * * @static * @param {string} file * @returns {boolean} * * @memberof FileSystem */ static isImage(file) { const ext = file.split('.').pop().toLocaleLowerCase(); const validExtensions = ['png', 'jpg', 'jpeg']; return validExtensions.includes(ext); } /** * Clones the origial dir with a "-tinyme-optimized" prefix at the same level of the * original dir. * * @static * @param {string} dir * @param {string} [prefix='tinyme-optimized'] * @returns {string} * * @memberof FileSystem */ static async cloneDir(dir, prefix = 'tinyme-optimized') { const originalDir = path.resolve(dir); const clonedDir = `${originalDir}-${prefix}`; try { await ncp(originalDir, clonedDir); } catch (err) { throw new Error('Could not clone given dir'); } return clonedDir; } } module.exports = FileSystem;
Fix bug in detecting facebook feeds
<?php class Af_FacebookFeedImages extends Plugin { private $host; function about() { return array( 1.1, "Insert larger images in Facebook feeds.", "kuc" ); } function api_version() { return 2; } function init($host) { $this->host = $host; $host->add_hook($host::HOOK_ARTICLE_FILTER, $this); } function hook_article_filter($article) { $owner_uid = $article["owner_uid"]; if (strpos($article["link"], "https://www.facebook.com/") === 0) { if (strpos($article["plugin_data"], "facebookfeedimages,$owner_uid:") === FALSE) { if (strpos($article["content"], '_s.jpg"') !== FALSE) { $article["content"] = str_replace('_s.jpg"', '_n.jpg"', $article["content"]); $article["plugin_data"] = "facebookfeedimages,$owner_uid:" . $article["plugin_data"]; } } else if (isset($article["stored"]["content"])) { $article["content"] = $article["stored"]["content"]; } } return $article; } }
<?php class Af_FacebookFeedImages extends Plugin { private $host; function about() { return array( 1.0, "Insert larger images in Facebook feeds.", "kuc" ); } function api_version() { return 2; } function init($host) { $this->host = $host; $host->add_hook($host::HOOK_ARTICLE_FILTER, $this); } function hook_article_filter($article) { $owner_uid = $article["owner_uid"]; if (strpos($article["link"], "facebook.com/photo.php") !== FALSE) { if (strpos($article["plugin_data"], "facebookfeedimages,$owner_uid:") === FALSE) { if (strpos($article["content"], '_s.jpg"') !== FALSE) { $article["content"] = str_replace('_s.jpg"', '_n.jpg"', $article["content"]); $article["plugin_data"] = "facebookfeedimages,$owner_uid:" . $article["plugin_data"]; } } else if (isset($article["stored"]["content"])) { $article["content"] = $article["stored"]["content"]; } } return $article; } }
Refactor code and add ability for many input.
from flask import Flask, request, redirect import twilio.twiml app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def root(): """Respond to incoming requests""" resp = twilio.twiml.Response() with resp.gather(finishOnKey="*", action="/handle-key", method="POST") as g: g.say("Play that trill trap shit bro") return str(resp) @app.route("/handle-key", methods=['GET', 'POST']) def handle_key(): digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = twilio.twiml.Response() resp.play("http://demo.twilio.com/hellomonkey/monkey.mp3") return str(resp) else: return redirect("/") if __name__ == "__main__": app.run(debug=True)
from flask import Flask, request, redirect import twilio.twiml app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello_monkey(): """Respond to incoming requests""" resp = twilio.twiml.Response() with resp.gather(numDigits=1, action="/handle-key", method="POST") as g: g.say("press 1 or something") return str(resp) @app.route("/handle-key", methods=['GET', 'POST']) def handle_key(): digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = twilio.twiml.Response() resp.play("http://demo.twilio.com/hellomonkey/monkey.mp3") return str(resp) else: return redirect("/") if __name__ == "__main__": app.run(debug=True)
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-typography/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-typography/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
Refactor in progress - cleaning...
package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } }
package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { private static String projectKey = "TPT"; private static String repositorySlug = "testrepository"; public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } }
fix(bookmarks): Remove Highlights from Bookmarks page
const React = require("react"); const {connect} = require("react-redux"); const GroupedActivityFeed = require("components/ActivityFeed/ActivityFeed"); const {RequestMoreBookmarks} = require("common/action-manager").actions; const LoadMore = require("components/LoadMore/LoadMore"); const TimelineBookmarks = React.createClass({ getMore() { const bookmarks = this.props.Bookmarks.rows; if (!bookmarks.length) { return; } const beforeDate = bookmarks[bookmarks.length - 1].lastModified; this.props.dispatch(RequestMoreBookmarks(beforeDate)); }, render() { const props = this.props; return (<div className="wrapper"> <GroupedActivityFeed title="Just now" sites={props.Bookmarks.rows} length={20} dateKey="bookmarkDateCreated" /> <LoadMore loading={props.Bookmarks.isLoading} hidden={!props.Bookmarks.canLoadMore || !props.Bookmarks.rows.length} onClick={this.getMore} label="See more activity"/> </div>); } }); TimelineBookmarks.propTypes = { Bookmarks: React.PropTypes.object.isRequired }; module.exports = connect(state => { return { Bookmarks: state.Bookmarks }; })(TimelineBookmarks); module.exports.TimelineBookmarks = TimelineBookmarks;
const React = require("react"); const {connect} = require("react-redux"); const {selectSpotlight} = require("selectors/selectors"); const GroupedActivityFeed = require("components/ActivityFeed/ActivityFeed"); const Spotlight = require("components/Spotlight/Spotlight"); const {RequestMoreBookmarks} = require("common/action-manager").actions; const LoadMore = require("components/LoadMore/LoadMore"); const TimelineBookmarks = React.createClass({ getMore() { const bookmarks = this.props.Bookmarks.rows; if (!bookmarks.length) { return; } const beforeDate = bookmarks[bookmarks.length - 1].lastModified; this.props.dispatch(RequestMoreBookmarks(beforeDate)); }, render() { const props = this.props; return (<div className="wrapper"> <Spotlight sites={props.Spotlight.rows} /> <GroupedActivityFeed title="Just now" sites={props.Bookmarks.rows} length={20} dateKey="bookmarkDateCreated" /> <LoadMore loading={props.Bookmarks.isLoading} hidden={!props.Bookmarks.canLoadMore || !props.Bookmarks.rows.length} onClick={this.getMore} label="See more activity"/> </div>); } }); TimelineBookmarks.propTypes = { Spotlight: React.PropTypes.object.isRequired, Bookmarks: React.PropTypes.object.isRequired }; module.exports = connect(state => { return { Spotlight: selectSpotlight(state), Bookmarks: state.Bookmarks }; })(TimelineBookmarks); module.exports.TimelineBookmarks = TimelineBookmarks;
Update for fixing odd Japanese Selenium is "セレニウム" in Japanese. (Most people don't write Selenium in Japanese, by the way)
# Japanese Language Test - Python 3 Only! from seleniumbase.translate.japanese import セレニウムテストケース # noqa class テストクラス(セレニウムテストケース): # noqa def test_例1(self): self.URLを開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title="メインページに移動する"]') self.テキストを更新("#searchInput", "アニメ") self.クリックして("#searchButton") self.テキストを確認する("アニメ", "#firstHeading") self.テキストを更新("#searchInput", "寿司") self.クリックして("#searchButton") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]')
# Japanese Language Test - Python 3 Only! from seleniumbase.translate.japanese import セレンテストケース # noqa class テストクラス(セレンテストケース): # noqa def test_例1(self): self.URLを開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title="メインページに移動する"]') self.テキストを更新("#searchInput", "アニメ") self.クリックして("#searchButton") self.テキストを確認する("アニメ", "#firstHeading") self.テキストを更新("#searchInput", "寿司") self.クリックして("#searchButton") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]')
FAQ: Add the required-attribute when no is selected.
/** * Interaction for the faq module * * @author Annelies Van Extergem <annelies@netlash.com> * @author Jelmer Snoeck <jelmer.snoeck@netlash.com> * @author Thomas Deceuninck <thomas@fronto.be> */ jsFrontend.faq = { // init, something like a constructor init: function() { if($('#faqFeedbackForm').length > 0) jsFrontend.faq.feedback.init(); } } // feedback form jsFrontend.faq.feedback = { init: function() { // useful status has been changed $('#usefulY, #usefulN').on('click', function() { // get useful status var useful = ($('#usefulY').attr('checked') ? true : false); // show or hide the form if(useful) { $('#message').prop('required', false); $('form#feedback').submit(); } else { $('#feedbackNoInfo').show(); $('#message').prop('required', true); } }); } } $(jsFrontend.faq.init);
/** * Interaction for the faq module * * @author Annelies Van Extergem <annelies@netlash.com> * @author Jelmer Snoeck <jelmer.snoeck@netlash.com> * @author Thomas Deceuninck <thomas@fronto.be> */ jsFrontend.faq = { // init, something like a constructor init: function() { if($('#faqFeedbackForm').length > 0) jsFrontend.faq.feedback.init(); } } // feedback form jsFrontend.faq.feedback = { init: function() { // useful status has been changed $('#usefulY, #usefulN').on('click', function() { // get useful status var useful = ($('#usefulY').attr('checked') ? true : false); // show or hide the form if(useful) { $('form#feedback').submit(); } else { $('#feedbackNoInfo').show(); } }); } } $(jsFrontend.faq.init);
Fix menu in template list
import { provideHooks } from 'redial' import { connect } from 'react-redux' import MobSelectors from '~client/mobrender/redux/selectors' import { toggleMobilizationMenu } from '~client/mobrender/redux/action-creators' import * as TemplateActions from '~mobilizations/templates/action-creators' import * as TemplateSelectors from '~mobilizations/templates/selectors' import Page from './page' const redial = { fetch: ({ dispatch, getState, params }) => { const state = getState() const promises = [] !TemplateSelectors.isLoaded(state) && promises.push( dispatch(TemplateActions.asyncFetch()) ) promises.push(dispatch(toggleMobilizationMenu(undefined))) return Promise.all(promises) } } const mapStateToProps = state => ({ loading: TemplateSelectors.isLoading(state), menuActiveIndex: MobSelectors(state).getMobilizationMenuActive(), mobilizationTemplates: TemplateSelectors.getCustomTemplates(state) }) const mapActionCreatorsToProps = { asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate, toggleMenu: toggleMobilizationMenu } export default provideHooks(redial)( connect(mapStateToProps, mapActionCreatorsToProps)(Page) )
import { provideHooks } from 'redial' import { connect } from 'react-redux' import * as MobilizationActions from '~mobilizations/action-creators' import * as MobilizationSelectors from '~mobilizations/selectors' import * as TemplateActions from '~mobilizations/templates/action-creators' import * as TemplateSelectors from '~mobilizations/templates/selectors' import Page from './page' const redial = { fetch: ({ dispatch, getState, params }) => { const state = getState() const promises = [] !TemplateSelectors.isLoaded(state) && promises.push( dispatch(TemplateActions.asyncFetch()) ) promises.push(dispatch(MobilizationActions.toggleMenu(undefined))) return Promise.all(promises) } } const mapStateToProps = state => ({ loading: TemplateSelectors.isLoading(state), menuActiveIndex: MobilizationSelectors.getMenuActiveIndex(state), mobilizationTemplates: TemplateSelectors.getCustomTemplates(state) }) const mapActionCreatorsToProps = { asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate, toggleMenu: MobilizationActions.toggleMenu } export default provideHooks(redial)( connect(mapStateToProps, mapActionCreatorsToProps)(Page) )
Define mocked connection with expectations for "on" method
var assert = require('chai').assert; var nodemock = require('nodemock'); var utils = require('./test-utils'); var express = require('express'); var socketAdaptor = require('../lib/socket-adaptor'); var Connection = require('../lib/backend-adaptor').Connection; var client = require('socket.io-client'); suite('Socket.IO API', function() { var server; teardown(function() { if (server) { server.close(); } server = undefined; }); test('front to back', function() { var connection = nodemock .mock('on') .takes('message', function() {}) .times(socketAdaptor.commands.length) .mock('emitMessage') .takes('search', { requestMessage: true }, function() {}); var application = express(); server = utils.setupServer(application); socketAdaptor.registerHandlers(application, server, { connection: connection }); var clientSocket = client.connect('http://localhost:' + utils.testServerPort); clientSocket.emit('search', { requestMessage: true }); connection.assertThrows(); }); });
var assert = require('chai').assert; var nodemock = require('nodemock'); var utils = require('./test-utils'); var express = require('express'); var socketAdaptor = require('../lib/socket-adaptor'); var Connection = require('../lib/backend-adaptor').Connection; var client = require('socket.io-client'); suite('Socket.IO API', function() { var server; teardown(function() { if (server) { server.close(); } server = undefined; }); test('front to back', function() { var connection = nodemock .mock('emitMessage') .takes('search', { requestMessage: true }, function() {}); var application = express(); server = utils.setupServer(application); socketAdaptor.registerHandlers(application, server, { connection: connection }); var clientSocket = client.connect('http://localhost:' + utils.testServerPort); clientSocket.emit('search', { requestMessage: true }); connection.assertThrows(); }); });
Create Web Server & Handle route GET and POST
// Problem: We need a simple way to look at a user's badge count and JavaScript point from a web browser // Solution: Use Node.js to perform the profile look ups and server our template via HTTP // 1. Create a web server var http = require('http'); http.createServer(function (request, response) { homeRoute(request, response); }).listen(3000); console.log('Server is running on port 3000'); // 2. Handle HTTP route GET / and POST / i.e. Home function homeRoute(request, response) { // if url == "/" && GET if (request.url === "/") { // show search response.writeHead(200, {'Content-Type': 'text/plain'}); response.write('Header\n'); response.write('Search\n'); response.end('Footer\n'); } // if url == "/" && POST // redirect to /:username } // 3. Handle HTTP route GET /:username i.e. /chalkers // if url == "/...." // get json from Treehouse // on "end" // show profile // on "error" // show error // 4. Function that handles the reading of files and merge in value. // read from file and get a string // merge values in to string
// Problem: We need a simple way to look at a user's badge count and JavaScript point from a web browser // Solution: Use Node.js to perform the profile look ups and server our template via HTTP // 1. Create a web server var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.write('This is before the end\n'); response.end('Hello World\n'); }).listen(3000); console.log('Server is running on port 3000'); // 2. Handle HTTP route GET / and POST / i.e. Home // if url == "/" && GET // show search // if url == "/" && POST // redirect to /:username // 3. Handle HTTP route GET /:username i.e. /chalkers // if url == "/...." // get json from Treehouse // on "end" // show profile // on "error" // show error // 4. Function that handles the reading of files and merge in value. // read from file and get a string // merge values in to string
Change: Set error message if validation fails
<?php namespace Checkdomain\TeleCash\IPG\API\Response\Action; use Checkdomain\TeleCash\IPG\API\Response\Action; use Checkdomain\TeleCash\IPG\API\Service\OrderService; /** * Class Validation */ class Validation extends Action { /** * @param \DOMDocument $responseDoc * * @throws \Exception */ public function __construct(\DOMDocument $responseDoc) { $actionResponse = $responseDoc->getElementsByTagNameNS(OrderService::NAMESPACE_N3, 'IPGApiActionResponse'); $success = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N3, 'successfully'); if ($actionResponse->length > 0) { $this->wasSuccessful = ($success === 'true'); if (false === $this->wasSuccessful) { $this->errorMessage = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N2, 'ErrorMessage'); } } else { throw new \Exception("Validate Call failed " . $responseDoc->saveXML()); } } }
<?php namespace Checkdomain\TeleCash\IPG\API\Response\Action; use Checkdomain\TeleCash\IPG\API\Response\Action; use Checkdomain\TeleCash\IPG\API\Service\OrderService; /** * Class Validation */ class Validation extends Action { /** * @param \DOMDocument $responseDoc * * @throws \Exception */ public function __construct(\DOMDocument $responseDoc) { $actionResponse = $responseDoc->getElementsByTagNameNS(OrderService::NAMESPACE_N3, 'IPGApiActionResponse'); $success = $this->firstElementByTagNSString($responseDoc, OrderService::NAMESPACE_N3, 'successfully'); if ($actionResponse->length > 0) { $this->wasSuccessful = ($success === 'true'); } else { throw new \Exception("Validate Call failed " . $responseDoc->saveXML()); } } }
Set PYTHONPATH and use sys.executable
# -*- coding: utf-8 -*- """ test_cookiecutter_invocation ---------------------------- Tests to make sure that cookiecutter can be called from the cli without using the entry point set up for the package. """ import os import pytest import subprocess import sys from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(monkeypatch, project_dir): monkeypatch.setenv('PYTHONPATH', '.') subprocess.check_call([ sys.executable, '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir)
# -*- coding: utf-8 -*- """ test_cookiecutter_invocation ---------------------------- Tests to make sure that cookiecutter can be called from the cli without using the entry point set up for the package. """ import os import pytest import subprocess from cookiecutter import utils def test_should_raise_error_without_template_arg(capfd): with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(['python', '-m', 'cookiecutter.cli']) _, err = capfd.readouterr() exp_message = 'Error: Missing argument "template".' assert exp_message in err @pytest.fixture def project_dir(request): """Remove the rendered project directory created by the test.""" rendered_dir = 'fake-project-templated' def remove_generated_project(): if os.path.isdir(rendered_dir): utils.rmtree(rendered_dir) request.addfinalizer(remove_generated_project) return rendered_dir def test_should_invoke_main(project_dir): subprocess.check_call([ 'python', '-m', 'cookiecutter.cli', 'tests/fake-repo-tmpl', '--no-input' ]) assert os.path.isdir(project_dir)
Redefine build:all:js task to skip jquery builds
'use strict'; var gulp = require('gulp'); var path = require('path'); var metal = require('gulp-metal'); var runSequence = require('run-sequence'); var codeFileGlobs = [ 'src/**/*.js', 'test/**/*.js', 'gulpfile.js', '!test/**/assets/**/*.js' ]; metal.registerTasks({ corePathFromSoy: function(file) { return path.relative(path.dirname(file.path), path.resolve('src')); }, formatGlobs: codeFileGlobs, lintGlobs: codeFileGlobs, soyDest: function(file) { if (file.base === path.resolve('temp')) { return 'test'; } else { return file.base; } }, soyGeneratedDest: false, soySrc: ['src/**/*.soy', 'test/**/*.soy'] }); gulp.task('build:all:js', function(done) { runSequence(['build:globals', 'build:amd'], done); });
'use strict'; var gulp = require('gulp'); var path = require('path'); var metal = require('gulp-metal'); var runSequence = require('run-sequence'); var codeFileGlobs = [ 'src/**/*.js', 'test/**/*.js', 'gulpfile.js', '!test/**/assets/**/*.js' ]; metal.registerTasks({ corePathFromSoy: function(file) { return path.relative(path.dirname(file.path), path.resolve('src')); }, formatGlobs: codeFileGlobs, lintGlobs: codeFileGlobs, soyDest: function(file) { if (file.base === path.resolve('temp')) { return 'test'; } else { return file.base; } }, soyGeneratedDest: false, soySrc: ['src/**/*.soy', 'test/**/*.soy'] });
Add koa-json module and koa-qs module
'use strict'; const koa = require('koa'); const passport = require('./config/passport'); const webpack = require('webpack'); const webpackConfig = require('./webpack.config'); const compiler = webpack(webpackConfig); const logger = require('koa-logger'); const serve = require('koa-static'); const routes = require('./config/routes'); const bodyParser = require('koa-bodyparser'); const session = require('koa-generic-session'); const json = require('koa-json'); const app = koa(); app.use(logger()); app.use(bodyParser()); app.keys = require('./config/salt'); app.use(session()); app.use(json()); passport(app); require('koa-qs')(app); app.use(require('koa-webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, noInfo: true })); app.use(require('koa-webpack-hot-middleware')(compiler, { path: '/__webpack_hmr', noInfo: true, heartbeat: 10 * 1000 })); app.use(serve('./public')); routes(app); app.listen(3000); module.exports = app;
'use strict'; const koa = require('koa'); const passport = require('./config/passport'); const webpack = require('webpack'); const webpackConfig = require('./webpack.config'); const compiler = webpack(webpackConfig); const logger = require('koa-logger'); const serve = require('koa-static'); const routes = require('./config/routes'); const bodyParser = require('koa-bodyparser'); const session = require('koa-generic-session'); const app = koa(); app.use(logger()); app.use(bodyParser()); app.keys = require('./config/salt'); app.use(session()); passport(app); app.use(require('koa-webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, noInfo: true })); app.use(require('koa-webpack-hot-middleware')(compiler, { path: '/__webpack_hmr', noInfo: true, heartbeat: 10 * 1000 })); routes(app); app.use(serve('./public')); app.listen(3000); module.exports = app;
Add mssql to staging branch
import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages setup( name = "mobile-city-history", version = 0.1, author = "Jan-Christopher Pien", author_email = "jan_christopher.pien@fokus.fraunhofer.de", url = "http://www.foo.bar", license = "MIT", description = "A mobile city history to enable citizens to explore the history of their surroundings.", packages = find_packages(), zip_safe = False, include_package_data = True, install_requires = [ "sparqlwrapper", "django >= 1.6", "jsonpickle >= 0.7.0", "django-apptemplates", "django-mssql >= 1.5", "pywin32 >= 219", "djangorestframework", "schedule", ], classifiers = [ "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Intended Audience :: Other Audience", "Framework :: Django", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary", ], )
import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages setup( name = "mobile-city-history", version = 0.1, author = "Jan-Christopher Pien", author_email = "jan_christopher.pien@fokus.fraunhofer.de", url = "http://www.foo.bar", license = "MIT", description = "A mobile city history to enable citizens to explore the history of their surroundings.", packages = find_packages(), zip_safe = False, include_package_data = True, install_requires = [ "sparqlwrapper", "django >= 1.6", "jsonpickle >= 0.7.0", "django-apptemplates", "djangorestframework", "schedule", ], classifiers = [ "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Intended Audience :: Other Audience", "Framework :: Django", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary", ], )
Add case sensitivity to field and clarify analyzer.
from elasticsearch_dsl import String, Nested, Boolean, DocType, tokenizer, analyzer # Required for case sensitivity # To add an analyzer to an existing mapping requires mapping to be "closed" case_sensitive_analyzer = analyzer("case_sensitive_analyzer", tokenizer=tokenizer("keyword")) class Metadata(DocType): property_list = Nested( properties={ "name": String(analyzer=case_sensitive_analyzer), "value": String(analyzer=case_sensitive_analyzer), "immutable": Boolean() } ) def update_all(self, metadata): """ Updates all metadata related to an artifact. Args metadata(dict): collection of metadata for document. """ self.property_list = metadata.values()
from elasticsearch_dsl import String, Nested, Boolean, DocType, tokenizer, analyzer # Required for case sensitivity metadata_analyzer = analyzer("metadata_analyzer", tokenizer=tokenizer("keyword")) class Metadata(DocType): property_list = Nested( properties={ "name": String(), "value": String(analyzer=metadata_analyzer), "immutable": Boolean() } ) def update_all(self, metadata): """ Updates all metadata related to an artifact. Args metadata(dict): collection of metadata for document. """ self.property_list = metadata.values()
Fix query when MySQL runs in strict mode
<?php namespace C5TL\Parser\DynamicItem; /** * Extract translatable data from Areas. */ class Area extends DynamicItem { /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::getParsedItemNames() */ public function getParsedItemNames() { return function_exists('t') ? t('Area names') : 'Area names'; } /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::getClassNameForExtractor() */ protected function getClassNameForExtractor() { return '\Concrete\Core\Area\Area'; } /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::parseManual() */ public function parseManual(\Gettext\Translations $translations, $concrete5version) { $db = \Loader::db(); $rs = $db->Execute('select distinct (binary arHandle) as AreaName from Areas order by binary arHandle'); while ($row = $rs->FetchRow()) { $this->addTranslation($translations, $row['AreaName'], 'AreaName'); } $rs->Close(); } }
<?php namespace C5TL\Parser\DynamicItem; /** * Extract translatable data from Areas. */ class Area extends DynamicItem { /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::getParsedItemNames() */ public function getParsedItemNames() { return function_exists('t') ? t('Area names') : 'Area names'; } /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::getClassNameForExtractor() */ protected function getClassNameForExtractor() { return '\Concrete\Core\Area\Area'; } /** * {@inheritdoc} * * @see \C5TL\Parser\DynamicItem::parseManual() */ public function parseManual(\Gettext\Translations $translations, $concrete5version) { $db = \Loader::db(); $rs = $db->Execute('select distinct (binary arHandle) as AreaName from Areas order by arHandle'); while ($row = $rs->FetchRow()) { $this->addTranslation($translations, $row['AreaName'], 'AreaName'); } $rs->Close(); } }
Add ffmpeg to the required environment.
#!/usr/bin/env python """Computational environment check script for 2014 SciPy Conference Tutorial: Reproducible Research: Walking the Walk. https://github.com/reproducible-research/scipy-tutorial-2014 """ import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 print('') required_executables = ['git', 'dexy', 'ipython', 'nosetests', 'ffmpeg'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help'], stderr=subprocess.STDOUT) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn defect was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
#!/usr/bin/env python """Computational environment check script for 2014 SciPy Conference Tutorial: Reproducible Research: Walking the Walk. https://github.com/reproducible-research/scipy-tutorial-2014 """ import sys import subprocess return_value = 0 required_packages = ['numpy', 'scipy', 'matplotlib', 'SimpleITK'] for package in required_packages: print('Importing ' + package + ' ...') try: __import__(package, globals(), locals(), [], 0) except ImportError: print('Error: could not import ' + package) return_value += 1 required_executables = ['git', 'dexy', 'ipython', 'nosetests'] for executable in required_executables: print('Executing ' + executable + ' ...') try: output = subprocess.check_output([executable, '--help']) except OSError: print('Error: could not execute ' + executable) return_value += 1 if return_value is 0: print('\nSuccess.') else: print('\nAn error was found in your environment, please see the messages ' + 'above.') sys.exit(return_value)
Change name of package to roku
from roku import __version__ from setuptools import setup, find_packages import os f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='roku', version=__version__, description='Client for the Roku media player', long_description=readme, author='Jeremy Carbaugh', author_email='jcarbaugh@gmail.com', url='http://github.com/jcarbaugh/python-roku/', packages=find_packages(), license='BSD License', platforms=["any"], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
from roku import __version__ from setuptools import setup, find_packages import os f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='python-roku', version=__version__, description='Client for the Roku media player', long_description=readme, author='Jeremy Carbaugh', author_email='jcarbaugh@gmail.com', url='http://github.com/jcarbaugh/python-roku/', packages=find_packages(), license='BSD License', platforms=["any"], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
Fix bug crashing the experiment on a non-recognized keypress.
""" Main world controller. """ from appstate import AppState import pygame import events class Controller(events.EventListener): """ Controller class. """ def __init__(self): pass def _quit(self): """ Gracefully quit the simulator. """ quitEvent = events.QuitEvent() AppState.get_state().get_event_manager().post_event(quitEvent) def process_input(self): """ Process user input. """ for event in pygame.event.get(): if event.type == pygame.QUIT: self._quit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self._quit() return def notify(self, event): if isinstance(event, events.TickEvent): self.process_input()
""" Main world controller. """ from appstate import AppState import pygame import events class Controller(events.EventListener): """ Controller class. """ def __init__(self): pass def _quit(self): """ Gracefully quit the simulator. """ quitEvent = events.QuitEvent() AppState.get_state().get_event_manager().post_event(quitEvent) def process_input(self): """ Process user input. """ for event in pygame.event.get(): if event.type == pygame.QUIT: self._quit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self._quit() return pygame.M def notify(self, event): if isinstance(event, events.TickEvent): self.process_input()
Use better exception for AUTH_USER_MODEL If AUTH_USER_MODEL is improperly configured as 'project.customer.User', the error is: ValueError: too many values to unpack Use rather standard Django's error: ImproperlyConfigured: AUTH_USER_MODEL must be of the form 'app_label.model_name'
from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured def get_user_model(): """ Return the User model Using this function instead of Django 1.5's get_user_model allows backwards compatibility with Django 1.4. """ try: # Django 1.5+ from django.contrib.auth import get_user_model except ImportError: # Django <= 1.4 model = User else: model = get_user_model() # Test if user model has any custom fields and add attributes to the _meta # class core_fields = set([f.name for f in User._meta.fields]) model_fields = set([f.name for f in model._meta.fields]) new_fields = model_fields.difference(core_fields) model._meta.has_additional_fields = len(new_fields) > 0 model._meta.additional_fields = new_fields return model # A setting that can be used in foreign key declarations AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') # Two additional settings that are useful in South migrations when # specifying the user model in the FakeORM try: AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME = AUTH_USER_MODEL.split('.') except ValueError: raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
from django.conf import settings from django.contrib.auth.models import User def get_user_model(): """ Return the User model Using this function instead of Django 1.5's get_user_model allows backwards compatibility with Django 1.4. """ try: # Django 1.5+ from django.contrib.auth import get_user_model except ImportError: # Django <= 1.4 model = User else: model = get_user_model() # Test if user model has any custom fields and add attributes to the _meta # class core_fields = set([f.name for f in User._meta.fields]) model_fields = set([f.name for f in model._meta.fields]) new_fields = model_fields.difference(core_fields) model._meta.has_additional_fields = len(new_fields) > 0 model._meta.additional_fields = new_fields return model # A setting that can be used in foreign key declarations AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') # Two additional settings that are useful in South migrations when # specifying the user model in the FakeORM AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME = AUTH_USER_MODEL.split('.')
CRM-3483: Change origin syncs (IMAP/EWS) to use origin - Fix Installer
<?php namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class RemoveOldSchema implements Migration, OrderedMigrationInterface { /** * {@inheritDoc} */ public function up(Schema $schema, QueryBag $queries) { $schema->dropTable('oro_user_email_origin'); self::execute($schema); } /** * @param Schema $schema * * @throws \Doctrine\DBAL\Schema\SchemaException */ public static function execute(Schema $schema) { $schema->dropTable('oro_email_to_folder'); $emailTable = $schema->getTable('oro_email'); $emailTable->dropColumn('is_seen'); $emailTable->dropColumn('received'); } /** * {@inheritDoc} */ public function getOrder() { return 2; } }
<?php namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class RemoveOldSchema implements Migration, OrderedMigrationInterface { /** * {@inheritDoc} */ public function up(Schema $schema, QueryBag $queries) { self::execute($schema); } /** * @param Schema $schema * * @throws \Doctrine\DBAL\Schema\SchemaException */ public static function execute(Schema $schema) { $schema->dropTable('oro_user_email_origin'); $schema->dropTable('oro_email_to_folder'); $emailTable = $schema->getTable('oro_email'); $emailTable->dropColumn('is_seen'); $emailTable->dropColumn('received'); } /** * {@inheritDoc} */ public function getOrder() { return 2; } }
Reset the loading state after the site socket gets disconnected. This fixes a bug where after navigating to a route which is not below the SiteConnectedFilter, the site socket would get disconnected, but all the loading state would remain "loaded". Then after going back to a route under the SiteConnectedFilter, site socket would get connected again, but the LoadingFilter would not wait for all the state to be loaded again since it thought it was already loaded. This lead the `goToIndex` action creator to incorrectly change the route based on the current state, which was wrong. Also, we only reset the loading state of stuff that gets initialized through the web sockets; other stuff can remain "loaded", eg. an audio manager.
import { Record } from 'immutable' import keyedReducer from '../reducers/keyed-reducer' import { AUDIO_MANAGER_INITIALIZED, CHAT_LOADING_COMPLETE, NETWORK_SITE_DISCONNECTED, SUBSCRIPTIONS_CLIENT_LOADING_COMPLETE, SUBSCRIPTIONS_USER_LOADING_COMPLETE, WHISPERS_LOADING_COMPLETE, } from '../actions' export const LoadingState = new Record({ audio: true, chat: true, clientSubscriptions: true, userSubscriptions: true, whispers: true, }) export default keyedReducer(new LoadingState(), { [AUDIO_MANAGER_INITIALIZED](state, action) { return state.set('audio', false) }, [CHAT_LOADING_COMPLETE](state, action) { return state.set('chat', false) }, [SUBSCRIPTIONS_CLIENT_LOADING_COMPLETE](state, action) { return state.set('clientSubscriptions', false) }, [SUBSCRIPTIONS_USER_LOADING_COMPLETE](state, action) { return state.set('userSubscriptions', false) }, [WHISPERS_LOADING_COMPLETE](state, action) { return state.set('whispers', false) }, [NETWORK_SITE_DISCONNECTED](state, action) { // Reset the loading state of the stuff that gets initialized through sockets return state.withMutations(s => s .set('chat', true) .set('clientSubscriptions', true) .set('userSubscriptions', true) .set('whispers', true), ) }, })
import { Record } from 'immutable' import keyedReducer from '../reducers/keyed-reducer' import { AUDIO_MANAGER_INITIALIZED, CHAT_LOADING_COMPLETE, SUBSCRIPTIONS_CLIENT_LOADING_COMPLETE, SUBSCRIPTIONS_USER_LOADING_COMPLETE, WHISPERS_LOADING_COMPLETE, } from '../actions' export const LoadingState = new Record({ audio: true, chat: true, clientSubscriptions: true, userSubscriptions: true, whispers: true, }) export default keyedReducer(new LoadingState(), { [AUDIO_MANAGER_INITIALIZED](state, action) { return state.set('audio', false) }, [CHAT_LOADING_COMPLETE](state, action) { return state.set('chat', false) }, [SUBSCRIPTIONS_CLIENT_LOADING_COMPLETE](state, action) { return state.set('clientSubscriptions', false) }, [SUBSCRIPTIONS_USER_LOADING_COMPLETE](state, action) { return state.set('userSubscriptions', false) }, [WHISPERS_LOADING_COMPLETE](state, action) { return state.set('whispers', false) }, })
Fix for moving parent - accidentally moving site!
<?php class changeSitetreeForm extends SitetreeForm { public function setup() { parent::setup(); // set sitetree for form $tree = siteManager::getInstance()->getSitetreeForForm($this->object->site, null, false, array('lft'=>$this->object->lft, 'rgt'=>$this->object->rgt), 'id'); $this->widgetSchema['parent'] = new sfWidgetFormChoice(array('choices'=>$tree)); $this->validatorSchema['parent'] = new sfValidatorCallback(array('callback'=>array($this, 'checkParent')), array('invalid'=>'This is already the parent page')); $this->widgetSchema->setHelp('parent', 'Select where you want to move this page to - the page you select will become the parent page'); $this->useFields(array('parent', 'site')); } public function checkParent($validator, $value) { $currentParent = $this->object->getNode()->getParent(); if ($value == $currentParent->route_name) { $error = new sfValidatorError($validator, 'invalid'); throw new sfValidatorErrorSchema($validator, array('parent' => $error)); } return $value; } public function doSave($con = null) { $parent = SitetreeTable::getInstance()->findOneById($this->getValue('parent')); $this->object->getNode()->moveAsLastChildOf($parent); } }
<?php class changeSitetreeForm extends SitetreeForm { public function setup() { parent::setup(); // set sitetree for form $tree = siteManager::getInstance()->getSitetreeForForm($this->object->site, null, false, array('lft'=>$this->object->lft, 'rgt'=>$this->object->rgt)); $this->widgetSchema['parent'] = new sfWidgetFormChoice(array('choices'=>$tree)); $this->validatorSchema['parent'] = new sfValidatorCallback(array('callback'=>array($this, 'checkParent')), array('invalid'=>'This is already the parent page')); $this->widgetSchema->setHelp('parent', 'Select where you want to move this page to - the page you select will become the parent page'); $this->useFields(array('parent')); } public function checkParent($validator, $value) { $currentParent = $this->object->getNode()->getParent(); if ($value == $currentParent->route_name) { $error = new sfValidatorError($validator, 'invalid'); throw new sfValidatorErrorSchema($validator, array('parent' => $error)); } return $value; } public function doSave($con = null) { $parent = SitetreeTable::getInstance()->findOneByRouteName($this->getValue('parent')); $this->object->getNode()->moveAsLastChildOf($parent); } }
Fix issue with URL patterns adding parentheses around codes.
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
Resolve Liikt's PR review comments.
// Submitted by Christopher Milan (christopherm99) package main import ( "fmt" "math/rand" "time" ) func shuffle(a *[]int) { for i := len(*a) - 1; i > 0; i-- { j := rand.Intn(i + 1) (*a)[i], (*a)[j] = (*a)[j], (*a)[i] } } func isSorted(a []int) bool { for i := 0; i < len(a)-1; i++ { if a[i+1] < a[i] { return false } } return true } func bogoSort(a *[]int) { for !isSorted(*a) { shuffle(a) } } func main() { rand.Seed(time.Now().UnixNano()) a := []int{1, 3, 4, 2} bogoSort(&a) fmt.Println(a) }
// Submitted by Christopher Milan (christopherm99) package main import ( "fmt" "math/rand" "time" ) func shuffle(a []int) []int { rand.Seed(time.Now().UnixNano()) for i := len(a) - 1; i > 0; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } return a } func is_sorted(a []int) bool { for i := 0; i < len(a)-1; i++ { if a[i+1] < a[i] { return false } } return true } func bogo_sort(a *[]int) { for !is_sorted(*a) { *a = shuffle(*a) } } func main() { a := []int{1, 3, 4, 2} bogo_sort(&a) fmt.Println(a) }
Remove aci files after tests have run
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import os import threading import unittest import glob, os import containers PORT = 8080 class TestServer(TCPServer): allow_reuse_address = True handler = SimpleHTTPRequestHandler httpd = TestServer(('', PORT), handler) httpd_thread = threading.Thread(target=httpd.serve_forever) httpd_thread.setDaemon(True) httpd_thread.start() class TestDiscovery(unittest.TestCase): def tearDown(self): filelist = glob.glob('/tmp/*.aci') for f in filelist: os.remove(f) def test_get_etcd(self): containers.simple_discovery('localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64', var='/tmp', secure=False) if __name__ == '__main__': unittest.main()
try: from http.server import SimpleHTTPRequestHandler except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer import os import threading import unittest import containers PORT = 8080 class TestServer(TCPServer): allow_reuse_address = True handler = SimpleHTTPRequestHandler httpd = TestServer(('', PORT), handler) httpd_thread = threading.Thread(target=httpd.serve_forever) httpd_thread.setDaemon(True) httpd_thread.start() class TestDiscovery(unittest.TestCase): def test_get_etcd(self): containers.simple_discovery('localhost:8080/tests/etc/etcd-v2.0.0-linux-amd64', var='/tmp', secure=False) if __name__ == '__main__': unittest.main()
Fix link to spec in README
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
Use more gunicorn threads when pooling database connector isn't available. When using postgres with meinheld, the best you can do so far (as far as I know) is up the number of threads.
import subprocess import sys import setup_util import os from os.path import expanduser home = expanduser("~") def start(args): setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'") setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu", home) # because pooling doesn't work with meinheld, it's necessary to create a ton of gunicorn threads (think apache pre-fork) # to allow the OS to switch processes when waiting for socket I/O. args.max_threads *= 8 # and go from there until the database server runs out of memory for new threads (connections) subprocess.Popen("gunicorn hello.wsgi:application --worker-class=\"egg:meinheld#gunicorn_worker\" -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="django/hello") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
import subprocess import sys import setup_util import os from os.path import expanduser home = expanduser("~") def start(args): setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'") setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu", home) subprocess.Popen("gunicorn hello.wsgi:application --worker-class=\"egg:meinheld#gunicorn_worker\" -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="django/hello") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'gunicorn' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) except OSError: pass return 0
Replace .jsx requires in .js to be able to require e.g. timeago
'use strict'; var fs = require('fs'); var visitors = require('react-tools/vendor/fbtransform/visitors'); var jstransform = require('jstransform'); var visitorList = visitors.getAllVisitors(); var getJsName = function(filename) { var dot = filename.lastIndexOf("."); var baseName = filename.substring(0, dot); return baseName + ".js"; } // perform es6 / jsx tranforms on all files and simultaneously copy them to the // top level. var files = fs.readdirSync('js'); for (var i = 0; i < files.length; i++) { var src = 'js/' + files[i]; var dest = getJsName(files[i]); var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; transformed = transformed.replace('.jsx', '.js'); fs.writeFileSync(dest, transformed); }
'use strict'; var fs = require('fs'); var visitors = require('react-tools/vendor/fbtransform/visitors'); var jstransform = require('jstransform'); var visitorList = visitors.getAllVisitors(); var getJsName = function(filename) { var dot = filename.lastIndexOf("."); var baseName = filename.substring(0, dot); return baseName + ".js"; } // perform es6 / jsx tranforms on all files and simultaneously copy them to the // top level. var files = fs.readdirSync('js'); for (var i = 0; i < files.length; i++) { var src = 'js/' + files[i]; var dest = getJsName(files[i]); var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; fs.writeFileSync(dest, transformed); }
Work with Django 1.10 as well.
""" Django middleware that enables the MDK. """ import atexit from traceback import format_exception_only from mdk import start # Django 1.10 new-style middleware compatibility: try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class MDKSessionMiddleware(MiddlewareMixin): """ Add an MDK session to the Django request, as well as circuit breaker support. The request object will get a ``mdk_session`` attribute added to it. """ def __init__(self, *args, **kwargs): MiddlewareMixin.__init__(self, *args, **kwargs) self.mdk = start() atexit.register(self.mdk.stop) def process_request(self, request): request.mdk_session = self.mdk.join( request.META.get("HTTP_X_MDK_CONTEXT")) request.mdk_session.start_interaction() def process_response(self, request, response): request.mdk_session.finish_interaction() del request.mdk_session return response def process_exception(self, request, exception): request.mdk_session.fail_interaction( "".join(format_exception_only(exception.__class__, exception)))
""" Django middleware that enables the MDK. This is old-style (Django <1.10) middleware. Please see https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-middleware if you're using Django 1.10. """ import atexit from traceback import format_exception_only from mdk import start class MDKSessionMiddleware(object): """ Add an MDK session to the Django request, as well as circuit breaker support. The request object will get a ``mdk_session`` attribute added to it. """ def __init__(self): self.mdk = start() atexit.register(self.mdk.stop) def process_request(self, request): request.mdk_session = self.mdk.join( request.META.get("HTTP_X_MDK_CONTEXT")) request.mdk_session.start_interaction() def process_response(self, request, response): request.mdk_session.finish_interaction() del request.mdk_session return response def process_exception(self, request, exception): request.mdk_session.fail_interaction( "".join(format_exception_only(exception.__class__, exception)))
Use default Deserializer for object-type - Use default Deserializer for object-type instead of map each field
package ch.viascom.hipchat.api.deserializer; import ch.viascom.hipchat.api.models.message.MessageFrom; import com.google.gson.*; import java.lang.reflect.Type; /** * Created by patrickboesch on 21.04.16. */ public class MessageFromDeserializer implements JsonDeserializer<MessageFrom> { @Override public MessageFrom deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { MessageFrom messageFrom = new MessageFrom(); if (jsonElement.isJsonObject()) { messageFrom = new Gson().fromJson(jsonElement, MessageFrom.class); } else { messageFrom.setName(jsonElement.getAsString()); } return messageFrom; } }
package ch.viascom.hipchat.api.deserializer; import ch.viascom.hipchat.api.models.message.MessageFrom; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.lang.reflect.Type; /** * Created by patrickboesch on 21.04.16. */ public class MessageFromDeserializer implements JsonDeserializer<MessageFrom> { @Override public MessageFrom deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { MessageFrom messageFrom = new MessageFrom(); if(jsonElement.isJsonObject()){ messageFrom.setId(jsonElement.getAsJsonObject().get("id").getAsInt()); messageFrom.setName(jsonElement.getAsJsonObject().get("name").getAsString()); messageFrom.setMention_name(jsonElement.getAsJsonObject().get("mention_name").getAsString()); messageFrom.setVersion(jsonElement.getAsJsonObject().get("version").getAsString()); } else { messageFrom.setName(jsonElement.getAsString()); } return messageFrom; } }
Deal with salted passwords in Redmine 4 Redmine 4 adds a salt to the SHA1-hashed passwords. If the "salt" field of the user record is present, the hashed password is calculated by SHA1(salt + SHA1(cleartext)) where + means string concatenation.
<?php namespace Api\Models; class User extends \ActiveRecord\Model { static $connection = 'public'; static $has_many = array( array('members'), array('projects', 'through' => 'members') ); static $table_name = 'users'; public function passwordCheck($plainPassword) { $hashedPassword = sha1($plainPassword); $salt = $this->salt; if (isset($salt)) { $hashedPassword = sha1($salt . $hashedPassword); } return $hashedPassword == $this->hashed_password; } /** * Query for user by login * @param $login * @return \ActiveRecord\Model */ static public function findByLogin($login) { return self::first(array('conditions' => array('login = ?', $login))); } /** * Query for user by email address * @param $mail * @return \ActiveRecord\Model */ static public function findByMail($mail) { return self::first(array('conditions' => array('mail = ?', $mail))); } }
<?php namespace Api\Models; class User extends \ActiveRecord\Model { static $connection = 'public'; static $has_many = array( array('members'), array('projects', 'through' => 'members') ); static $table_name = 'users'; public function passwordCheck($plainPassword) { $hashedPassword = sha1($plainPassword); return $hashedPassword == $this->hashed_password; } /** * Query for user by login * @param $login * @return \ActiveRecord\Model */ static public function findByLogin($login) { return self::first(array('conditions' => array('login = ?', $login))); } /** * Query for user by email address * @param $mail * @return \ActiveRecord\Model */ static public function findByMail($mail) { return self::first(array('conditions' => array('mail = ?', $mail))); } }
Remove High Peak election id (complaint from user)
from data_collection.management.commands import BaseShpStationsShpDistrictsImporter class Command(BaseShpStationsShpDistrictsImporter): srid = 27700 council_id = 'E07000037' districts_name = 'High Peak Polling Districts' stations_name = 'High Peak Polling Districts.shp' elections = [ 'local.derbyshire.2017-05-04', #'parl.2017-06-08' ] def district_record_to_dict(self, record): name = str(record[0]).strip() # codes are embedded in the name string: extract them code = name[name.find("(")+1:name.find(")")].strip() return { 'internal_council_id': code, 'name': name, 'polling_station_id': code, } def station_record_to_dict(self, record): name = str(record[0]).strip() # codes are embedded in the name string: extract them code = name[name.find("(")+1:name.find(")")].strip() return { 'internal_council_id': code, 'postcode': '', 'address': str(record[1]).strip(), 'location': None, }
from data_collection.management.commands import BaseShpStationsShpDistrictsImporter class Command(BaseShpStationsShpDistrictsImporter): srid = 27700 council_id = 'E07000037' districts_name = 'High Peak Polling Districts' stations_name = 'High Peak Polling Districts.shp' elections = [ 'local.derbyshire.2017-05-04', 'parl.2017-06-08' ] def district_record_to_dict(self, record): name = str(record[0]).strip() # codes are embedded in the name string: extract them code = name[name.find("(")+1:name.find(")")].strip() return { 'internal_council_id': code, 'name': name, 'polling_station_id': code, } def station_record_to_dict(self, record): name = str(record[0]).strip() # codes are embedded in the name string: extract them code = name[name.find("(")+1:name.find(")")].strip() return { 'internal_council_id': code, 'postcode': '', 'address': str(record[1]).strip(), 'location': None, }
Mark test with "REQUIRES: shell" since it directly invokes "sh" and was failing on Windows. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@332563 91177308-0d34-0410-b5e6-96231b3b80d8
# REQUIRES: shell # Check xunit output # RUN: rm -rf %t.xunit.xml # RUN: not %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/xunit-output # If xmllint is installed verify that the generated xml is well-formed # RUN: sh -c 'if command -v xmllint 2>/dev/null; then xmllint --noout %t.xunit.xml; fi' # RUN: FileCheck < %t.xunit.xml %s # CHECK: <?xml version="1.0" encoding="UTF-8" ?> # CHECK: <testsuites> # CHECK: <testsuite name='test-data' tests='1' failures='1' skipped='0'> # CHECK: <testcase classname='test-data.test-data' name='bad&amp;name.ini' time='{{[0-1]}}.{{[0-9]+}}'> # CHECK-NEXT: <failure ><![CDATA[& < > ]]]]><![CDATA[> &"]]></failure> # CHECK: </testsuite> # CHECK: </testsuites>
# Check xunit output # RUN: rm -rf %t.xunit.xml # RUN: not %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/xunit-output # If xmllint is installed verify that the generated xml is well-formed # RUN: sh -c 'if command -v xmllint 2>/dev/null; then xmllint --noout %t.xunit.xml; fi' # RUN: FileCheck < %t.xunit.xml %s # CHECK: <?xml version="1.0" encoding="UTF-8" ?> # CHECK: <testsuites> # CHECK: <testsuite name='test-data' tests='1' failures='1' skipped='0'> # CHECK: <testcase classname='test-data.test-data' name='bad&amp;name.ini' time='{{[0-1]}}.{{[0-9]+}}'> # CHECK-NEXT: <failure ><![CDATA[& < > ]]]]><![CDATA[> &"]]></failure> # CHECK: </testsuite> # CHECK: </testsuites>
Set encoding to UTF-8 in fs.readFile call https://youtu.be/AXwGVXD7qEQ
var Bot = require( 'nodemw' ), readline = require( 'readline' ), fs = require( 'fs' ), c = require( 'ansicolors' ), rl = readline.createInterface( { input: process.stdin, output: process.stdout } ), client = new Bot( { protocol: 'https', server: 'dev.fandom.com', path: '' } ), params = { action: 'scribunto-console', title: 'Module:Sandbox/CLI', clear: true }; function call( err, info, next, data ) { if ( err ) { console.error( err ); } else if ( data.type === 'error' ) { console.error( data.message ); } else { console.log( data.print ); } } function cli( input ) { params.question = input; client.api.call( params, call ); } function session( err, data ) { params.content = data; console.log( c.green( '* The module exports are available as the variable "p", including unsaved modifications.' ) ); console.log( c.green( '* Precede a line with "=" to evaluate it as an expression, or use print().' ) ); console.log( c.green( '* Use mw.log() in module code to send messages to this console.' ) ); rl.on( 'line', cli ); } fs.readFile( 'helloworld.lua', 'utf8', session );
var Bot = require( 'nodemw' ), readline = require( 'readline' ), fs = require( 'fs' ), c = require( 'ansicolors' ), rl = readline.createInterface( { input: process.stdin, output: process.stdout } ), client = new Bot( { protocol: 'https', server: 'dev.fandom.com', path: '' } ), params = { action: 'scribunto-console', title: 'Module:Sandbox/CLI', clear: true }; function call( err, info, next, data ) { if ( err ) { console.error( err ); } else if ( data.type === 'error' ) { console.error( data.message ); } else { console.log( data.print ); } } function cli( input ) { params.question = input; client.api.call( params, call ); } function session( err, data ) { params.content = data; console.log( c.green( '* The module exports are available as the variable "p", including unsaved modifications.' ) ); console.log( c.green( '* Precede a line with "=" to evaluate it as an expression, or use print().' ) ); console.log( c.green( '* Use mw.log() in module code to send messages to this console.' ) ); rl.on( 'line', cli ); } fs.readFile( 'helloworld.lua', session );
Work around for semver's hatred of underscores. 64-bit linux kernels return a release version number to node containing the suffix ".x86_64". Node semver's regexps collapse in the face of underscores.
/*! Device Reporter Copyright 2012 Raising the Floor - International Licensed under the New BSD license. You may not use this file except in compliance with this License. You may obtain a copy of the License at https://github.com/gpii/universal/LICENSE.txt */ (function () { var os = require("os"); "use strict"; var express = require("express"), fluid = require("infusion"), gpii = fluid.registerNamespace("gpii"); fluid.defaults("gpii.deviceReporter", { gradeNames: ["fluid.littleComponent", "autoInit"], preInitFunction: "gpii.deviceReporter.preInit" }); gpii.deviceReporter.preInit = function (that) { that.get = function (directModel, callback) { callback({ OS: { //TODO: need to report more details - windowmanager, etc. id: os.platform(), version: os.release().replace("_", "-") // TODO: Need a better strategy--Node semver fails horribly in the face of the benign underscore (eg. x86_64). } }); } } })();
/*! Device Reporter Copyright 2012 Raising the Floor - International Licensed under the New BSD license. You may not use this file except in compliance with this License. You may obtain a copy of the License at https://github.com/gpii/universal/LICENSE.txt */ (function () { var os = require("os"); "use strict"; var express = require("express"), fluid = require("infusion"), gpii = fluid.registerNamespace("gpii"); fluid.defaults("gpii.deviceReporter", { gradeNames: ["fluid.littleComponent", "autoInit"], preInitFunction: "gpii.deviceReporter.preInit" }); gpii.deviceReporter.preInit = function (that) { that.get = function (directModel, callback) { callback({ OS: { //TODO: need to report more details - windowmanager, etc. id: os.platform(), version: os.release() } }); } } })();
Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Use ColorPropType to validate color prop
/** * https://github.com/facebook/react-native/blob/master/Libraries/Components/ActivityIndicator/ActivityIndicator.js */ import React from 'react'; import NativeMethodsMixin from '../mixins/NativeMethodsMixin'; import View from './View'; import ColorPropType from '../propTypes/ColorPropType'; const { PropTypes } = React; const ActivityIndicator = React.createClass({ propTypes: { ...View.propTypes, /** * Whether to show the indicator (true, the default) or hide it (false). */ animating: PropTypes.bool, /** * The foreground color of the spinner (default is gray). */ color: ColorPropType, /** * Whether the indicator should hide when not animating (true by default). */ hidesWhenStopped: PropTypes.bool, /** * Size of the indicator. Small has a height of 20, large has a height of 36. */ size: PropTypes.oneOf([ 'small', 'large', ]), /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ onLayout: PropTypes.func, }, mixins: [NativeMethodsMixin], render() { return null; }, }); module.exports = ActivityIndicator;
/** * https://github.com/facebook/react-native/blob/master/Libraries/Components/ActivityIndicator/ActivityIndicator.js */ import React from 'react'; import NativeMethodsMixin from '../mixins/NativeMethodsMixin'; import View from './View'; const { PropTypes } = React; const ActivityIndicator = React.createClass({ propTypes: { ...View.propTypes, /** * Whether to show the indicator (true, the default) or hide it (false). */ animating: PropTypes.bool, /** * The foreground color of the spinner (default is gray). */ color: PropTypes.string, /** * Whether the indicator should hide when not animating (true by default). */ hidesWhenStopped: PropTypes.bool, /** * Size of the indicator. Small has a height of 20, large has a height of 36. */ size: PropTypes.oneOf([ 'small', 'large', ]), /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. */ onLayout: PropTypes.func, }, mixins: [NativeMethodsMixin], render() { return null; }, }); module.exports = ActivityIndicator;
Fix the quantization factor for writing.
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
Change the ugly hack to detect atari
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if env.action_space.__class__.__name__ == 'Discrete': env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
Fix typo in log message
package main import ( "html/template" "log" "net/http" "time" "github.com/andrewslotin/doppelganger/git" ) var ( reposTemplate = template.Must(template.ParseFiles("templates/repos/index.html.template")) ) type ReposHandler struct { repositories git.RepositoryService } func NewReposHandler(repositoryService git.RepositoryService) *ReposHandler { return &ReposHandler{ repositories: repositoryService, } } func (handler *ReposHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { startTime := time.Now() if repoName := req.FormValue("repo"); repoName != "" { NewRepoClient(handler.repositories).ServeHTTP(w, req) return } repos, err := handler.repositories.All() if err != nil { log.Printf("failed to get repos (%s) %s", err, req) http.Error(w, "Internal server error", http.StatusInternalServerError) return } if err := reposTemplate.Execute(w, repos); err != nil { log.Printf("failed to render repos/index with %d entries (%s)", len(repos), err) } else { log.Printf("rendered repos/index with %d entries [%s]", len(repos), time.Since(startTime)) } }
package main import ( "html/template" "log" "net/http" "time" "github.com/andrewslotin/doppelganger/git" ) var ( reposTemplate = template.Must(template.ParseFiles("templates/repos/index.html.template")) ) type ReposHandler struct { repositories git.RepositoryService } func NewReposHandler(repositoryService git.RepositoryService) *ReposHandler { return &ReposHandler{ repositories: repositoryService, } } func (handler *ReposHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { startTime := time.Now() if repoName := req.FormValue("repo"); repoName != "" { NewRepoClient(handler.repositories).ServeHTTP(w, req) return } repos, err := handler.repositories.All() if err != nil { log.Printf("failed to get repos (%s) %s", err, req) http.Error(w, "Internal server error", http.StatusInternalServerError) return } if err := reposTemplate.Execute(w, repos); err != nil { log.Printf("failse to render repos/index with %d entries (%s)", len(repos), err) } else { log.Printf("rendered repos/index with %d entries [%s]", len(repos), time.Since(startTime)) } }
Return stderr on script failure
import sh import tempfile import logging logger = logging.getLogger(__name__) def fetch_bash(conf, **kwargs): code = conf['script'] logger.info("Executing bash fetcher") logger.debug(code) with tempfile.NamedTemporaryFile() as fp: logger.debug("Saving code to %r", fp.name) fp.write(code.encode('utf-8')) fp.flush() logger.debug("Launching script %r", fp.name) result = sh.bash(fp.name) stdout = result.stdout.decode('utf-8') stderr = result.stderr.decode('utf-8') logger.debug("Bash exit_code: %r", result.exit_code) logger.debug("Bash stdout: %s", stdout) logger.debug("Bash stderr: %s", stderr) ok = (result.exit_code == 0) if ok: report = stdout else: report = u'\n'.join([stdout, stderr]) return ok, report
import sh import tempfile import logging logger = logging.getLogger(__name__) def fetch_bash(conf, **kwargs): code = conf['script'] logger.info("Executing bash fetcher") logger.debug(code) with tempfile.NamedTemporaryFile() as fp: logger.debug("Saving code to %r", fp.name) fp.write(code.encode('utf-8')) fp.flush() logger.debug("Launching script %r", fp.name) result = sh.bash(fp.name) stdout = result.stdout.decode('utf-8') stderr = result.stderr.decode('utf-8') logger.debug("Bash exit_code: %r", result.exit_code) logger.debug("Bash stdout: %s", stdout) logger.debug("Bash stderr: %s", stderr) ok = (result.exit_code == 0) return ok, stdout
Improve function to get all menu fetchers
package io.yancey.menufetcher; import java.time.*; import java.util.*; public interface MenuFetcher { public List<Meal> getMeals(LocalDate day); public static Map<String,MenuFetcher> getAllMenuFetchers() { Map<String, MenuFetcher> menuFetchers = new LinkedHashMap<>(); menuFetchers.put("The Hoch", new SodexoMenuFetcher(SodexoMenuFetcher.HOCH_SITENAME)); menuFetchers.put("Pitzer", new BonAppetitMenuFetcher(BonAppetitMenuFetcher.PITZER_ID)); menuFetchers.put("Frank", new PomonaMenuFetcher(PomonaMenuFetcher.FRANK_NAME)); menuFetchers.put("Frary", new PomonaMenuFetcher(PomonaMenuFetcher.FRARY_NAME)); menuFetchers.put("Oldenborg",new PomonaMenuFetcher(PomonaMenuFetcher.OLDENBORG_NAME)); menuFetchers.put("Scripps", new SodexoMenuFetcher(SodexoMenuFetcher.SCRIPPS_SITENAME)); menuFetchers.put("Collins", new BonAppetitMenuFetcher(BonAppetitMenuFetcher.COLLINS_ID)); return Collections.unmodifiableMap(menuFetchers); } }
package io.yancey.menufetcher; import java.time.*; import java.util.*; public interface MenuFetcher { public List<Meal> getMeals(LocalDate day); public static List<MenuFetcher> getAllMenuFetchers() { return Arrays.asList( new PomonaMenuFetcher(PomonaMenuFetcher.FRANK_NAME), new PomonaMenuFetcher(PomonaMenuFetcher.FRARY_NAME), new PomonaMenuFetcher(PomonaMenuFetcher.OLDENBORG_NAME), new BonAppetitMenuFetcher(BonAppetitMenuFetcher.COLLINS_ID), new BonAppetitMenuFetcher(BonAppetitMenuFetcher.PITZER_ID), new SodexoMenuFetcher(SodexoMenuFetcher.HOCH_SITENAME), new SodexoMenuFetcher(SodexoMenuFetcher.SCRIPPS_SITENAME)); } }
Add a balance (equity) account
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 03:55 from __future__ import unicode_literals from django.db import migrations, connection def load_data(apps, schema_editor): Account = apps.get_model("ledger", "Account") Account(name="Cash", type="asset").save() Account(name="Bank", type="asset").save() Account(name="Fees", type="revenue").save() Account(name="Deposits", type="revenue").save() Account(name="Administrative", type="expense").save() Account(name="Purchases", type="expense").save() Account(name="Balance", type="equity").save() def remove_data(apps, schema_editor): with connection.cursor() as cursor: cursor.execute('DELETE FROM ledger_entry') cursor.execute('DELETE FROM ledger_account') class Migration(migrations.Migration): dependencies = [ ('ledger', '0001_initial'), ] operations = [ migrations.RunPython(load_data, remove_data) ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 03:55 from __future__ import unicode_literals from django.db import migrations, connection def load_data(apps, schema_editor): Account = apps.get_model("ledger", "Account") Account(name="Cash", type="asset").save() Account(name="Bank", type="asset").save() Account(name="Fees", type="revenue").save() Account(name="Deposits", type="revenue").save() Account(name="Administrative", type="expense").save() Account(name="Purchases", type="expense").save() def remove_data(apps, schema_editor): with connection.cursor() as cursor: cursor.execute('DELETE FROM ledger_entry') cursor.execute('DELETE FROM ledger_account') class Migration(migrations.Migration): dependencies = [ ('ledger', '0001_initial'), ] operations = [ migrations.RunPython(load_data, remove_data) ]
Add the quick shortcut to create an image macro. Maybe. I don't actually have Phabricator installed locally so I have no idea if this works, but in theory this should add one of the + buttons in the left sidebar to quickly add a new macro.
<?php final class PhabricatorApplicationMacro extends PhabricatorApplication { public function getBaseURI() { return '/macro/'; } public function getShortDescription() { return pht('Image Macros and Memes'); } public function getIconName() { return 'macro'; } public function getTitleGlyph() { return "\xE2\x9A\x98"; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getQuickCreateURI() { return $this->getBaseURI().'create/'; } public function getRoutes() { return array( '/macro/' => array( '(query/(?P<key>[^/]+)/)?' => 'PhabricatorMacroListController', 'create/' => 'PhabricatorMacroEditController', 'view/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroViewController', 'comment/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroCommentController', 'edit/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroEditController', 'disable/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroDisableController', 'meme/' => 'PhabricatorMacroMemeController', 'meme/create/' => 'PhabricatorMacroMemeDialogController', ), ); } }
<?php final class PhabricatorApplicationMacro extends PhabricatorApplication { public function getBaseURI() { return '/macro/'; } public function getShortDescription() { return pht('Image Macros and Memes'); } public function getIconName() { return 'macro'; } public function getTitleGlyph() { return "\xE2\x9A\x98"; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getRoutes() { return array( '/macro/' => array( '(query/(?P<key>[^/]+)/)?' => 'PhabricatorMacroListController', 'create/' => 'PhabricatorMacroEditController', 'view/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroViewController', 'comment/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroCommentController', 'edit/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroEditController', 'disable/(?P<id>[1-9]\d*)/' => 'PhabricatorMacroDisableController', 'meme/' => 'PhabricatorMacroMemeController', 'meme/create/' => 'PhabricatorMacroMemeDialogController', ), ); } }
Add subset of missing react-autosuggest props as optional properties
import React from 'react' import Autosuggest from 'react-autosuggest' import style from './bpk-autosuggest.scss' const defaultTheme = { container: 'bpk-autosuggest__container', containerOpen: 'bpk-autosuggest__container--open', input: 'bpk-autosuggest__input', suggestionsContainer: 'bpk-autosuggest__suggestions-container', suggestionsList: 'bpk-autosuggest__suggestions-list', suggestion: 'bpk-autosuggest__suggestion', suggestionFocused: 'bpk-autosuggest__suggestion--focused', sectionContainer: 'bpk-autosuggest__section-container', sectionTitle: 'bpk-autosuggest__section-title' } const BpkAutosuggest = (props) => { const inputProps = { value: props.value, onChange: props.onChange } return ( <Autosuggest suggestions={props.suggestions} onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested} onSuggestionsClearRequested={props.onSuggestionsClearRequested || (() => {})} getSuggestionValue={props.getSuggestionValue} renderSuggestion={props.renderSuggestion} onSuggestionSelected={props.onSuggestionSelected || (() => {})} inputProps={inputProps} theme={defaultTheme} /> ) } export default BpkAutosuggest
import React from 'react' import Autosuggest from 'react-autosuggest' import style from './bpk-autosuggest.scss' const defaultTheme = { container: 'bpk-autosuggest__container', containerOpen: 'bpk-autosuggest__container--open', input: 'bpk-autosuggest__input', suggestionsContainer: 'bpk-autosuggest__suggestions-container', suggestionsList: 'bpk-autosuggest__suggestions-list', suggestion: 'bpk-autosuggest__suggestion', suggestionFocused: 'bpk-autosuggest__suggestion--focused', sectionContainer: 'bpk-autosuggest__section-container', sectionTitle: 'bpk-autosuggest__section-title' } const BpkAutosuggest = (props) => { const inputProps = { value: props.value, onChange: props.onChange } return ( <Autosuggest suggestions={props.suggestions} onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested} getSuggestionValue={props.getSuggestionValue} renderSuggestion={props.renderSuggestion} inputProps={inputProps} theme={defaultTheme} /> ) } export default BpkAutosuggest
Add comment attribute (default off)
<?php class Item extends Eloquent { protected $hidden = array('updated_at', 'deleted_at', 'user_id'); protected $fillable = ['user_id', 'price', 'currency', 'initial_units', 'description', 'title']; protected $softDelete = true; //protected $appends = ['comments']; public function user() { return $this->belongsTo('User'); } public function photos() { return $this->hasMany('Photo'); } public function comment() { return $this->hasMany('Comment'); } public static $rules = array( 'title' => 'required|max:40', 'description' => 'required|max:240', 'price' => 'required|numeric|min:0.00|max:999999999', 'currency' => 'required|alpha|min:3|max:3|in:AUD,CAD,EUR,GBP,JPY,USD,NZD,CHF,HKD,SGD,SEK,DKK,PLN,NOK,HUF,CZK,ILS,MXN,PHP,TWD,THB,RUB', 'initial_units' => 'required|min:1|max:9999999', ); public function getCommentsAttribute() { $comments = Comment::where('item_id', '=', $this->id); return $this->attributes['comments'] = $comments; } }
<?php class Item extends Eloquent { protected $hidden = array('updated_at', 'deleted_at', 'user_id'); protected $fillable = ['user_id', 'price', 'currency', 'initial_units', 'description', 'title']; protected $softDelete = true; public function user() { return $this->belongsTo('User'); } public function photos() { return $this->hasMany('Photo'); } public function comment() { return $this->hasMany('Comment'); } public static $rules = array( 'title' => 'required|max:40', 'description' => 'required|max:240', 'price' => 'required|numeric|min:0.00|max:999999999', 'currency' => 'required|alpha|min:3|max:3|in:AUD,CAD,EUR,GBP,JPY,USD,NZD,CHF,HKD,SGD,SEK,DKK,PLN,NOK,HUF,CZK,ILS,MXN,PHP,TWD,THB,RUB', 'initial_units' => 'required|min:1|max:9999999', ); }
Create dummy route for trait_details
<?php /** * Created by PhpStorm. * User: s216121 * Date: 12.10.16 * Time: 09:34 */ namespace AppBundle\Controller; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class TraitController extends Controller { /** * @param $request Request * @return \Symfony\Component\HttpFoundation\Response * @Route("/{dbversion}/trait/search", name="trait_search") */ public function searchAction(Request $request, $dbversion){ return $this->render('trait/search.html.twig', ['type' => 'trait', 'dbversion' => $dbversion, 'title' => 'Trait Search']); } /** * @param Request $request * @param $dbversion * @param $trait_id * @return Response * @Route("/{dbversion}/organism/details/{trait_id}", name="trait_details", options={"expose" = true}) */ public function detailsAction(Request $request, $dbversion, $trait_id){ } }
<?php /** * Created by PhpStorm. * User: s216121 * Date: 12.10.16 * Time: 09:34 */ namespace AppBundle\Controller; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class TraitController extends Controller { /** * @param $request Request * @return \Symfony\Component\HttpFoundation\Response * @Route("/{dbversion}/trait/search", name="trait_search") */ public function searchAction(Request $request, $dbversion){ return $this->render('trait/search.html.twig', ['type' => 'trait', 'dbversion' => $dbversion, 'title' => 'Trait Search']); } }
Use floats instead of decimals
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRacePerksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('race_perks', function (Blueprint $table) { $table->increments('id'); $table->integer('race_id')->unsigned(); $table->integer('race_perk_type_id')->unsigned(); $table->float('value'); $table->timestamps(); $table->foreign('race_id')->references('id')->on('races'); $table->foreign('race_perk_type_id')->references('id')->on('race_perk_types'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('race_perks'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRacePerksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('race_perks', function (Blueprint $table) { $table->increments('id'); $table->integer('race_id')->unsigned(); $table->integer('race_perk_type_id')->unsigned(); $table->decimal('value'); $table->timestamps(); $table->foreign('race_id')->references('id')->on('races'); $table->foreign('race_perk_type_id')->references('id')->on('race_perk_types'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('race_perks'); } }
Update project metadata with supported Python versions
import sys from setuptools import setup, find_packages setup( name = "python-dispatch", version = "v0.1.31", author = "Matthew Reid", author_email = "matt@nomadic-recording.com", description = "Lightweight Event Handling", url='https://github.com/nocarryr/python-dispatch', license='MIT', packages=find_packages(exclude=['tests*']), include_package_data=True, keywords='event properties dispatch', platforms=['any'], python_requires='>=3.6', classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
import sys from setuptools import setup, find_packages setup( name = "python-dispatch", version = "v0.1.31", author = "Matthew Reid", author_email = "matt@nomadic-recording.com", description = "Lightweight Event Handling", url='https://github.com/nocarryr/python-dispatch', license='MIT', packages=find_packages(exclude=['tests*']), include_package_data=True, keywords='event properties dispatch', platforms=['any'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
Add whitespace in order to be PEP8 compliant
import os from .bacman import BacMan class MySQL(BacMan): """Take a snapshot of a MySQL DB.""" filename_prefix = os.environ.get('BACMAN_PREFIX', 'mysqldump') def get_command(self, path): command_string = "mysqldump -u {user} -p{password} -h {host} {name} > {path}" command = command_string.format(user=self.user, password=self.password, host=self.host, name=self.name, path=path) return command if __name__ == "__main__": MySQL()
import os from .bacman import BacMan class MySQL(BacMan): """Take a snapshot of a MySQL DB.""" filename_prefix = os.environ.get('BACMAN_PREFIX', 'mysqldump') def get_command(self, path): command_string = "mysqldump -u {user} -p{password} -h {host} {name} > {path}" command = command_string.format(user=self.user, password=self.password, host=self.host, name=self.name, path=path) return command if __name__ == "__main__": MySQL()
Add foreign keys for form and route in Fdb Gcn Seq in carepoint cph
# -*- coding: utf-8 -*- # © 2015-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from carepoint import Carepoint from sqlalchemy import (Column, Integer, String, Boolean, ForeignKey, ) class FdbGcnSeq(Carepoint.BASE): __tablename__ = 'fdrgcnseq' __dbname__ = 'cph' gcn_seqno = Column(Integer, primary_key=True) hic3 = Column(String) hicl_seqno = Column(Integer) gcdf = Column( String, ForeignKey('fdrdosed.gcdf'), ) gcrt = Column( String, ForeignKey('fdrrouted.gcrt'), ) str = Column(String) gtc = Column(Integer) tc = Column(Integer) dcc = Column(Integer) gcnseq_gi = Column(Integer) gender = Column(Integer) hic3_seqn = Column(Integer) str60 = Column(String) update_yn = Column(Boolean)
# -*- coding: utf-8 -*- # © 2015-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from carepoint import Carepoint from sqlalchemy import (Column, Integer, String, Boolean, ) class FdbGcnSeq(Carepoint.BASE): __tablename__ = 'fdrgcnseq' __dbname__ = 'cph' gcn_seqno = Column(Integer, primary_key=True) hic3 = Column(String) hicl_seqno = Column(Integer) gcdf = Column(String) gcrt = Column(String) str = Column(String) gtc = Column(Integer) tc = Column(Integer) dcc = Column(Integer) gcnseq_gi = Column(Integer) gender = Column(Integer) hic3_seqn = Column(Integer) str60 = Column(String) update_yn = Column(Boolean)
Throw exception in not implemented methods
<?php namespace stekycz\Cronner\TimestampStorage; use Nette\Object; use LogicException; use DateTime; use stekycz\Cronner\ITimestampStorage; /** * @author Martin Štekl <martin.stekl@gmail.com> * @since 2013-02-04 */ class FileStorage extends Object implements ITimestampStorage { /** * @var string */ private $path; /** * @param string $path */ public function __construct($path) { $this->path = $path; } /** * Saves current date and time as last invocation time. * * @param \DateTime $now */ public function saveRunTime(DateTime $now) { // TODO - save current date & time throw new LogicException("Not implemented yet."); } /** * Returns date and time of last cron task invocation. * * @return \DateTime|null */ public function loadLastRunTime() { // TODO - load date & time of last invocation throw new LogicException("Not implemented yet."); return null; } }
<?php namespace stekycz\Cronner\TimestampStorage; use Nette\Object; use DateTime; use stekycz\Cronner\ITimestampStorage; /** * @author Martin Štekl <martin.stekl@gmail.com> * @since 2013-02-04 */ class FileStorage extends Object implements ITimestampStorage { /** * @var string */ private $path; /** * @param string $path */ public function __construct($path) { $this->path = $path; } /** * Saves current date and time as last invocation time. * * @param \DateTime $now */ public function saveRunTime(DateTime $now) { // TODO - save current date & time } /** * Returns date and time of last cron task invocation. * * @return \DateTime|null */ public function loadLastRunTime() { // TODO - load date & time of last invocation return null; } }