text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add text type as markdown.
"""Set up script""" from setuptools import setup import os def _create_long_desc(): """Create long description and README formatted with rst.""" _long_desc = '' if os.path.isfile('README.md'): with open('README.md', 'r') as rf: return rf.read() if os.path.isfile('README.rst'): with open('README.rst', 'r') as rf: return rf.read() long_desc = _create_long_desc() # Setup setup(name='cronquot', version='0.1.3', description='Cron scheduler.', long_description=long_desc, long_description_content_type='text/markdown', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules' ], keywords='cron crontab schedule', author='Shohei Mukai', author_email='[email protected]', url='https://github.com/pyohei/cronquot', license='MIT', packages=['cronquot'], entry_points={ 'console_scripts': [ 'cronquot = cronquot.cronquot:execute_from_console'], }, install_requires=['crontab'], test_suite='test' )
"""Set up script""" from setuptools import setup import os def _create_long_desc(): """Create long description and README formatted with rst.""" _long_desc = '' if os.path.isfile('README.md'): with open('README.md', 'r') as rf: return rf.read() if os.path.isfile('README.rst'): with open('README.rst', 'r') as rf: return rf.read() long_desc = _create_long_desc() # Setup setup(name='cronquot', version='0.1.2', description='Cron scheduler.', long_description=long_desc, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules' ], keywords='cron crontab schedule', author='Shohei Mukai', author_email='[email protected]', url='https://github.com/pyohei/cronquot', license='MIT', packages=['cronquot'], entry_points={ 'console_scripts': [ 'cronquot = cronquot.cronquot:execute_from_console'], }, install_requires=['crontab'], test_suite='test' )
Store as a whole document instead of individual rows as it can get really expensive
var async = require('async'); var AWS = require('aws-sdk'); require('dotenv').config(); AWS.config.update({ region: process.env.AWS_REGION }); var docClient = new AWS.DynamoDB.DocumentClient(); module.exports = { // Log of taxis locations // Trigger this every 30 seconds logTaxis: function (event, context) { require('./taxis').fetch(function (err, results, headers) { if (err) { return context.fail(err); } var params = { TableName: process.env.AWS_DYNAMODB_TABLE, Item: { timestamp: Math.floor(new Date(headers.lastmod).getTime() / 1000), locations: results } }; var saved = false; async.whilst( function() { return !saved; }, function (callback) { docClient.put(params, function (err, data) { saved = true; if (err && err.retryable === true) { saved = false; } callback(err, data); }); }, function (err, data) { if (err) { console.error(err); } return context.done(err, results.length + ' locations saved successfully with timestamp ' + headers.lastmod); }); }); } };
var async = require('async'); var AWS = require('aws-sdk'); require('dotenv').config(); AWS.config.update({ region: process.env.AWS_REGION }); var docClient = new AWS.DynamoDB.DocumentClient(); module.exports = { // Periodically recording of taxis locations taxis: function (event, context) { require('./taxis').fetch(function (err, results, headers) { if (err) { return context.fail(err); } var params = { TableName: process.env.AWS_DYNAMODB_TABLE }; var timestamp = Math.floor(new Date(headers.lastmod).getTime() / 1000); var q = async.queue(function (location, callback) { params['Item'] = { timestamp: timestamp, coord: location.lat + ',' + location.lng } console.log(q.length() + ' left in queue'); docClient.put(params, function (err, data) { if (err) { console.log(err); if (err.retryable === true) { console.log('Added current one to retry'); q.push(location); } } callback(err); }); }, process.env.AWS_DYNAMODB_WRITE_CONCURRENCY); q.drain = function() { return context.done(null, '[DONE] ' + results.length + ' locations saved successfully. ' + headers.lastmod); }; console.log(results.length + ' locations obtained. Saving...'); results.forEach(function (location) { q.push(location); }); }); } };
Exclude bower_components/ from watch task
module.exports = function(grunt) { grunt.initConfig({ sass: { dist: { files: { 'sass/main.css': 'sass/main.scss' }, options: { style: 'compressed' } } }, watch: { sass: { files: ['sass/*.scss'], tasks: ['sass', 'autoprefixer'] }, dist: { files: [ 'public/**/*', '!public/bower_components/**/*' ], options: { livereload: true } } }, connect: { server: { options: { port: 9001, hostname: 'localhost', base: 'public/', livereload: true, open: 'http://localhost:9001' } } }, autoprefixer: { main: { 'public/css/main.css': 'sass/main.css' }, options: {} }, 'gh-pages': { src: ['**'], options: { base: 'public/', message: 'Refer to master branch' } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.registerTask('default', ['sass', 'connect', 'watch']); grunt.registerTask('deploy', ['gh-pages']); };
module.exports = function(grunt) { grunt.initConfig({ sass: { dist: { files: { 'sass/main.css': 'sass/main.scss' }, options: { style: 'compressed' } } }, watch: { sass: { files: ['sass/*.scss'], tasks: ['sass', 'autoprefixer'] }, dist: { files: ['public/**/*'], options: { livereload: true } } }, connect: { server: { options: { port: 9001, hostname: 'localhost', base: 'public/', livereload: true, open: 'http://localhost:9001' } } }, autoprefixer: { main: { 'public/css/main.css': 'sass/main.css' }, options: {} }, 'gh-pages': { src: ['**'], options: { base: 'public/', message: 'Refer to master branch' } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.registerTask('default', ['sass', 'connect', 'watch']); grunt.registerTask('deploy', ['gh-pages']); };
Add sleep during tests to prevent race
import sys import unittest import tempfile import pathlib import os import os.path import time from unittest.mock import patch import monitor class TestMonitor(unittest.TestCase): def test_MonitorConfigInterval(self): with self.assertRaises(SystemExit): testargs = ["monitor.py", "-f", "tests/mocks/ini/monitor-nointerval.ini"] with patch.object(sys, "argv", testargs): monitor.main() with self.assertRaises(SystemExit): testargs = ["monitor.py", "-f", "tests/mocks/ini/monitor-badinterval.ini"] with patch.object(sys, "argv", testargs): monitor.main() def test_file_hup(self): temp_file_info = tempfile.mkstemp() os.close(temp_file_info[0]) temp_file_name = temp_file_info[1] monitor.check_hup_file(temp_file_name) time.sleep(2) pathlib.Path(temp_file_name).touch() self.assertEqual( monitor.check_hup_file(temp_file_name), True, "check_hup_file did not trigger", ) self.assertEqual( monitor.check_hup_file(temp_file_name), False, "check_hup_file should not have triggered", ) os.unlink(temp_file_name)
import sys import unittest import tempfile import pathlib import os import os.path from unittest.mock import patch import monitor class TestMonitor(unittest.TestCase): def test_MonitorConfigInterval(self): with self.assertRaises(SystemExit): testargs = ["monitor.py", "-f", "tests/mocks/ini/monitor-nointerval.ini"] with patch.object(sys, "argv", testargs): monitor.main() with self.assertRaises(SystemExit): testargs = ["monitor.py", "-f", "tests/mocks/ini/monitor-badinterval.ini"] with patch.object(sys, "argv", testargs): monitor.main() def test_file_hup(self): temp_file_info = tempfile.mkstemp() os.close(temp_file_info[0]) temp_file_name = temp_file_info[1] monitor.check_hup_file(temp_file_name) pathlib.Path(temp_file_name).touch() self.assertEqual( monitor.check_hup_file(temp_file_name), True, "check_hup_file did not trigger", ) self.assertEqual( monitor.check_hup_file(temp_file_name), False, "check_hup_file should not have triggered", ) os.unlink(temp_file_name)
Add bash script to add measures
from distutils.core import setup setup( name='boundary', version='0.0.6', url="https://github.com/boundary/boundary-api-cli", author='David Gwartney', author_email='[email protected]', packages=['boundary',], scripts=[ 'bin/alarm-create', 'bin/alarm-list', 'bin/action-installed', 'bin/action-types', 'bin/hostgroup-create', 'bin/hostgroup-delete', 'bin/hostgroup-get', 'bin/hostgroup-list', 'bin/hostgroup-update', 'bin/measurement-create', 'bin/metric-create', 'bin/metric-delete', 'bin/metric-export', 'bin/metric-import', 'bin/metric-list', 'bin/metric-markdown', 'bin/metric-ref', 'bin/plugin-add', 'bin/plugin-get', 'bin/plugin-get-components', 'bin/plugin-list', 'bin/plugin-install', 'bin/plugin-installed', 'bin/plugin-remove', 'bin/plugin-uninstall', 'bin/relay-list', 'bin/user-get', 'src/main/scripts/metrics/metric-add', ], license='LICENSE.txt', description='Command line interface to Boundary REST APIs', long_description=open('README.txt').read(), install_requires=[ "requests >= 2.3.0", ], )
from distutils.core import setup setup( name='boundary', version='0.0.6', url="https://github.com/boundary/boundary-api-cli", author='David Gwartney', author_email='[email protected]', packages=['boundary',], scripts=[ 'bin/alarm-create', 'bin/alarm-list', 'bin/action-installed', 'bin/action-types', 'bin/hostgroup-create', 'bin/hostgroup-delete', 'bin/hostgroup-get', 'bin/hostgroup-list', 'bin/hostgroup-update', 'bin/measurement-create', 'bin/metric-create', 'bin/metric-delete', 'bin/metric-export', 'bin/metric-import', 'bin/metric-list', 'bin/metric-markdown', 'bin/metric-ref', 'bin/plugin-add', 'bin/plugin-get', 'bin/plugin-get-components', 'bin/plugin-list', 'bin/plugin-install', 'bin/plugin-installed', 'bin/plugin-remove', 'bin/plugin-uninstall', 'bin/relay-list', 'bin/user-get', ], license='LICENSE.txt', description='Command line interface to Boundary REST APIs', long_description=open('README.txt').read(), install_requires=[ "requests >= 2.3.0", ], )
Remove notification type on log in
<?php session_start(); $servername = "localhost"; $username = "root"; $password = ""; $db_name = "grade4_db"; $table_name = "students"; $name = $_POST['studname']; $passphrase = $_POST['password']; $url_success = 'pages/main_menu.php'; $url_fail = 'index.php'; try { $conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT id, name, password FROM $table_name WHERE name = '$name'"); $stmt->execute(); if ($stmt->rowCount() > 0) { # code... echo $name . ' exists'; $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result['password'] == $passphrase) { $_SESSION['id'] = $result['id']; $_SESSION['name'] = $name; $_SESSION['notification'] = null; $_SESSION['notificationType'] = null; header("Location: $url_success"); } else { $_SESSION['notification'] = 'The password you used was wrong.'; $_SESSION['notificationType'] = 'fail'; header("Location: $url_fail"); } } echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
<?php session_start(); $servername = "localhost"; $username = "root"; $password = ""; $db_name = "grade4_db"; $table_name = "students"; $name = $_POST['studname']; $passphrase = $_POST['password']; $url_success = 'pages/main_menu.php'; $url_fail = 'index.php'; try { $conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT id, name, password FROM $table_name WHERE name = '$name'"); $stmt->execute(); if ($stmt->rowCount() > 0) { # code... echo $name . ' exists'; $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result['password'] == $passphrase) { $_SESSION['id'] = $result['id']; $_SESSION['name'] = $name; $_SESSION['notification'] = null; header("Location: $url_success"); } else { $_SESSION['notification'] = 'The password you used was wrong.'; $_SESSION['notificationType'] = 'fail'; header("Location: $url_fail"); } } echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Use tuple for version check
# -*- coding: utf-8 -*- import os import django from django.conf import settings from django.template import loader from django.test import TestCase try: from django.test import override_settings except ImportError: from django.test.utils import override_settings class CrispyTestCase(TestCase): def setUp(self): template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] template_dirs = template_dirs + list(settings.TEMPLATE_DIRS) template_loaders = ['django.template.loaders.filesystem.Loader'] template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS) # ensuring test templates directory is loaded first self.__overriden_settings = override_settings(**{ 'TEMPLATE_LOADERS': template_loaders, 'TEMPLATE_DIRS': template_dirs, }) self.__overriden_settings.enable() if django.VERSION < (1,8): # resetting template loaders cache self.__template_source_loaders = loader.template_source_loaders loader.template_source_loaders = None def tearDown(self): if django.VERSION < (1,8): loader.template_source_loaders = self.__template_source_loaders self.__overriden_settings.disable() @property def current_template_pack(self): return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
# -*- coding: utf-8 -*- import os import django from django.conf import settings from django.template import loader from django.test import TestCase try: from django.test import override_settings except ImportError: from django.test.utils import override_settings class CrispyTestCase(TestCase): def setUp(self): template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] template_dirs = template_dirs + list(settings.TEMPLATE_DIRS) template_loaders = ['django.template.loaders.filesystem.Loader'] template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS) # ensuring test templates directory is loaded first self.__overriden_settings = override_settings(**{ 'TEMPLATE_LOADERS': template_loaders, 'TEMPLATE_DIRS': template_dirs, }) self.__overriden_settings.enable() if django.VERSION < 1.8: # resetting template loaders cache self.__template_source_loaders = loader.template_source_loaders loader.template_source_loaders = None def tearDown(self): if django.VERSION < 1.8: loader.template_source_loaders = self.__template_source_loaders self.__overriden_settings.disable() @property def current_template_pack(self): return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
Make simple option true by default as specified in README Simple was undefined (falsy) unless specified explicitly
var Promise = require('bluebird'), request = require('request'); function rp(options) { var statusCodes = { 'GET' : [200], 'HEAD' : [200], 'PUT' : [200, 201], 'POST' : [200, 201], 'DELETE' : [200, 201] }, c = {simple: true}, i; if (typeof options === 'string') { c.uri = options; c.method = 'GET'; } if (typeof options === 'object') { for (i in options) { if (options.hasOwnProperty(i)) { c[i] = options[i]; } } } c.method = c.method || 'GET'; return new Promise(function (resolve, reject) { request(c, function (error, response, body) { if (error) { reject(error); } else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) > -1)) { reject(response.statusCode); } else { if (c.transform && typeof c.transform === 'function') { resolve(c.transform(body)); } else { resolve(body); } } }); }); } module.exports = function (a) { if (a) return rp(a); };
var Promise = require('bluebird'), request = require('request'); function rp(options) { var statusCodes = { 'GET' : [200], 'HEAD' : [200], 'PUT' : [200, 201], 'POST' : [200, 201], 'DELETE' : [200, 201] }, c = {}, i; if (typeof options === 'string') { c.uri = options; c.method = 'GET'; } if (typeof options === 'object') { for (i in options) { if (options.hasOwnProperty(i)) { c[i] = options[i]; } } } c.method = c.method || 'GET'; return new Promise(function (resolve, reject) { request(c, function (error, response, body) { if (error) { reject(error); } else if (c.simple && (statusCodes[c.method].indexOf(response.statusCode) > -1)) { reject(response.statusCode); } else { if (c.transform && typeof c.transform === 'function') { resolve(c.transform(body)); } else { resolve(body); } } }); }); } module.exports = function (a) { if (a) return rp(a); };
Fix bug with ics url format with latest vobject version
import urllib import logging import caldav from dateutil.relativedelta import relativedelta log = logging.getLogger(__file__) def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:%s DTSTART;VALUE=DATE:%s DTEND;VALUE=DATE:%s END:VEVENT END:VCALENDAR """ client = caldav.DAVClient(url) principal = client.principal() calendars = principal.calendars() if not len(calendars): return False vcal_entry = vcal_entry % (summary, date_from.strftime('%Y%m%d'), (date_end + relativedelta(days=1)).strftime('%Y%m%d')) calendar = calendars[0] log.info('Using calendar %r' % calendar) log.info('Using entry: %s' % vcal_entry) event = caldav.Event(client, data=vcal_entry, parent=calendar).save() log.info('Event %s created' % event) url_obj = event.url url_obj = urllib.quote(url_obj, safe='/:') return str(url_obj) def delFromCal(url, ics): """ Delete entry in calendar""" if not url: return False client = caldav.DAVClient(url) log.info('Deleting entry %r' % ics) client.delete(ics) return True
import logging import caldav from dateutil.relativedelta import relativedelta log = logging.getLogger(__file__) def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:%s DTSTART;VALUE=DATE:%s DTEND;VALUE=DATE:%s END:VEVENT END:VCALENDAR """ client = caldav.DAVClient(url) principal = client.principal() calendars = principal.calendars() if not len(calendars): return False vcal_entry = vcal_entry % (summary, date_from.strftime('%Y%m%d'), (date_end + relativedelta(days=1)).strftime('%Y%m%d')) calendar = calendars[0] log.info('Using calendar %r' % calendar) log.info('Using entry: %s' % vcal_entry) event = caldav.Event(client, data=vcal_entry, parent=calendar).save() log.info('Event %s created' % event) url_obj = event.url return str(url_obj) def delFromCal(url, ics): """ Delete entry in calendar""" if not url: return False client = caldav.DAVClient(url) log.info('Deleting entry %r' % ics) client.delete(ics) return True
Remove the opposite event when image loading completes or fails .
define('summernote/core/async', function () { /** * Async functions which returns `Promise` */ var async = (function () { /** * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: sDataUrl */ var readFileAsDataURL = function (file) { return $.Deferred(function (deferred) { $.extend(new FileReader(), { onload: function (e) { var sDataURL = e.target.result; deferred.resolve(sDataURL); }, onerror: function () { deferred.reject(this); } }).readAsDataURL(file); }).promise(); }; /** * create `<image>` from url string * * @param {String} sUrl * @param {String} filename * @return {Promise} - then: $image */ var createImage = function (sUrl, filename) { return $.Deferred(function (deferred) { var $img = $('<img>'); $img.one('load', function () { $img.off('error abort'); deferred.resolve($img); }).one('error abort', function () { $img.off('load').detach(); deferred.reject($img); }).css({ display: 'none' }).appendTo(document.body).attr({ 'src': sUrl, 'data-filename': filename }); }).promise(); }; return { readFileAsDataURL: readFileAsDataURL, createImage: createImage }; })(); return async; });
define('summernote/core/async', function () { /** * Async functions which returns `Promise` */ var async = (function () { /** * read contents of file as representing URL * * @param {File} file * @return {Promise} - then: sDataUrl */ var readFileAsDataURL = function (file) { return $.Deferred(function (deferred) { $.extend(new FileReader(), { onload: function (e) { var sDataURL = e.target.result; deferred.resolve(sDataURL); }, onerror: function () { deferred.reject(this); } }).readAsDataURL(file); }).promise(); }; /** * create `<image>` from url string * * @param {String} sUrl * @return {Promise} - then: $image */ var createImage = function (sUrl, filename) { return $.Deferred(function (deferred) { $('<img>').one('load', function () { deferred.resolve($(this)); }).one('error abort', function () { deferred.reject($(this).detach()); }).css({ display: 'none' }).appendTo(document.body) .attr('src', sUrl) .attr('data-filename', filename); }).promise(); }; return { readFileAsDataURL: readFileAsDataURL, createImage: createImage }; })(); return async; });
UPDATE autocomplete - set search string
var ResourceService = require("services/ResourceService"); var ItemListService = require("services/ItemListService"); Vue.component("item-search", { template: "#vue-item-search", data: function() { return { searchString: "", itemSearch: {} }; }, ready: function() { ResourceService.bind("itemSearch", this); var countries = [ {value: "Andorra", data: "AD"}, {value: "tets", data: "t1"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Zimbabwe", data: "ZZ"} ]; var self = this; $(".search-input").autocomplete({ lookup: countries, width: $(".search-box-shadow-frame").width(), onSelect: function(suggestion) { self.itemSearch.searchString = suggestion.value; } }); $(window).resize(function() { $(".autocomplete-suggestions").width($(".search-box-shadow-frame").width()); }); }, methods: { search: function() { if (document.location.pathname === "/search") { ItemListService.setSearchString(this.itemSearch.searchString); } else { window.open("/search?searchString=" + this.itemSearch.searchString, "_self", false); } } } });
var ResourceService = require("services/ResourceService"); var ItemListService = require("services/ItemListService"); Vue.component("item-search", { template: "#vue-item-search", data: function() { return { searchString: "", itemSearch: {} }; }, ready: function() { ResourceService.bind("itemSearch", this); var countries = [ {value: "Andorra", data: "AD"}, {value: "tets", data: "t1"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Test", data: "tt"}, {value: "Zimbabwe", data: "ZZ"} ]; $(".search-input").autocomplete({ lookup: countries, width: $(".search-box-shadow-frame").width(), onSelect: function(suggestion) { console.log(suggestion); } }); $(window).resize(function() { $(".autocomplete-suggestions").width($(".search-box-shadow-frame").width()); }); }, methods: { search: function() { if (document.location.pathname === "/search") { ItemListService.setSearchString(this.itemSearch.searchString); } else { window.open("/search?searchString=" + this.itemSearch.searchString, "_self", false); } } } });
Remove uneccesary title for HTML in WebPack
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { main: [ './src/js/app.js', './src/sass/app.scss', ], }, output: { filename: 'assets/js/[name].js', path: path.resolve(__dirname, 'build/'), //ecmaVersion: 5, }, plugins: [ new MiniCssExtractPlugin({ filename: 'assets/css/[name].css', }), new HtmlWebpackPlugin({ filename: 'templates/index.html', template: './src/templates/index.html', inject: false, }), new HtmlWebpackPlugin({ filename: 'templates/need_token.html', template: './src/templates/need_token.html', inject: false, }), ], module: { rules: [ { test: /\.s[ac]ss$/i, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ], }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { 'corejs': '3.6', 'useBuiltIns': 'usage', }, ], ], }, }, }, ], }, /*experiments: { mjs: true, },*/ };
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { main: [ './src/js/app.js', './src/sass/app.scss', ], }, output: { filename: 'assets/js/[name].js', path: path.resolve(__dirname, 'build/'), //ecmaVersion: 5, }, plugins: [ new MiniCssExtractPlugin({ filename: 'assets/css/[name].css', }), new HtmlWebpackPlugin({ title: 'botamusique', filename: 'templates/index.html', template: './src/templates/index.html', inject: false, }), new HtmlWebpackPlugin({ title: 'botamusique - Needs Auth', filename: 'templates/need_token.html', template: './src/templates/need_token.html', inject: false, }), ], module: { rules: [ { test: /\.s[ac]ss$/i, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ], }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { 'corejs': '3.6', 'useBuiltIns': 'usage', }, ], ], }, }, }, ], }, /*experiments: { mjs: true, },*/ };
Modify test to test that bucketlist nolonger exists in system
import json from api.test import BaseTestCase from api.models import BucketList class TestDeleteBucketList(BaseTestCase): def test_delete_bucket_list(self): bucket_list_one = { "description": "Movies i have to watch by the end of the week", "status": "Pending", "title": "Entertainment", "user_id": 1 } self.client.post('/api/v1/bucketlists', headers={ 'Authorization': 'JWT ' + self.token }, data=json.dumps(bucket_list_one), content_type='application/json') count = len(BucketList.query.all()) self.client.delete('/api/v1/bucketlists/1', headers={ 'Authorization': 'JWT ' + self.token },) new_count = len(BucketList.query.all()) self.assertEqual(new_count - count, -1) response = self.client.get( '/api/v1/bucketlists/1', headers=dict( Authorization='Bearer ' + self.token ) ) self.assertIn("Bucket list not found", str(response.data)) self.assertEqual(response.status_code, 404)
import json from api.test import BaseTestCase from api.models import BucketList class TestDeleteBucketList(BaseTestCase): def test_delete_bucket_list(self): bucket_list_one = { "description": "Movies i have to watch by the end of the week", "status": "Pending", "title": "Entertainment", "user_id": 1 } self.client.post('/api/v1/bucketlists', headers={ 'Authorization': 'JWT ' + self.token }, data=json.dumps(bucket_list_one), content_type='application/json') count = len(BucketList.query.all()) self.client.delete('/api/v1/bucketlists/1', headers={ 'Authorization': 'JWT ' + self.token },) new_count = len(BucketList.query.all()) self.assertEqual(new_count - count, -1)
Fix button class on upload modal no issue - this makes sure that the cancel button on the upload modal gets the correct class
import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: 'btn btn-default', text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal;
import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: true, text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal;
Update config tree builder constructor
<?php namespace DataDog\AuditBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Configuration for DataDog/AuditBundle */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} * @see \Symfony\Component\Config\Definition\ConfigurationInterface::getConfigTreeBuilder() */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('data_dog_audit'); // BC layer for symfony/config < 4.2 $rootNode = method_exists($treeBuilder, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('data_dog_audit'); $rootNode ->children() ->arrayNode('audited_entities') ->canBeUnset() ->performNoDeepMerging() ->prototype('scalar')->end() ->end() ->end() ; $rootNode ->children() ->arrayNode('unaudited_entities') ->canBeUnset() ->performNoDeepMerging() ->prototype('scalar')->end() ->end() ->end() ; $rootNode ->children() ->booleanNode('blame_impersonator') ->defaultFalse() ->end() ; return $treeBuilder; } }
<?php namespace DataDog\AuditBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * Configuration for DataDog/AuditBundle */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} * @see \Symfony\Component\Config\Definition\ConfigurationInterface::getConfigTreeBuilder() */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('data_dog_audit'); $rootNode ->children() ->arrayNode('audited_entities') ->canBeUnset() ->performNoDeepMerging() ->prototype('scalar')->end() ->end() ->end() ; $rootNode ->children() ->arrayNode('unaudited_entities') ->canBeUnset() ->performNoDeepMerging() ->prototype('scalar')->end() ->end() ->end() ; $rootNode ->children() ->booleanNode('blame_impersonator') ->defaultFalse() ->end() ; return $treeBuilder; } }
Check for state presence as well
import React, { Component } from 'react'; import Channel from 'jschannel'; const CHANNEL_NOT_READY = 'CHANNEL_NOT_READY'; class Seed extends Component { componentWillUnmount() { this.iframe.removeEventListener('load', this.iframeLoaded); this.channel.destroy(); } request = (requestOptions, callback) => { return new Promise((resolve, reject) => { if (!this.state || this.state.ready !== true) return reject(new Error(CHANNEL_NOT_READY)); this.channel.call({ method: 'httpRequest', params: requestOptions, success: resolve, error: reject }); }); } iframeLoaded = () => { this.channel = Channel.build({ window: this.iframe.contentWindow, origin: this.props.baseUrl, scope: this.props.scope, onReady: () => { this.setState({ ready: true }); this.props.onReady && this.props.onReady(); } }); } render() { return ( <iframe src={this.props.baseUrl} height="0" width="0" frameBorder="0" sandbox="allow-scripts allow-same-origin" ref={(iframe) => { if (iframe) { this.iframe = iframe; iframe.addEventListener('load', this.iframeLoaded, false); } } } > </iframe> ); } } Seed.propTypes = { baseUrl: React.PropTypes.string, scope: React.PropTypes.string, onReady: React.PropTypes.func }; export default Seed;
import React, { Component } from 'react'; import Channel from 'jschannel'; const CHANNEL_NOT_READY = 'CHANNEL_NOT_READY'; class Seed extends Component { componentWillUnmount() { this.iframe.removeEventListener('load', this.iframeLoaded); this.channel.destroy(); } request = (requestOptions, callback) => { return new Promise((resolve, reject) => { if (this.state.ready !== true) return reject(new Error(CHANNEL_NOT_READY)); this.channel.call({ method: 'httpRequest', params: requestOptions, success: resolve, error: reject }); }); } iframeLoaded = () => { this.channel = Channel.build({ window: this.iframe.contentWindow, origin: this.props.baseUrl, scope: this.props.scope, onReady: () => { this.setState({ ready: true }); this.props.onReady && this.props.onReady(); } }); } render() { return ( <iframe src={this.props.baseUrl} height="0" width="0" frameBorder="0" sandbox="allow-scripts allow-same-origin" ref={(iframe) => { if (iframe) { this.iframe = iframe; iframe.addEventListener('load', this.iframeLoaded, false); } } } > </iframe> ); } } Seed.propTypes = { baseUrl: React.PropTypes.string, scope: React.PropTypes.string, onReady: React.PropTypes.func }; export default Seed;
Add indented syntax for .sass files
let AutomaticComponent = require('./AutomaticComponent'); class Css extends AutomaticComponent { /** * webpack rules to be appended to the master config. */ webpackRules() { return [ { test: /\.css$/, loaders: ['style-loader', 'css-loader'] }, { test: /\.scss$/, exclude: this.excludePathsFor('sass'), loaders: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.sass$/, exclude: this.excludePathsFor('sass'), loaders: [ 'style-loader', 'css-loader', { loader: 'sass-loader', options: { indentedSyntax: true } } ] }, { test: /\.less$/, exclude: this.excludePathsFor('less'), loaders: ['style-loader', 'css-loader', 'less-loader'] } ]; } /** * Paths to be excluded from the loader. * * @param {string} preprocessor */ excludePathsFor(preprocessor) { let exclusions = Mix.components.get(preprocessor); return exclusions ? exclusions.details.map(preprocessor => preprocessor.src.path()) : []; } } module.exports = Css;
let AutomaticComponent = require('./AutomaticComponent'); class Css extends AutomaticComponent { /** * webpack rules to be appended to the master config. */ webpackRules() { return [ { test: /\.css$/, loaders: ['style-loader', 'css-loader'] }, // We're not doing test: /\.s[ca]ss/ for a reason, related to Vue SFP's. // Don't merge. { test: /\.scss$/, exclude: this.excludePathsFor('sass'), loaders: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.sass$/, exclude: this.excludePathsFor('sass'), loaders: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.less$/, exclude: this.excludePathsFor('less'), loaders: ['style-loader', 'css-loader', 'less-loader'] } ]; } /** * Paths to be excluded from the loader. * * @param {string} preprocessor */ excludePathsFor(preprocessor) { let exclusions = Mix.components.get(preprocessor); return exclusions ? exclusions.details.map(preprocessor => preprocessor.src.path()) : []; } } module.exports = Css;
Change from constant public and secret key to retrieve it from database Change the constant of public key and secret key that was fixed, to retrieve it from database by using the class OmiseConfigProvider.
<?php namespace Omise\Payment\Gateway\Http\Client; use Magento\Payment\Gateway\Http\ClientInterface; use Magento\Payment\Gateway\Http\TransferInterface; use Omise\Payment\Model\Ui\OmiseConfigProvider; abstract class AbstractOmiseClient implements ClientInterface { /** * Client request status represented to initiating step. * * @var string */ const PROCESS_STATUS_INIT = 'initiate_request'; /** * Client request status represented to successful request step. * * @var string */ const PROCESS_STATUS_SUCCESSFUL = 'successful'; /** * Client request status represented to failed request step. * * @var string */ const PROCESS_STATUS_FAILED = 'failed'; protected $publicKey; protected $secretKey; public function __construct(OmiseConfigProvider $config) { $this->publicKey = $config->getPublicKey(); $this->secretKey = $config->getSecretKey(); } /** * @param \Magento\Payment\Gateway\Http\TransferInterface $transferObject * * @return array */ public function placeRequest(TransferInterface $transferObject) { $payload = []; $response = [ 'status' => self::PROCESS_STATUS_INIT, 'api' => null ]; try { $response['api'] = $this->request($payload); $response['status'] = self::PROCESS_STATUS_SUCCESSFUL; } catch (Exception $e) { $response['status'] = self::PROCESS_STATUS_FAILED; } return $response; } }
<?php namespace Omise\Payment\Gateway\Http\Client; use Magento\Payment\Gateway\Http\ClientInterface; use Magento\Payment\Gateway\Http\TransferInterface; define('OMISE_PUBLIC_KEY', 'pkey_test_51fl8dfabqmt3m27vl7'); define('OMISE_SECRET_KEY', 'skey_test_51fl8dfabe7sqnj8th2'); abstract class AbstractOmiseClient implements ClientInterface { /** * Client request status represented to initiating step. * * @var string */ const PROCESS_STATUS_INIT = 'initiate_request'; /** * Client request status represented to successful request step. * * @var string */ const PROCESS_STATUS_SUCCESSFUL = 'successful'; /** * Client request status represented to failed request step. * * @var string */ const PROCESS_STATUS_FAILED = 'failed'; /** * @param \Magento\Payment\Gateway\Http\TransferInterface $transferObject * * @return array */ public function placeRequest(TransferInterface $transferObject) { $payload = []; $response = [ 'status' => self::PROCESS_STATUS_INIT, 'api' => null ]; try { $response['api'] = $this->request($payload); $response['status'] = self::PROCESS_STATUS_SUCCESSFUL; } catch (Exception $e) { $response['status'] = self::PROCESS_STATUS_FAILED; } return $response; } }
Create folder if not exist
import os from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) directory = self.container + measure.device_id.split('/')[-1] file_path = directory + self.extension if not os.path.exists(directory): os.makedirs(directory) f = open(file_path, 'w+') f.writelines([log_entry])
from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + self.extension f = open(file_path, 'w+') f.writelines([log_entry])
Add missing line break on the first status line
<?php require_once('class/3rdparty/OAuth.php'); require_once('class/3rdparty/twitter.class.php'); /** * Generate tweet string **/ class Tweet { /** * Generate tweet from body * Returns array of tweets * * @param $body * @return array or false if no data */ public function generate($status) { if ($status == '') return null; $tweetlength = 140; // Splits into tweet-length number of characters, breaking at // new line $tweet_lines = explode("\n", $status); $tweets = ['']; foreach ($tweet_lines as $n => $line) { $current_tweet_id = count($tweets) - 1; $length_of_current_tweet = strlen($tweets[$current_tweet_id]); $length_of_line_to_add = strlen($line); if ($length_of_current_tweet + $length_of_line_to_add < $tweetlength) { $tweets[$current_tweet_id] .= $line . "\n"; } else { $tweets[] = $line . "\n"; } } return $tweets; } public function post($tweet) { if (true == MMS_DEBUG) { echo $tweet; } else { $twitter = new Twitter( TWITTER_CONSUMERKEY, TWITTER_CONSUMERSECRET, TWITTER_ACCESSTOKEN, TWITTER_ACCESSTOKENSECRET ); $twitter->send($tweet); } } }
<?php require_once('class/3rdparty/OAuth.php'); require_once('class/3rdparty/twitter.class.php'); /** * Generate tweet string **/ class Tweet { /** * Generate tweet from body * Returns array of tweets * * @param $body * @return array or false if no data */ public function generate($status) { if ($status == '') return null; $tweetlength = 140; // Splits into tweet-length number of characters, breaking at // new line $tweet_lines = explode("\n", $status); $tweets = ['']; foreach ($tweet_lines as $n => $line) { $current_tweet_id = count($tweets) - 1; $length_of_current_tweet = strlen($tweets[$current_tweet_id]); $length_of_line_to_add = strlen($line); if ($length_of_current_tweet + $length_of_line_to_add < $tweetlength) { $tweets[$current_tweet_id] .= $line . "\n"; } else { $tweets[] = $line; } } return $tweets; } public function post($tweet) { if (true == MMS_DEBUG) { echo $tweet; } else { $twitter = new Twitter( TWITTER_CONSUMERKEY, TWITTER_CONSUMERSECRET, TWITTER_ACCESSTOKEN, TWITTER_ACCESSTOKENSECRET ); $twitter->send($tweet); } } }
Remove all temporary files from disk
import unittest import os from tempfile import NamedTemporaryFile from .. import archivebot class TestRename(unittest.TestCase): def test_valid_rename(self): try: tmp = NamedTemporaryFile() new_tmp = archivebot._rename(tmp.name) self.assertFalse(os.path.isfile(tmp.name)) self.assertTrue(os.path.isfile(new_tmp)) self.assertTrue(new_tmp.find(".compress") > 1) finally: for file in [tmp.name, new_tmp]: if os.path.isfile(file): os.remove(file) class TestCompress(unittest.TestCase): def test_dotcompress(self): with NamedTemporaryFile(prefix="roomname.compress@example") as tmp: self.assertRaises(ValueError, archivebot.compress, tmp.name) def test_valid_compress(self): try: tmp = NamedTemporaryFile(suffix=".compress") tmp.write("test") gz_file = archivebot.compress(tmp.name) self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz")) finally: for file in [tmp.name, gz_file]: if os.path.isfile(file): os.remove(file)
import unittest import os from tempfile import NamedTemporaryFile from .. import archivebot class TestRename(unittest.TestCase): def test_valid_rename(self): try: tmp = NamedTemporaryFile() new_tmp = archivebot._rename(tmp.name) self.assertFalse(os.path.isfile(tmp.name)) self.assertTrue(os.path.isfile(new_tmp)) self.assertTrue(new_tmp.find(".compress") > 1) finally: if os.path.isfile(tmp.name): os.remove(tmp.name) if os.path.isfile(new_tmp): os.remove(new_tmp) class TestCompress(unittest.TestCase): def test_dotcompress(self): with NamedTemporaryFile(prefix="roomname.compress@example") as tmp: self.assertRaises(ValueError, archivebot.compress, tmp.name) def test_valid_compress(self): try: tmp = NamedTemporaryFile(suffix=".compress") tmp.write("test") gz_file = archivebot.compress(tmp.name) self.assertEqual(gz_file, tmp.name.replace(".compress", ".gz")) finally: if os.path.isfile(tmp.name): os.remove(tmp.name)
Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing
from django.core.handlers.wsgi import STATUS_CODE_TEXT from django.template.response import SimpleTemplateResponse class Response(SimpleTemplateResponse): """ An HttpResponse that allows it's data to be rendered into arbitrary media types. """ def __init__(self, data=None, status=None, headers=None, renderer=None, accepted_media_type=None): """ Alters the init arguments slightly. For example, drop 'template_name', and instead use 'data'. Setting 'renderer' and 'media_type' will typically be defered, For example being set automatically by the `APIView`. """ super(Response, self).__init__(None, status=status) self.data = data self.headers = headers and headers[:] or [] self.renderer = renderer # Accepted media type is the portion of the request Accept header # that the renderer satisfied. It could be '*/*', or somthing like # 'application/json; indent=4' # # This is NOT the value that will be returned in the 'Content-Type' # header, but we do need to know the value in case there are # any specific parameters which affect the rendering process. self.accepted_media_type = accepted_media_type @property def rendered_content(self): self['Content-Type'] = self.renderer.media_type if self.data is None: return self.renderer.render() render_media_type = self.accepted_media_type or self.renderer.media_type return self.renderer.render(self.data, render_media_type) @property def status_text(self): """ Returns reason text corresponding to our HTTP response status code. Provided for convenience. """ return STATUS_CODE_TEXT.get(self.status_code, '')
from django.core.handlers.wsgi import STATUS_CODE_TEXT from django.template.response import SimpleTemplateResponse class Response(SimpleTemplateResponse): """ An HttpResponse that allows it's data to be rendered into arbitrary media types. """ def __init__(self, data=None, status=None, headers=None, renderer=None, accepted_media_type=None): """ Alters the init arguments slightly. For example, drop 'template_name', and instead use 'data'. Setting 'renderer' and 'media_type' will typically be defered, For example being set automatically by the `APIView`. """ super(Response, self).__init__(None, status=status) self.data = data self.headers = headers and headers[:] or [] self.renderer = renderer self.accepted_media_type = accepted_media_type @property def rendered_content(self): self['Content-Type'] = self.renderer.media_type if self.data is None: return self.renderer.render() render_media_type = self.accepted_media_type or self.renderer.media_type return self.renderer.render(self.data, render_media_type) @property def status_text(self): """ Returns reason text corresponding to our HTTP response status code. Provided for convenience. """ return STATUS_CODE_TEXT.get(self.status_code, '')
Move fields for new output
#!/usr/bin/env python import sys import numpy as np from optparse import OptionParser parser = OptionParser() parser.add_option("-b", "--bedpe_file", dest="bedpe_file", help="BEDPE file") parser.add_option("-n", "--name", default="LUMPY BedGraph", dest="name", help="Name") (options, args) = parser.parse_args() if not options.bedpe_file: parser.error('BEDPE file not given') f = open(options.bedpe_file,'r') print 'track type=bedGraph name="' + options.name + '"' for l in f: A = l.rstrip().split('\t') L=[float(x) for x in A[15][2:].split(',')] R=[float(x) for x in A[16][2:].split(',')] l_chr = A[0] l_start = int(A[1]) r_chr = A[3] r_start = int(A[4]) c = 0 for p in L: print '\t'.join( [l_chr, str(l_start + c), str(l_start + c + 1), str(p)]) c+=1 c = 0 for p in R: print '\t'.join( [r_chr, str(r_start + c), str(r_start + c + 1), str(p)]) c+=1 f.close()
#!/usr/bin/env python import sys import numpy as np from optparse import OptionParser parser = OptionParser() parser.add_option("-b", "--bedpe_file", dest="bedpe_file", help="BEDPE file") parser.add_option("-n", "--name", default="LUMPY BedGraph", dest="name", help="Name") (options, args) = parser.parse_args() if not options.bedpe_file: parser.error('BEDPE file not given') f = open(options.bedpe_file,'r') print 'track type=bedGraph name="' + options.name + '"' for l in f: A = l.rstrip().split('\t') L=[float(x) for x in A[11].split()] R=[float(x) for x in A[12].split()] l_chr = A[0] l_start = int(A[1]) r_chr = A[3] r_start = int(A[4]) c = 0 for p in L: print '\t'.join( [l_chr, str(l_start + c), str(l_start + c + 1), str(p)]) c+=1 c = 0 for p in R: print '\t'.join( [r_chr, str(r_start + c), str(r_start + c + 1), str(p)]) c+=1 f.close()
Validate that the function exists before execute.
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var FixedDataTableRowDragDropConfig = { type: 'column', exchangeItemPosition: null, drop: { target: { drop: function (props, monitor, component) { var item = monitor.getItem(); return props.onDrop && props.onDrop(item, props); }, hover: function (props, monitor, component) { var item = monitor.getItem(); if (item.index !== props.index) { return props.onDragDrop && props.onDragDrop(item, props); } } }, collect: function (connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } }, drag: { source: { beginDrag: function (props, monitor, component) { return props; }, endDrag: function (props, monitor, component) { return props; }, canDrag: function (props, monitor) { return !!props.isSortable; } }, collect: function (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }; } } }; module.exports = FixedDataTableRowDragDropConfig;
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var FixedDataTableRowDragDropConfig = { type: 'column', exchangeItemPosition: null, drop: { target: { drop: function (props, monitor, component) { var item = monitor.getItem(); if (props.onDrop) { props.onDrop(item, props); } }, hover: function (props, monitor, component) { var item = monitor.getItem(); if (item.index !== props.index) { props.onDragDrop(item, props); } } }, collect: function (connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } }, drag: { source: { beginDrag: function (props, monitor, component) { return props; }, endDrag: function (props, monitor, component) { return props; }, canDrag: function (props, monitor) { return !!props.isSortable; } }, collect: function (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }; } } }; module.exports = FixedDataTableRowDragDropConfig;
Remove unused var :police_car: :pencil:
"use strict"; var assert = require("assert"), Processor = require("../src/processor"); describe("modular-css", function() { describe("issue 56", function() { it("shouldn't prune classes that have pseudo-classed variants", function(done) { var processor = new Processor(); processor.string( "./test/specimens/issues/56.css", ".booga { color: red } " + ".fooga { composes: booga } " + ".fooga:hover { color: blue } " + ".wooga { composes: booga }" ) .then(function(result) { assert.deepEqual(result.exports, { booga : "mc13e7db14_booga", fooga : "mc13e7db14_booga mc13e7db14_fooga", wooga : "mc13e7db14_booga" }); done(); }) .catch(done); }); }); });
"use strict"; var assert = require("assert"), Processor = require("../src/processor"); describe("modular-css", function() { describe("issue 56", function() { it("shouldn't prune classes that have pseudo-classed variants", function(done) { var processor = new Processor(); processor.string( "./test/specimens/issues/56.css", ".booga { color: red } " + ".fooga { composes: booga } " + ".fooga:hover { color: blue } " + ".wooga { composes: booga }" ) .then(function(result) { var file = result.files["test/specimens/issues/56.css"]; assert.deepEqual(result.exports, { booga : "mc13e7db14_booga", fooga : "mc13e7db14_booga mc13e7db14_fooga", wooga : "mc13e7db14_booga" }); done(); }) .catch(done); }); }); });
Refactor implement object entries locally
import invariant from "invariant"; const entries = (obj) => Object.keys(obj).map((key) => [key, obj[key]]); const propValidates = ([name, propValidationFn]) => (props, componentName) => !(propValidationFn(props, name, componentName) instanceof Error); export const satisfyOneOf = (propSet) => { invariant( "object" === typeof propSet && null != propSet, "Expected propSet to be an object" ); if (2 > Object.keys(propSet).length) { return propSet; } const propSetValidationFailed = `Expected one in [${Object.keys(propSet).join(", ")}] to pass validation`; const satisfyOne = (name, propValidationFn) => { const restOfPropSet = entries(propSet).filter(([propName]) => propName !== name).map(propValidates); return (props, propName, componentName) => { const shouldValidateLocally = null != props[propName]; if (!shouldValidateLocally) { return restOfPropSet.some((isValid) => isValid(props, componentName)) || new Error(propSetValidationFailed); } return propValidationFn(props, propName, componentName); }; }; return entries(propSet). reduce((props, [name, propValidationFn]) => ({ ...props, [name]: satisfyOne(name, propValidationFn) }), {}); };
import invariant from "invariant"; const propValidates = ([name, propValidationFn]) => (props, componentName) => !(propValidationFn(props, name, componentName) instanceof Error); export const satisfyOneOf = (propSet) => { invariant( "object" === typeof propSet && null != propSet, "Expected propSet to be an object" ); if (2 > Object.keys(propSet).length) { return propSet; } const propSetValidationFailed = `Expected one in [${Object.keys(propSet).join(", ")}] to pass validation`; const satisfyOne = (name, propValidationFn) => { const restOfPropSet = Object.entries(propSet).filter(([propName]) => propName !== name).map(propValidates); return (props, propName, componentName) => { const shouldValidateLocally = null != props[propName]; if (!shouldValidateLocally) { return restOfPropSet.some((isValid) => isValid(props, componentName)) || new Error(propSetValidationFailed); } return propValidationFn(props, propName, componentName); }; }; return Object.entries(propSet). reduce((props, [name, propValidationFn]) => ({ ...props, [name]: satisfyOne(name, propValidationFn) }), {}); };
Switch to single-string commands and long ids
package forager.events; import java.io.IOException; import java.util.ArrayList; import java.util.List; import galileo.event.Event; import galileo.net.NetworkDestination; import galileo.serialization.SerializationInputStream; import galileo.serialization.SerializationOutputStream; public class TaskSpec implements Event { public long taskId; public String command; private List<NetworkDestination> assignments = new ArrayList<>(); public TaskSpec(long taskId, String command) { this.taskId = taskId; this.command = command; } public void addAssignment(NetworkDestination host) { assignments.add(host); } public void removeAssignment(NetworkDestination host) { assignments.remove(host); } /** * Determine whether the Task associated with this TaskSpec has been * assigned to any resources yet. * * @return true if the Task has been assigned, false otherwise. */ public boolean isAssigned() { return assignments.isEmpty() == false; } public String toString() { return "[" + taskId + "] " + command; } @Deserialize public TaskSpec(SerializationInputStream in) throws IOException { taskId = in.readLong(); command = in.readString(); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeLong(taskId); out.writeString(command); } }
package forager.events; import java.io.IOException; import galileo.event.Event; import galileo.serialization.SerializationInputStream; import galileo.serialization.SerializationOutputStream; public class TaskSpec implements Event { public int taskId; public String[] command; public TaskSpec(int taskId, String[] command) { private List<NetworkDestination> assignments = new ArrayList<>(); this.taskId = taskId; this.command = command; } public void addAssignment(NetworkDestination host) { assignments.add(host); } public void removeAssignment(NetworkDestination host) { assignments.remove(host); } /** * Determine whether the Task associated with this TaskSpec has been * assigned to any resources yet. * * @return true if the Task has been assigned, false otherwise. */ public boolean isAssigned() { return assignments.isEmpty() == false; } public String toString() { String str = "[" + taskId + "] "; for (String s : command) { str += s + " "; } return str; } @Deserialize public TaskSpec(SerializationInputStream in) throws IOException { taskId = in.readInt(); int numArgs = in.readInt(); command = new String[numArgs]; for (int i = 0; i < numArgs; ++i) { command[i] = in.readString(); } } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeInt(taskId); out.writeInt(command.length); for (String s : command) { out.writeString(s); } } }
Make data zoom match place zoom
import React, { PropTypes } from 'react' import Map from '../home/map' import LayerKey from './layer-key' const PrimaryDataset = ({ dataset, lngLat }) => { if (!dataset) return null const { name, provider, description, url } = dataset const selectedLayers = [dataset] return ( <article className='cf'> <div className='fl w-40-ns'> <h1 className='f6 black-40 ttu tracked'>{name}</h1> <p className='f6 black-40 ttu tracked'>{provider}</p> <p className='lh-copy'>{description}</p> <p className='mb4'> <a href={url} target='_blank' className='green'>Find out more</a> </p> <LayerKey dataset={dataset} /> </div> <div className='fl w-60-ns pl3'> <Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={11} minZoom={8} /> </div> </article> ) } PrimaryDataset.propTypes = { dataset: PropTypes.shape({ name: PropTypes.string.isRequired, provider: PropTypes.string.isRequired, description: PropTypes.string.isRequired, url: PropTypes.string.isRequired, source: PropTypes.shape({ type: PropTypes.string.isRequired, url: PropTypes.string.isRequired }), layers: PropTypes.array }), lngLat: PropTypes.shape({ lng: PropTypes.number.isRequired, lat: PropTypes.number.isRequired }) } export default PrimaryDataset
import React, { PropTypes } from 'react' import Map from '../home/map' import LayerKey from './layer-key' const PrimaryDataset = ({ dataset, lngLat }) => { if (!dataset) return null const { name, provider, description, url } = dataset const selectedLayers = [dataset] return ( <article className='cf'> <div className='fl w-40-ns'> <h1 className='f6 black-40 ttu tracked'>{name}</h1> <p className='f6 black-40 ttu tracked'>{provider}</p> <p className='lh-copy'>{description}</p> <p className='mb4'> <a href={url} target='_blank' className='green'>Find out more</a> </p> <LayerKey dataset={dataset} /> </div> <div className='fl w-60-ns pl3'> <Map datasets={selectedLayers} selectedLayers={selectedLayers} lngLat={lngLat} zoom={10} minZoom={8} /> </div> </article> ) } PrimaryDataset.propTypes = { dataset: PropTypes.shape({ name: PropTypes.string.isRequired, provider: PropTypes.string.isRequired, description: PropTypes.string.isRequired, url: PropTypes.string.isRequired, source: PropTypes.shape({ type: PropTypes.string.isRequired, url: PropTypes.string.isRequired }), layers: PropTypes.array }), lngLat: PropTypes.shape({ lng: PropTypes.number.isRequired, lat: PropTypes.number.isRequired }) } export default PrimaryDataset
Use list instead of [:] to allow the pact argument to be an iterator
import itertools from .base import PactBase class PactGroup(PactBase): def __init__(self, pacts=None, lazy=True): if pacts is None: pacts = [] self._pacts = list(pacts) self._finished_pacts = [] self._is_lazy = lazy super(PactGroup, self).__init__() def __iadd__(self, other): self.add(other) return self def __iter__(self): return itertools.chain(self._pacts, self._finished_pacts) def add(self, pact, absorb=False): if absorb and isinstance(pact, PactGroup): if isinstance(pact, PactGroup): raise NotImplementedError('Absorbing groups is not supported') # pragma: no cover self._pacts.append(pact) if absorb: # pylint: disable=protected-access while pact._then: # then might throw, so we attempt it first self.then(pact._then[0]) pact._then.pop(0) def _is_finished(self): has_finished = True indexes_to_remove = [] for index, pact in enumerate(self._pacts): if pact.poll(): indexes_to_remove.append(index) else: has_finished = False if self._is_lazy: break for index in reversed(indexes_to_remove): self._finished_pacts.append(self._pacts.pop(index)) return has_finished def __repr__(self): return repr(list(self._pacts))
import itertools from .base import PactBase class PactGroup(PactBase): def __init__(self, pacts=None, lazy=True): if pacts is None: pacts = [] self._pacts = pacts[:] self._finished_pacts = [] self._is_lazy = lazy super(PactGroup, self).__init__() def __iadd__(self, other): self.add(other) return self def __iter__(self): return itertools.chain(self._pacts, self._finished_pacts) def add(self, pact, absorb=False): if absorb and isinstance(pact, PactGroup): if isinstance(pact, PactGroup): raise NotImplementedError('Absorbing groups is not supported') # pragma: no cover self._pacts.append(pact) if absorb: # pylint: disable=protected-access while pact._then: # then might throw, so we attempt it first self.then(pact._then[0]) pact._then.pop(0) def _is_finished(self): has_finished = True indexes_to_remove = [] for index, pact in enumerate(self._pacts): if pact.poll(): indexes_to_remove.append(index) else: has_finished = False if self._is_lazy: break for index in reversed(indexes_to_remove): self._finished_pacts.append(self._pacts.pop(index)) return has_finished def __repr__(self): return repr(list(self._pacts))
Fix bug with space not working in input boxes
window.GLOBAL_ACTIONS = { 'play': function () { wavesurfer.playPause(); }, 'back': function () { wavesurfer.skipBackward(); }, 'forth': function () { wavesurfer.skipForward(); }, 'toggle-mute': function () { wavesurfer.toggleMute(); } }; // Bind actions to buttons and keypresses document.addEventListener('DOMContentLoaded', function () { document.addEventListener('keydown', function (e) { var map = { 32: 'play', // space 37: 'back', // left 39: 'forth' // right }; if(e.target.nodeName.toLowerCase() === 'textarea'){ return; } var action = map[e.keyCode]; if (action in GLOBAL_ACTIONS) { e.preventDefault(); GLOBAL_ACTIONS[action](e); } }); [].forEach.call(document.querySelectorAll('[data-action]'), function (el) { el.addEventListener('click', function (e) { var action = e.currentTarget.dataset.action; if (action in GLOBAL_ACTIONS) { e.preventDefault(); GLOBAL_ACTIONS[action](e); } }); }); wavesurfer.on('play', function() {$('#play').addClass('hide'); $('#pause').removeClass('hide')}); wavesurfer.on('pause', function() {$('#pause').addClass('hide'); $('#play').removeClass('hide')}); });
window.GLOBAL_ACTIONS = { 'play': function () { wavesurfer.playPause(); }, 'back': function () { wavesurfer.skipBackward(); }, 'forth': function () { wavesurfer.skipForward(); }, 'toggle-mute': function () { wavesurfer.toggleMute(); } }; // Bind actions to buttons and keypresses document.addEventListener('DOMContentLoaded', function () { document.addEventListener('keydown', function (e) { var map = { 32: 'play', // space 37: 'back', // left 39: 'forth' // right }; if(e.target.nodeName.toLowerCase() === 'input'){ return; } var action = map[e.keyCode]; if (action in GLOBAL_ACTIONS) { e.preventDefault(); GLOBAL_ACTIONS[action](e); } }); [].forEach.call(document.querySelectorAll('[data-action]'), function (el) { el.addEventListener('click', function (e) { var action = e.currentTarget.dataset.action; if (action in GLOBAL_ACTIONS) { e.preventDefault(); GLOBAL_ACTIONS[action](e); } }); }); wavesurfer.on('play', function() {$('#play').addClass('hide'); $('#pause').removeClass('hide')}); wavesurfer.on('pause', function() {$('#pause').addClass('hide'); $('#play').removeClass('hide')}); });
Add some debug logging to books that fail to register
package amerifrance.guideapi.util; import amerifrance.guideapi.api.GuideAPI; import amerifrance.guideapi.api.GuideBook; import amerifrance.guideapi.api.IGuideBook; import amerifrance.guideapi.api.impl.Book; import com.google.common.collect.Lists; import net.minecraftforge.fml.common.discovery.ASMDataTable; import org.apache.commons.lang3.tuple.Pair; import java.util.List; public class AnnotationHandler { public static final List<Pair<Book, IGuideBook>> BOOK_CLASSES = Lists.newArrayList(); public static void registerBooks(ASMDataTable dataTable) { for (ASMDataTable.ASMData data : dataTable.getAll(GuideBook.class.getCanonicalName())) { try { Class<?> genericClass = Class.forName(data.getClassName()); if (!IGuideBook.class.isAssignableFrom(genericClass)) continue; IGuideBook guideBook = (IGuideBook) genericClass.newInstance(); Book book = guideBook.buildBook(); if (book == null) continue; APISetter.registerBook(book); BOOK_CLASSES.add(Pair.of(book, guideBook)); } catch (Exception e) { LogHelper.error("Error registering book for class " + data.getClassName()); e.printStackTrace(); } } APISetter.setIndexedBooks(Lists.newArrayList(GuideAPI.getBooks().values())); } }
package amerifrance.guideapi.util; import amerifrance.guideapi.api.GuideAPI; import amerifrance.guideapi.api.GuideBook; import amerifrance.guideapi.api.IGuideBook; import amerifrance.guideapi.api.impl.Book; import com.google.common.collect.Lists; import net.minecraftforge.fml.common.discovery.ASMDataTable; import org.apache.commons.lang3.tuple.Pair; import java.util.List; public class AnnotationHandler { public static final List<Pair<Book, IGuideBook>> BOOK_CLASSES = Lists.newArrayList(); public static void registerBooks(ASMDataTable dataTable) { for (ASMDataTable.ASMData data : dataTable.getAll(GuideBook.class.getCanonicalName())) { try { Class<?> genericClass = Class.forName(data.getClassName()); if (!IGuideBook.class.isAssignableFrom(genericClass)) return; IGuideBook guideBook = (IGuideBook) genericClass.newInstance(); Book book = guideBook.buildBook(); if (book == null) continue; APISetter.registerBook(book); BOOK_CLASSES.add(Pair.of(book, guideBook)); } catch (Exception e) { LogHelper.error("Error registering book for class " + data.getClassName()); } } APISetter.setIndexedBooks(Lists.newArrayList(GuideAPI.getBooks().values())); } }
Add extra constructor for backwards compatibility
package io.doist.recyclerviewext.click_listeners; import android.support.v7.widget.RecyclerView; import android.view.View; public class ClickableViewHolder extends RecyclerView.ViewHolder { public ClickableViewHolder(View itemView, OnItemClickListener onItemClickListener) { this(itemView, onItemClickListener, null); } public ClickableViewHolder(View itemView, OnItemClickListener onItemClickListener, OnItemLongClickListener onItemLongClickListener) { super(itemView); setClickListeners(onItemClickListener, onItemLongClickListener); } private void setClickListeners(final OnItemClickListener onItemClickListener, final OnItemLongClickListener onItemLongClickListener) { if (onItemClickListener != null) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onItemClickListener.onItemClick(ClickableViewHolder.this); } }); } if (onItemLongClickListener != null) { itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { onItemLongClickListener.onItemLongClick(ClickableViewHolder.this); return true; } }); } } }
package io.doist.recyclerviewext.click_listeners; import android.support.v7.widget.RecyclerView; import android.view.View; public class ClickableViewHolder extends RecyclerView.ViewHolder { public ClickableViewHolder(View itemView, OnItemClickListener onItemClickListener, OnItemLongClickListener onItemLongClickListener) { super(itemView); setClickListeners(onItemClickListener, onItemLongClickListener); } private void setClickListeners(final OnItemClickListener onItemClickListener, final OnItemLongClickListener onItemLongClickListener) { if (onItemClickListener != null) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onItemClickListener.onItemClick(ClickableViewHolder.this); } }); } if (onItemLongClickListener != null) { itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { onItemLongClickListener.onItemLongClick(ClickableViewHolder.this); return true; } }); } } }
Fix issue with recursive arrays on exact matching domains, also added function to dump entire config
<?php namespace ET; class Config { private $config; public function __construct($configFile, $visitDomain) { // Config not found at all if (!file_exists($configFile)) { throw new ConfigException('Configruation file not found: '.$configFile); } // Parse INI file $config = parse_ini_file($configFile, true); // Failed to parse, empty or no default domain specified if (!$config || !is_array($config['@'])) { throw new ConfigException('Configruation file failed to parse: '.$configFile); } // Set default-values and remove it from the list $this->config = $config['@']; unset($config['@']); //Exact matching of domain name will have priority and ignore all fuzzy matching if (isset($config[$visitDomain])) { foreach ($config[$visitDomain] as $key => $value) { if (!is_array($value)) { $this->config[$key] = $value; } else { foreach ($value as $key2 => $value2) { $this->config[$key][$key2] = $value2; } } } } else { // Fuzzy match domain name with wildcards and run to the end of the array foreach ($config as $domain => $contents) { if (fnmatch($domain, $visitDomain)) { foreach ($contents as $key => $value) { if (!is_array($value)) { $this->config[$key] = $value; } else { foreach ($value as $key2 => $value2) { $this->config[$key][$key2] = $value2; } } } } } } } public function dumpConfig() { return $this->config; } }
<?php namespace ET; class Config { private $config; public function __construct($configFile, $visitDomain) { // Config not found at all if (!file_exists($configFile)) { throw new ConfigException('Configruation file not found: '.$configFile); } // Parse INI file $config = parse_ini_file($configFile, true); // Failed to parse, empty or no default domain specified if (!$config || !is_array($config['@'])) { throw new ConfigException('Configruation file failed to parse: '.$configFile); } // Set default-values and remove it from the list $this->config = $config['@']; unset($config['@']); //Exact matching of domain name will have priority and ignore all fuzzy matching if (isset($config[$visitDomain])) { foreach ($contents as $key => $value) { $this->config[$key] = $value; } } else { // Fuzzy match domain name with wildcards and run to the end of the array foreach ($config as $domain => $contents) { if (fnmatch($domain, $visitDomain)) { foreach ($contents as $key => $value) { if (!is_array($value)) { $this->config[$key] = $value; } else { foreach ($value as $key2 => $value2) { $this->config[$key][$key2] = $value2; } } } } } } } }
Use filter instead of for loop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import omit from 'lodash.omit'; import theme from './theme.css'; class StatusLabel extends Component { static propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, mint: PropTypes.bool, teal: PropTypes.bool, violet: PropTypes.bool, ruby: PropTypes.bool, gold: PropTypes.bool, aqua: PropTypes.bool, small: PropTypes.bool, }; getColor () { const colors = [ 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal', ]; const color = colors.filter(color => this.props.hasOwnProperty(color)); return color[0]; } getSize () { return this.props.small ? 'small' : 'medium'; } render () { const { children, className, ...others } = this.props; const color = this.getColor(); const size = this.getSize(); const classes = cx( theme.label, theme[color], theme[size], className, ); const rest = omit(others, [ 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal', 'small', ]); return ( <span className={classes} {...rest} data-teamleader-ui="status-label"> {children} </span> ); } } export default StatusLabel;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import omit from 'lodash.omit'; import theme from './theme.css'; class StatusLabel extends Component { static propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, mint: PropTypes.bool, teal: PropTypes.bool, violet: PropTypes.bool, ruby: PropTypes.bool, gold: PropTypes.bool, aqua: PropTypes.bool, small: PropTypes.bool, }; getColor () { const colors = [ 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal', ]; for (var i = 0; i < colors.length; i++) { const color = colors[i]; if (this.props[color]) { return color; } } } getSize () { return this.props.small ? 'small' : 'medium'; } render () { const { children, className, ...others } = this.props; const color = this.getColor(); const size = this.getSize(); const classes = cx( theme.label, theme[color], theme[size], className, ); const rest = omit(others, [ 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal', 'small', ]); return ( <span className={classes} {...rest} data-teamleader-ui="status-label"> {children} </span> ); } } export default StatusLabel;
Fix line 40 to long issue.
const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); module.exports = function(options, fieldname, filename) { const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/'); let hash = crypto.createHash('md5'); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } let tempFilePath = path.join(dir, 'tmp' + Date.now()); let writeStream = fs.createWriteStream(tempFilePath); let fileSize = 0; // eslint-disable-line return { dataHandler: function(data) { writeStream.write(data); hash.update(data); fileSize += data.length; if (options.debug) { return console.log( // eslint-disable-line `Uploaded ${data.length} bytes for `, fieldname, filename ); } }, getFilePath: function(){ return tempFilePath; }, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: function(){ writeStream.end(); //return empty buffer since data has been uploaded to the temporary file. return Buffer.concat([]); }, cleanup: function(){ writeStream.end(); fs.unlink(tempFilePath, function(err) { if (err) throw err; }); } }; };
const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); module.exports = function(options, fieldname, filename) { const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/'); let hash = crypto.createHash('md5'); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } let tempFilePath = path.join(dir, 'tmp' + Date.now()); let writeStream = fs.createWriteStream(tempFilePath); let fileSize = 0; // eslint-disable-line return { dataHandler: function(data) { writeStream.write(data); hash.update(data); fileSize += data.length; if (options.debug) { return console.log( // eslint-disable-line `Uploaded ${data.length} bytes for `, fieldname, filename ); } }, getFilePath: function(){ return tempFilePath; }, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: function(){ writeStream.end(); return Buffer.concat([]); //return empty buffer since data has been uploaded to the temporary file. }, cleanup: function(){ writeStream.end(); fs.unlink(tempFilePath, function(err) { if (err) throw err; }); } }; };
Add private constructor for factory.
package com.novoda.downloadmanager; import com.novoda.notils.logger.simple.Log; class WaitForLockRunnable { interface Action { void performAction(); } private WaitForLockRunnable() { // Uses static factory method. } static WaitForLockAndThenPerformActionRunnable waitFor(Object lock) { return new WaitForLockAndThenPerformActionRunnable(lock); } static class WaitForLockAndThenPerformActionRunnable { private final Object lock; WaitForLockAndThenPerformActionRunnable(Object lock) { this.lock = lock; } Runnable thenPerform(final Action action) { return new Runnable() { @Override public void run() { waitOnLock(); action.performAction(); } }; } private void waitOnLock() { try { synchronized (lock) { lock.wait(); } } catch (InterruptedException e) { Log.e(e, "Interruped waiting for download service."); } } } }
package com.novoda.downloadmanager; import com.novoda.notils.logger.simple.Log; class WaitForLockRunnable { interface Action { void performAction(); } static WaitForLockAndThenPerformActionRunnable waitFor(Object lock) { return new WaitForLockAndThenPerformActionRunnable(lock); } static class WaitForLockAndThenPerformActionRunnable { private final Object lock; WaitForLockAndThenPerformActionRunnable(Object lock) { this.lock = lock; } Runnable thenPerform(final Action action) { return new Runnable() { @Override public void run() { waitOnLock(); action.performAction(); } }; } private void waitOnLock() { try { synchronized (lock) { lock.wait(); } } catch (InterruptedException e) { Log.e(e, "Interruped waiting for download service."); } } } }
Change class to use new TaskDate
package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.getDates().setStartDate(startDate); this.task.getDates().setEndDate(endDate); return this; } public TestTask build() { return this.task; } }
package seedu.doist.testutil; import java.util.Date; import seedu.doist.commons.exceptions.IllegalValueException; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.Description; import seedu.doist.model.task.Priority; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } /** * Initializes the TaskBuilder with the data of {@code personToCopy}. */ public TaskBuilder(TestTask taskToCopy) { this.task = new TestTask(taskToCopy); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Description(name)); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { task.setTags(new UniqueTagList()); for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDates(Date startDate, Date endDate) throws IllegalValueException { this.task.setStartDate(startDate); this.task.setEndDate(endDate); return this; } public TestTask build() { return this.task; } }
Fix static path to match the /suppliers URL prefix
import os import jinja2 basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False SECRET_KEY = 'this is not secret' STATIC_URL_PATH = '/suppliers/static' ASSET_PATH = STATIC_URL_PATH + '/' BASE_TEMPLATE_DATA = { 'asset_path': ASSET_PATH, 'header_class': 'with-proposition' } # Logging DM_LOG_LEVEL = 'DEBUG' DM_APP_NAME = 'buyer-frontend' DM_LOG_PATH = '/var/log/digitalmarketplace/application.log' DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id' @staticmethod def init_app(app): repo_root = os.path.abspath(os.path.dirname(__file__)) template_folders = [ os.path.join(repo_root, 'bower_components/govuk_template/views/layouts'), os.path.join(repo_root, 'app/templates') ] jinja_loader = jinja2.FileSystemLoader(template_folders) app.jinja_loader = jinja_loader class Test(Config): DEBUG = True class Development(Config): DEBUG = True, class Live(Config): DEBUG = False config = { 'development': Development, 'preview': Development, 'staging': Live, 'production': Live, 'test': Test, }
import os import jinja2 basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False SECRET_KEY = 'this is not secret' STATIC_URL_PATH = '/supplier/static' ASSET_PATH = STATIC_URL_PATH + '/' BASE_TEMPLATE_DATA = { 'asset_path': ASSET_PATH, 'header_class': 'with-proposition' } # Logging DM_LOG_LEVEL = 'DEBUG' DM_APP_NAME = 'buyer-frontend' DM_LOG_PATH = '/var/log/digitalmarketplace/application.log' DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id' @staticmethod def init_app(app): repo_root = os.path.abspath(os.path.dirname(__file__)) template_folders = [ os.path.join(repo_root, 'bower_components/govuk_template/views/layouts'), os.path.join(repo_root, 'app/templates') ] jinja_loader = jinja2.FileSystemLoader(template_folders) app.jinja_loader = jinja_loader class Test(Config): DEBUG = True class Development(Config): DEBUG = True, class Live(Config): DEBUG = False config = { 'development': Development, 'preview': Development, 'staging': Live, 'production': Live, 'test': Test, }
Fix form validation with editing form (values already here)
// Pay - /app/public/factories/formValidator.js // Form Validator resource 'use strict'; pay.factory('FormValidator', [function () { return function (form, imageSelector, imageValidator) { // If we end directly the function, all errors may be not thrown var formValid = true; // Image validation console.log(typeof imageValidator !== 'undefined'); if (typeof imageValidator !== 'undefined') { var $file = form[imageSelector]; var file = $file.files[0]; if (!file || (file.type !== 'image/png' && file.type !== 'image/jpeg')) { $($file).parent().parent().next().addClass('ng-invalid'); formValid = false; } else { $($file).parent().parent().next().removeClass('ng-invalid').addClass('ng-valid'); } } // Input validation var isFormValid = $('.ng-pristine, .ng-invalid', form).filter(function () { return this.value.length === 0; }).length === 0; if (!isFormValid) { var $invalids = $('.ng-pristine, .ng-invalid', form).filter(function () { return this.value.length === 0; }); $invalids.removeClass('ng-pristine ng-valid').addClass('ng-invalid'); formValid = false; } return formValid; }; }]);
// Pay - /app/public/factories/formValidator.js // Form Validator resource 'use strict'; pay.factory('FormValidator', [function () { return function (form, imageSelector) { // If we end directly the function, all errors may be not thrown var formValid = true; // Image validation var $file = form[imageSelector]; var file = $file.files[0]; if (!file || (file.type !== 'image/png' && file.type !== 'image/jpeg')) { $($file).parent().parent().next().addClass('ng-invalid'); formValid = false; } else { $($file).parent().parent().next().removeClass('ng-invalid').addClass('ng-valid'); } // Input validation var isFormValid = $('.ng-pristine, .ng-invalid', form).length === 0; if (!isFormValid) { var $invalids = $('.ng-pristine, .ng-invalid', form); $invalids.removeClass('ng-pristine ng-valid').addClass('ng-invalid'); formValid = false; } return formValid; }; }]);
Make reporter succeed in talking to the graph server
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import argparse import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(fpath) unlink_ok = False with file(fpath, 'rb') as f: try: post_data = 'data=%s' % (f.read(),) r = requests.post(self.url, data=post_data) unlink_ok = True except Exception, e: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run()
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeReporter(object): def __init__(self): self.rootdir = stoneridge.get_config('server', 'directory') self.pattern = os.path.join(self.rootdir, '*.json') self.url = stoneridge.get_config('report', 'url') def run(self): files = glob.glob(self.pattern) for fpath in files: fname = os.path.basename(f) unlink_ok = False with file(fpath, 'rb') as f: try: requests.post(self.url, files={fname: f}) unlink_ok = True except: pass if unlink_ok: os.unlink(fpath) @stoneridge.main def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', dest='config', required=True) args = parser.parse_args() stoneridge._conffile = args.config reporter = StoneRidgeReporter() reporter.run()
[ClientBundle] Fix for adding contact details
(function($) { 'use strict'; /** * Form Collection */ $(document.body).on('click', '.contact_details_collection li', function(event) { var $this = $(this), value, collectionHolder, prototype, regex, form, prototype_name, collectionContainer = $this.closest('.contact-type-list').siblings('.collection-container'); collectionHolder = collectionContainer.find('.' + $this.parents('ul').data('target') + '[data-type=' + $this.data('type') + ']'); value = $(this).data('value'); prototype = collectionHolder.data('prototype'); if(undefined !== prototype && null !== prototype) { if(collectionHolder.data('prototype-name')) { prototype_name = collectionHolder.data('prototype-name'); } else { prototype_name = '__name__'; } regex = new RegExp(prototype_name, "g"); form = $(prototype.replace(regex, collectionHolder.children().length)).hide(); collectionHolder.append(form); form.slideDown(); } }); })(window.jQuery);
(function($) { 'use strict'; /** * Form Collection */ $(document.body).on('click', '.contact_details_collection li', function(event) { var value, collectionHolder, prototype, regex, form, prototype_name, collectionContainer = $(this).closest('.contact-type-list').siblings('.collection-container'); collectionHolder = collectionContainer.find('.' + $(this).parents('ul').data('target')); collectionHolder = collectionHolder.filter('[data-type=' + $(this).data('type') + ']'); value = $(this).data('value'); prototype = collectionHolder.data('prototype'); if(undefined !== prototype && null !== prototype) { if(collectionHolder.data('prototype-name')) { prototype_name = collectionHolder.data('prototype-name'); } else { prototype_name = '__name__'; } regex = new RegExp(prototype_name, "g"); form = $(prototype.replace(regex, collectionHolder.children().length - 1)).hide(); collectionContainer.append(form); form.slideDown(); } }); })(window.jQuery);
Make sequence marker types (:type) case insensitive
import bpy def find_seqs(scene, select_marker): sequences = {} sequence_flags = {} for marker in scene.timeline_markers: if ":" not in marker.name or (select_marker and not marker.select): continue name, what = marker.name.rsplit(":", 1) what = what.lower() if name not in sequences: sequences[name] = {} if what in sequences[name]: print("Warning: Got duplicate '{}' marker for sequence '{}' at frame {} (first was at frame {}), ignoring".format(what, name, marker.frame, sequences[name][what].frame)) continue sequences[name][what] = marker if "Sequences" in bpy.data.texts: for line in bpy.data.texts["Sequences"].as_string().split("\n"): line = line.strip() if not line: continue if ":" not in line: print("Invalid line in 'Sequences':", line) continue name, flags = line.split(":", 1) if flags.lstrip(): flags = tuple(map(lambda f: f.strip(), flags.split(","))) else: flags = () sequence_flags[name] = flags return sequences, sequence_flags
import bpy def find_seqs(scene, select_marker): sequences = {} sequence_flags = {} for marker in scene.timeline_markers: if ":" not in marker.name or (select_marker and not marker.select): continue name, what = marker.name.rsplit(":", 1) if name not in sequences: sequences[name] = {} if what in sequences[name]: print("Warning: Got duplicate '{}' marker for sequence '{}' at frame {} (first was at frame {}), ignoring".format(what, name, marker.frame, sequences[name][what].frame)) continue sequences[name][what] = marker if "Sequences" in bpy.data.texts: for line in bpy.data.texts["Sequences"].as_string().split("\n"): line = line.strip() if not line: continue if ":" not in line: print("Invalid line in 'Sequences':", line) continue name, flags = line.split(":", 1) if flags.lstrip(): flags = tuple(map(lambda f: f.strip(), flags.split(","))) else: flags = () sequence_flags[name] = flags return sequences, sequence_flags
Add tags to the component seeder
<?php use CachetHQ\Cachet\Models\Component; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Seeder; class ComponentTableSeeder extends Seeder { /** * Run the database seeding. * * @return void */ public function run() { Model::unguard(); $defaultComponents = [ [ "name" => "API", "description" => "Used by third-parties to connect to us", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", "tags" => "", ], [ "name" => "Payments", "description" => "Backed by Stripe", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", "tags" => "", ], [ "name" => "Website", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", "tags" => "", ], ]; Component::truncate(); foreach ($defaultComponents as $component) { Component::create($component); } } }
<?php use CachetHQ\Cachet\Models\Component; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Seeder; class ComponentTableSeeder extends Seeder { /** * Run the database seeding. * * @return void */ public function run() { Model::unguard(); $defaultComponents = [ [ "name" => "API", "description" => "Used by third-parties to connect to us", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", ], [ "name" => "Payments", "description" => "Backed by Stripe", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", ], [ "name" => "Website", "status" => 1, "user_id" => 1, "order" => 0, "group_id" => 0, "link" => "", ], ]; Component::truncate(); foreach ($defaultComponents as $component) { Component::create($component); } } }
Fix stupid deep equal check
import { assert } from 'chai'; import { expandNodesToLevel } from '../src'; const nestedTree = [{ value: '0', label: 'Node 0', children: [{ value: '0-0', label: 'Node 0-0', }, { value: '0-1', label: 'Node 0-1', children: [{ value: '0-1-0', label: 'Node 0-1-0', children: [{ value: '0-1-0-0', label: 'Node 0-1-0-0', }], }, { value: '0-1-1', label: 'Node 0-1-1', children: [{ value: '0-1-1-0', label: 'Node 0-1-1-0', }], }], }, { value: '0-2', label: 'Node 0-2', }], }, { value: '1', label: 'Node 1', }]; describe('utils', () => { describe('expandNodesToLevel', () => { it('should recursively traverse a tree of nodes and return the key values of parents from the level specified', () => { const expected = ['0', '0-1']; assert.deepEqual(expected, expandNodesToLevel(nestedTree, 1)); }); }); });
import { assert } from 'chai'; import { expandNodesToLevel } from '../src'; const nestedTree = [{ value: '0', label: 'Node 0', children: [{ value: '0-0', label: 'Node 0-0', }, { value: '0-1', label: 'Node 0-1', children: [{ value: '0-1-0', label: 'Node 0-1-0', children: [{ value: '0-1-0-0', label: 'Node 0-1-0-0', }], }, { value: '0-1-1', label: 'Node 0-1-1', children: [{ value: '0-1-1-0', label: 'Node 0-1-1-0', }], }], }, { value: '0-2', label: 'Node 0-2', }], }, { value: '1', label: 'Node 1', }]; describe('utils', () => { describe('expandNodesToLevel', () => { it('should recursively traverse a tree of nodes and return the key values of parents from the level specified', () => { const expected = ['0', '0-1']; assert.equal(expected, expandNodesToLevel(nestedTree, 1)); }); }); });
Use disable autorum api call
<?php namespace NewRelic\Listener; use Zend\EventManager\EventManagerInterface as Events; use Zend\Mvc\MvcEvent; class ResponseListener extends AbstractListener { /** * @param Events $events * @return void */ public function attach(Events $events) { $this->listeners[] = $events->attach(MvcEvent::EVENT_FINISH, array($this, 'onResponse'), 100); } /** * @param MvcEvent $e * @return void */ public function onResponse(MvcEvent $e) { if (!$this->options->getBrowserTimingEnabled()) { $this->client->disableAutorum(); return; } if ($this->options->getBrowserTimingAutoInstrument()) { ini_set('newrelic.browser_monitoring.auto_instrument', true); return; } $response = $e->getResponse(); $content = $response->getContent(); $browserTimingHeader = $this->client->getBrowserTimingHeader(); $browserTimingFooter = $this->client->getBrowserTimingFooter(); $content = str_replace('<head>', '<head>' . $browserTimingHeader, $content); $content = str_replace('</body>', $browserTimingFooter . '</body>', $content); $response->setContent($content); } }
<?php namespace NewRelic\Listener; use Zend\EventManager\EventManagerInterface as Events; use Zend\Mvc\MvcEvent; class ResponseListener extends AbstractListener { /** * @param Events $events * @return void */ public function attach(Events $events) { $this->listeners[] = $events->attach(MvcEvent::EVENT_FINISH, array($this, 'onResponse'), 100); } /** * @param MvcEvent $e * @return void */ public function onResponse(MvcEvent $e) { if (!$this->options->getBrowserTimingEnabled()) { return; } if ($this->options->getBrowserTimingAutoInstrument()) { ini_set( 'newrelic.browser_monitoring.auto_instrument', $this->options->getBrowserTimingAutoInstrument() ); return; } $response = $e->getResponse(); $content = $response->getContent(); $browserTimingHeader = $this->client->getBrowserTimingHeader(); $browserTimingFooter = $this->client->getBrowserTimingFooter(); $content = str_replace('<head>', '<head>' . $browserTimingHeader, $content); $content = str_replace('</body>', $browserTimingFooter . '</body>', $content); $response->setContent($content); } }
Maintain alphabetical order in `install_requires` PiperOrigin-RevId: 395092683 Change-Id: I87f23eafcb8a3cdafd36b8fd700f8a1f24f9fa6e GitOrigin-RevId: a0819922a706dec7b8c2a17181c56a6900288e67
# Copyright 2021 DeepMind Technologies Limited # # 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. """Setup configuration specifying XManager dependencies.""" from setuptools import find_namespace_packages from setuptools import setup setup( name='xmanager', version='1.0.0', description='A framework for managing experiments', author='DeepMind Technologies Limited', packages=find_namespace_packages(), include_package_data=True, package_data={'': ['*.sh', '*.sql']}, python_requires='>=3.7', install_requires=[ 'absl-py', 'async_generator', 'attrs', 'docker', 'google-api-core', 'google-api-python-client', 'google-cloud-aiplatform>=1.4.0', 'google-auth', 'google-cloud-storage', 'humanize', 'immutabledict', 'kubernetes', 'sqlalchemy==1.2', 'termcolor', ], entry_points={ 'console_scripts': ['xmanager = xmanager.cli.cli:Entrypoint',], }, )
# Copyright 2021 DeepMind Technologies Limited # # 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. """Setup configuration specifying XManager dependencies.""" from setuptools import find_namespace_packages from setuptools import setup setup( name='xmanager', version='1.0.0', description='A framework for managing experiments', author='DeepMind Technologies Limited', packages=find_namespace_packages(), include_package_data=True, package_data={'': ['*.sh', '*.sql']}, python_requires='>=3.7', install_requires=[ 'absl-py', 'async_generator', 'attrs', 'docker', 'immutabledict', 'google-api-core', 'google-api-python-client', 'google-cloud-aiplatform>=1.4.0', 'google-auth', 'google-cloud-storage', 'humanize', 'kubernetes', 'sqlalchemy==1.2', 'termcolor', ], entry_points={ 'console_scripts': ['xmanager = xmanager.cli.cli:Entrypoint',], }, )
Add highlight to result in transformer
<?php namespace makeandship\elasticsearch\transformer; use makeandship\elasticsearch\Util; class SearchTransformer { public function transform($response) { $val = array( 'total' => $response->getTotalHits(), 'facets' => array(), 'ids' => array(), 'results' => array() ); foreach ($response->getAggregations() as $name => $agg) { if (isset($agg['facet']['buckets'])) { foreach ($agg['facet']['buckets'] as $bucket) { $val['facets'][$name][$bucket['key']] = $bucket['doc_count']; } } if (isset($agg['range']['buckets'])) { foreach ($agg['range']['buckets'] as $bucket) { $from = isset($bucket['from']) ? $bucket['from'] : ''; $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : ''; $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count']; } } } foreach ($response->getResults() as $result) { $id = $result->getId(); $source = $result->getSource(); $hit = $result->getHit(); $source['id'] = $id; $highlight = Util::safely_get_attribute($hit, 'highlight'); if ($highlight) { $source['highlight'] = $highlight; } $val['ids'][] = $id; $val['results'][] = $source; } return Util::apply_filters('searcher_results', $val, $response); } }
<?php namespace makeandship\elasticsearch\transformer; use makeandship\elasticsearch\Util; class SearchTransformer { public function transform($response) { $val = array( 'total' => $response->getTotalHits(), 'facets' => array(), 'ids' => array(), 'results' => array() ); foreach ($response->getAggregations() as $name => $agg) { if (isset($agg['facet']['buckets'])) { foreach ($agg['facet']['buckets'] as $bucket) { $val['facets'][$name][$bucket['key']] = $bucket['doc_count']; } } if (isset($agg['range']['buckets'])) { foreach ($agg['range']['buckets'] as $bucket) { $from = isset($bucket['from']) ? $bucket['from'] : ''; $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : ''; $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count']; } } } foreach ($response->getResults() as $result) { $id = $result->getId(); $source = $result->getSource(); $source['id'] = $id; $highlight = Util::safely_get_attribute($result, 'highlight'); if ($highlight) { $source['highlight'] = $highlight; } $val['ids'][] = $id; $val['results'][] = $source; } return Util::apply_filters('searcher_results', $val, $response); } }
Disable Flask 12h caching in debug mode - prevented refreshing of Angular directive templates
#!/usr/bin/env python """Main module""" from __future__ import print_function from __future__ import absolute_import import gevent import gevent.monkey gevent.monkey.patch_all() from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler import werkzeug.serving # from werkzeug.debug import DebuggedApplication # TODO .app gives error about relative import from .app import get_app, send_bulk APP_PORT = 5000 DEBUG = True # def main(): """Starts web application """ @werkzeug.serving.run_with_reloader def go(): app = get_app() app.debug = DEBUG if app.debug: app.config.update(SEND_FILE_MAX_AGE_DEFAULT=0) # TODO: asset debug settings will cause bad YSLOW rating app.config['COMPRESS_DEBUG'] = False app.config['ASSETS_DEBUG'] = DEBUG # Breaks web socket communication # (WebSocketConnectionClosedException in client) # app = DebuggedApplication(app, evalex=True) http_server = WSGIServer(('', APP_PORT), app, handler_class=WebSocketHandler) # gevent.spawn(send_dummy_notifications) gevent.spawn(send_bulk) http_server.serve_forever() # app.run() if __name__ == '__main__': main = werkzeug.serving.run_with_reloader(main) print('purkinje ready') main()
#!/usr/bin/env python """Main module""" from __future__ import print_function from __future__ import absolute_import import gevent import gevent.monkey gevent.monkey.patch_all() from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler import werkzeug.serving # from werkzeug.debug import DebuggedApplication # TODO .app gives error about relative import from .app import get_app, send_bulk APP_PORT = 5000 DEBUG = True # def main(): """Starts web application """ @werkzeug.serving.run_with_reloader def go(): app = get_app() app.debug = DEBUG # TODO: asset debug settings will cause bad YSLOW rating app.config['COMPRESS_DEBUG'] = False app.config['ASSETS_DEBUG'] = DEBUG # Breaks web socket communication # (WebSocketConnectionClosedException in client) # app = DebuggedApplication(app, evalex=True) http_server = WSGIServer(('', APP_PORT), app, handler_class=WebSocketHandler) # gevent.spawn(send_dummy_notifications) gevent.spawn(send_bulk) http_server.serve_forever() # app.run() if __name__ == '__main__': main = werkzeug.serving.run_with_reloader(main) print('purkinje ready') main()
Add prop structure and performance models
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius W 10 [lbf] prop weight """ def setup(self): exec parse_variables(Propeller.__doc__) def performance(state): return Propeller_Performance(self, state) class Propeller_Performance(Model): """ Propeller Model Variables --------- T [N] thrust Tc [-] coefficient of thrust etaadd 0.7 [-] swirl and nonuniformity losses etav 0.85 [-] viscous losses etai [-] inviscid losses eta [-] overall efficiency z1 self.helper [-] efficiency helper 1 z2 [-] efficiency helper 2 """ def helper(self, c): return 2. - 1./c[self.etaadd] def setup(self,parent, state): exec parse_variables(Propeller.__doc__) V = state.V rho = state.rho R = parent.R constraints = [eta <= etav*etai, Tc == T/(0.5*rho*V**2*pi*R**2), z2 >= Tc + 1, etai*(z1 + z2**0.5/etaadd) <= 2] return constraints
" propeller model " from numpy import pi from gpkit import Model, parse_variables, SignomialsEnabled, SignomialEquality class Propeller(Model): """ Propeller Model Variables --------- R 10 [m] prop radius """ def setup(self): exec parse_variables(Propeller.__doc__) def performance(state): return Propeller_Performance(self, state) class Propeller_Performance(Model): """ Propeller Model Variables --------- T [N] thrust Tc [-] coefficient of thrust etaadd 0.7 [-] swirl and nonuniformity losses etav 0.85 [-] viscous losses etai [-] inviscid losses eta [-] overall efficiency z1 self.helper [-] efficiency helper 1 z2 [-] efficiency helper 2 """ def helper(self, c): return 2. - 1./c[self.etaadd] def setup(self, state): exec parse_variables(Propeller.__doc__) V = state.V rho = state.rho constraints = [eta <= etav*etai, Tc == T/(0.5*rho*V**2*pi*R**2), z2 >= Tc + 1, etai*(z1 + z2**0.5/etaadd) <= 2] return constraints
Include static subdirectories in package
""" Favien ====== Network canvas community. """ from setuptools import setup setup( name='Favien', version='dev', url='https://github.com/limeburst/favien', author='Jihyeok Seo', author_email='[email protected]', description='Network canvas community', long_description=__doc__, zip_safe=False, packages=['favien', 'favien.web'], package_data={ 'favien.web': ['templates/*.*', 'templates/*/*.*', 'static/*.*', 'static/*/*.*', 'translations/*/LC_MESSAGES/*'], }, message_extractors={ 'favien/web/templates': [ ('**.html', 'jinja2', { 'extensions': 'jinja2.ext.autoescape,' 'jinja2.ext.with_' }) ] }, install_requires=[ 'Flask', 'Flask-Babel', 'SQLAlchemy', 'boto', 'click', 'redis', 'requests', 'requests_oauthlib', ], entry_points={ 'console_scripts': ['fav = favien.cli:cli'], } )
""" Favien ====== Network canvas community. """ from setuptools import setup setup( name='Favien', version='dev', url='https://github.com/limeburst/favien', author='Jihyeok Seo', author_email='[email protected]', description='Network canvas community', long_description=__doc__, zip_safe=False, packages=['favien', 'favien.web'], package_data={ 'favien.web': ['templates/*.*', 'templates/*/*.*', 'static/*.*', 'translations/*/LC_MESSAGES/*'], }, message_extractors={ 'favien/web/templates': [ ('**.html', 'jinja2', { 'extensions': 'jinja2.ext.autoescape,' 'jinja2.ext.with_' }) ] }, install_requires=[ 'Flask', 'Flask-Babel', 'SQLAlchemy', 'boto', 'click', 'redis', 'requests', 'requests_oauthlib', ], entry_points={ 'console_scripts': ['fav = favien.cli:cli'], } )
Remove comma for RT search
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') formatted_title = formatted_title.replace(':', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
Prepare for two-factor auth scenarios
export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { if (response.accessToken) { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) // If there was not an accessToken in the response, allow the response to pass through to handle two-factor-auth } else { return response } }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } }
export default function makeAuthActions (feathersClient) { return { authenticate (store, data) { const { commit, state, dispatch } = store commit('setAuthenticatePending') if (state.errorOnAuthenticate) { commit('clearAuthenticateError') } return feathersClient.authenticate(data) .then(response => { commit('setAccessToken', response.accessToken) // Decode the token and set the payload, but return the response return feathersClient.passport.verifyJWT(response.accessToken) .then(payload => { commit('setPayload', payload) // Populate the user if the userService was provided if (state.userService && payload.hasOwnProperty('userId')) { return dispatch('populateUser', payload.userId) .then(() => { commit('unsetAuthenticatePending') return response }) } else { commit('unsetAuthenticatePending') } return response }) }) .catch(error => { commit('setAuthenticateError', error) commit('unsetAuthenticatePending') return Promise.reject(error) }) }, populateUser ({ commit, state }, userId) { return feathersClient.service(state.userService) .get(userId) .then(user => { commit('setUser', user) return user }) }, logout ({commit}) { commit('setLogoutPending') return feathersClient.logout() .then(response => { commit('logout') commit('unsetLogoutPending') return response }) .catch(error => { return Promise.reject(error) }) } } }
Add missing 'boltons' package & clean up
#!/usr/bin/env python """Setuptools setup.""" from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
#!/usr/bin/env python import os import sys from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='[email protected]', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
Allow augmented data passing to combineResources
var _ = require('underscore'), lumbar = require('../lumbar'); function combineResources(context, outputData, callback) { var resources = context.resources || []; if (!resources.length) { return callback(); } context.outputFile(function(callback) { lumbar.combine( resources, context.fileName, context.options.minimize && context.mode === 'scripts', context.mode === 'styles', function(err, data) { if (data) { _.extend(data, outputData, { fileConfig: context.fileConfig, platform: context.platform, mode: context.mode }); } callback(err, data) }); }, callback); } module.exports = { module: function(context, next, complete) { next(function(err) { if (err) { return complete(err); } if (!context.combined) { context.resources = context.moduleResources; context.moduleResources = undefined; combineResources(context, { package: context.package, module: context.module.name }, complete); } else { context.combineResources = context.combineResources || {}; context.combineResources[context.module.name] = context.moduleResources; context.moduleResources = undefined; complete(); } }); } };
var lumbar = require('../lumbar'); function combineResources(context, callback) { var resources = context.resources || []; if (!resources.length) { return callback(); } context.outputFile(function(callback) { lumbar.combine( resources, context.fileName, context.options.minimize && context.mode === 'scripts', context.mode === 'styles', function(err, data) { if (data) { data.fileConfig = context.fileConfig; data.platform = context.platform; data.mode = context.mode; } callback(err, data) }); }, callback); } module.exports = { module: function(context, next, complete) { next(function(err) { if (err) { return complete(err); } if (!context.combined) { context.resources = context.moduleResources; context.moduleResources = undefined; combineResources(context, function(err, data) { if (data) { data.package = context.package; data.module = context.module.name; } complete(err, data); }); } else { context.combineResources = context.combineResources || {}; context.combineResources[context.module.name] = context.moduleResources; context.moduleResources = undefined; complete(); } }); } };
Improve handling of profile defaults If no profiles exist in the .novacfg, fall back to the default always.
var _ = require('underscore') , fs = require('fs'); function loadConfiguration() { var default_config = { default: { s3: { region: null, bucket: null, keyPrefix: '', }, }, profiles: {}, get: function(domain, profile) { var cfg = this.default[domain]; profile = profile || this.commonOptions.profile; if (profile) { var profilecfg = this.profiles[profile] || {}; cfg = _.extend({}, cfg, profilecfg[domain]); } return cfg; }, currentDeployment: { id: null, date: null, ref: null, region: null, }, currentBuild: { date: null, project: null, }, commonOptions: { }, paramsObject: { }, }; var filename = process.env['HOME'] + '/.novacfg'; if (fs.existsSync(filename)) { var data = fs.readFileSync(filename); var config = JSON.parse(data) || {}; } return _.extend(default_config, config); } module.exports = loadConfiguration();
var _ = require('underscore') , fs = require('fs'); function loadConfiguration() { var default_config = { default: { s3: { region: null, bucket: null, keyPrefix: '', }, }, get: function(domain, profile) { var cfg = this.default[domain]; profile = profile || this.commonOptions.profile; if (profile) { var profilecfg = this.profiles[profile] || {}; cfg = _.extend({}, cfg, profilecfg[domain]); } return cfg; }, currentDeployment: { id: null, date: null, ref: null, region: null, }, currentBuild: { date: null, project: null, }, commonOptions: { }, paramsObject: { }, }; var filename = process.env['HOME'] + '/.novacfg'; if (fs.existsSync(filename)) { var data = fs.readFileSync(filename); var config = JSON.parse(data) || {}; } return _.extend(default_config, config); } module.exports = loadConfiguration();
BAP-11418: Implement Upload (Import) functionality - remove not used import
<?php namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy; use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository; use Oro\Bundle\TranslationBundle\Entity\Translation; class TranslationResetStrategy extends TranslationImportStrategy { /** * @var array */ protected $processedLanguages = []; /** * @param Translation $entity * * {@inheritdoc} */ protected function beforeProcessEntity($entity) { if ($entity instanceof Translation) { $locale = $entity->getLocale(); if ($locale && empty($this->processedLanguages[$locale])) { /** @var TranslationRepository $repository */ $repository = $this->doctrineHelper->getEntityRepositoryForClass($this->entityName); $this->context->incrementDeleteCount( $repository->getCountByLocale($locale) ); $repository->deleteByLocale($locale); $this->processedLanguages[$locale] = true; } } return parent::beforeProcessEntity($entity); } /** * {@inheritdoc} */ protected function findExistingEntity($entity, array $searchContext = []) { // no need to search entity if (is_a($entity, $this->entityName)) { return null; } return parent::findExistingEntity($entity, $searchContext); } /** * There is no replaced entities during reset * * {@inheritdoc} */ protected function updateContextCounters($entity) { $this->context->incrementAddCount(); } }
<?php namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy; use Oro\Bundle\ImportExportBundle\Strategy\Import\ConfigurableAddOrReplaceStrategy; use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository; use Oro\Bundle\TranslationBundle\Entity\Translation; class TranslationResetStrategy extends TranslationImportStrategy { /** * @var array */ protected $processedLanguages = []; /** * @param Translation $entity * * {@inheritdoc} */ protected function beforeProcessEntity($entity) { if ($entity instanceof Translation) { $locale = $entity->getLocale(); if ($locale && empty($this->processedLanguages[$locale])) { /** @var TranslationRepository $repository */ $repository = $this->doctrineHelper->getEntityRepositoryForClass($this->entityName); $this->context->incrementDeleteCount( $repository->getCountByLocale($locale) ); $repository->deleteByLocale($locale); $this->processedLanguages[$locale] = true; } } return parent::beforeProcessEntity($entity); } /** * {@inheritdoc} */ protected function findExistingEntity($entity, array $searchContext = []) { // no need to search entity if (is_a($entity, $this->entityName)) { return null; } return parent::findExistingEntity($entity, $searchContext); } /** * There is no replaced entities during reset * * {@inheritdoc} */ protected function updateContextCounters($entity) { $this->context->incrementAddCount(); } }
Update to return data in alphabetical order Returns the countries and continents in alphabetical order, using the orderBy Method in Ascending order.
<?php namespace Khsing\World; use Khsing\World\Models\Continent; use Khsing\World\Models\Country; use Khsing\World\Models\Division; /** * World */ class World { public static function Continents() { return Continent::orderBy('name', 'asc')->get(); } public static function Countries() { return Country::orderBy('name', 'asc')->get(); } public static function getContinentByCode($code) { return Continent::getByCode($code); } public static function getCountryByCode($code) { return Country::getByCode($code); } public static function getByCode($code) { $code = strtolower($code); if (strpos($code, '-')) { list($country_code, $code) = explode('-', $code); $country = self::getCountryByCode($country_code); } else { return self::getCountryByCode($code); } if ($country->has_division) { return Division::where([ ['country_id', $country->id], ['code', $code], ])->first(); } return City::where([ ['country_id', $country->id], ['code', $code], ])->first(); throw new \Khsing\World\Exceptions\InvalidCodeException("Code is invalid"); } }
<?php namespace Khsing\World; use Khsing\World\Models\Continent; use Khsing\World\Models\Country; use Khsing\World\Models\Division; /** * World */ class World { public static function Continents() { return Continent::get(); } public static function Countries() { return Country::get(); } public static function getContinentByCode($code) { return Continent::getByCode($code); } public static function getCountryByCode($code) { return Country::getByCode($code); } public static function getByCode($code) { $code = strtolower($code); if (strpos($code, '-')) { list($country_code, $code) = explode('-', $code); $country = self::getCountryByCode($country_code); } else { return self::getCountryByCode($code); } if ($country->has_division) { return Division::where([ ['country_id', $country->id], ['code', $code], ])->first(); } return City::where([ ['country_id', $country->id], ['code', $code], ])->first(); throw new \Khsing\World\Exceptions\InvalidCodeException("Code is invalid"); } }
Introduce integration tests using DropWizards ResourceTest. Include ability to return an Invalid Request message when the DLN or EnquiryId are missing.
package uk.gov.dvla.domain; public class Message { private String key; private String description; private boolean error; private int type; public Message(){} public Message(String key) { this.key = key; } public Message(String key, MessageType type) { this.key = key; this.type = type.getMessageType(); } public Message(String description, boolean error) { this.description = description; this.error = error; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public void setError(boolean error) { this.error = error; } public boolean isError() { return this.error; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
package uk.gov.dvla.domain; public class Message { private String key; private String message; private boolean error; private int type; public Message(){} public Message(String key) { this.key = key; } public Message(String key, MessageType type) { this.key = key; this.type = type.getMessageType(); } public Message(String message, boolean error) { this.message = message; this.error = error; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public void setMessage(String message) { this.message = message; } public void setError(boolean error) { this.error = error; } public boolean isError() { return this.error; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
Fix missing text in services page
/* eslint-disable react/no-danger */ /* eslint-disable camelcase */ import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import DOMPurify from 'dompurify'; const ServiceDetailStdout = ({ taskid }) => { const [Taskresults, setTaskresults] = useState(''); const [Error, SetError] = useState(undefined); useEffect(() => { miqSparkleOn(); API.wait_for_task(taskid) .then(({ task_results }) => setTaskresults(task_results)) .catch((error) => { console.error(error); SetError(error.message); }) .then(() => { miqSparkleOff(); API.delete(`/api/tasks/${taskid}`); }); }, [taskid]); return ( <div className="standard_output"> {Error && ( <> <p> {' '} {__('Error loading data:')} </p> <p> {' '} {Error} </p> </> )} {Taskresults && ( <> <h3>{__('Standard Output:')}</h3> <div className="content" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(Taskresults) }} /> </> )} </div> ); }; export default ServiceDetailStdout; ServiceDetailStdout.propTypes = { taskid: PropTypes.number.isRequired, };
/* eslint-disable react/no-danger */ /* eslint-disable camelcase */ import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import DOMPurify from 'dompurify'; const ServiceDetailStdout = ({ taskid }) => { const [Taskresults, setTaskresults] = useState(''); const [Error, SetError] = useState(undefined); useEffect(() => { miqSparkleOn(); API.wait_for_task(taskid) .then(({ task_results }) => setTaskresults(task_results)) .catch((error) => { console.error(error); SetError(error.message); }) .then(() => { miqSparkleOff(); API.delete(`/api/tasks/${taskid}`); }); }, [taskid]); return ( <div className="standard_output"> {Error && ( <> <p> {' '} {_('Error loading data:')} </p> <p> {' '} {Error} </p> </> )} {Taskresults && ( <> <h3>{ _('Standard Output:')}</h3> <div className="content" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(Taskresults) }} /> </> )} </div> ); }; export default ServiceDetailStdout; ServiceDetailStdout.propTypes = { taskid: PropTypes.number.isRequired, };
Allow widget installation using the path.
<?php namespace Yajra\CMS\Console; use Illuminate\Console\Command; use Yajra\CMS\Repositories\Extension\Repository; class WidgetPublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'widget:install {name} {--path}'; /** * The console command description. * * @var string */ protected $description = 'Install YajraCMS widget extension.'; /** * @var \Yajra\CMS\Repositories\Extension\Repository */ private $extensions; /** * Create a new command instance. * * @param \Yajra\CMS\Repositories\Extension\Repository $extensions */ public function __construct(Repository $extensions) { parent::__construct(); $this->extensions = $extensions; } /** * Execute the console command. * * @return mixed */ public function handle() { $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json'; if ($this->option('path')) { $path = base_path($this->argument('name')); } $this->extensions->registerManifest($path); $this->laravel->make('cache.store')->forget('extensions.widgets'); $this->laravel->make('cache.store')->forget('extensions.all'); $this->info($this->argument('name') . ' widget extension installed!'); } }
<?php namespace Yajra\CMS\Console; use Illuminate\Console\Command; use Yajra\CMS\Repositories\Extension\Repository; class WidgetPublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'widget:install {name}'; /** * The console command description. * * @var string */ protected $description = 'Install YajraCMS widget extension.'; /** * @var \Yajra\CMS\Repositories\Extension\Repository */ private $extensions; /** * Create a new command instance. * * @param \Yajra\CMS\Repositories\Extension\Repository $extensions */ public function __construct(Repository $extensions) { parent::__construct(); $this->extensions = $extensions; } /** * Execute the console command. * * @return mixed */ public function handle() { $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json'; $this->extensions->registerManifest($path); $this->laravel->make('cache.store')->forget('extensions.widgets'); $this->laravel->make('cache.store')->forget('extensions.all'); $this->info($this->argument('name') . ' widget extension installed!'); } }
Fix bad bound in Type 0x00 (Real) reading
<?php /* * Part of tivars_lib * (C) 2015 Adrien 'Adriweb' Bertrand * https://github.com/adriweb/tivars_lib * License: MIT */ namespace tivars\TypeHandlers; include_once "ITIVarTypeHandler.php"; // Type Handler for type 0x00: Real class TH_0x00 implements ITIVarTypeHandler { public function makeDataFromString($str = '', array $options = []) { // TODO: Implement makeDataFromString() method. } public function makeStringFromData(array $data = [], array $options = []) { if (count($data) !== 9) { throw new \Exception("Invalid data array. Needs to contain 9 bytes"); } $flags = $data[0]; $isNegative = ($flags >> 7 === 1); // $isUndef = ($flags & 1 === 1); // if true, "used for initial sequence values" $exponent = $data[1] - 0x80; $number = ''; for ($i = 2; $i < 9; $i++) { $number .= dechex($data[$i]); } $number = substr($number, 0, 1) . '.' . substr($number, 1); $number = ($isNegative ? -1 : 1) * pow(10, $exponent) * ((float)$number); return (string)$number; } }
<?php /* * Part of tivars_lib * (C) 2015 Adrien 'Adriweb' Bertrand * https://github.com/adriweb/tivars_lib * License: MIT */ namespace tivars\TypeHandlers; include_once "ITIVarTypeHandler.php"; // Type Handler for type 0x00: Real class TH_0x00 implements ITIVarTypeHandler { public function makeDataFromString($str = '', array $options = []) { // TODO: Implement makeDataFromString() method. } public function makeStringFromData(array $data = [], array $options = []) { if (count($data) !== 9) { throw new \Exception("Invalid data array. Needs to contain 9 bytes"); } $flags = $data[0]; $isNegative = ($flags >> 7 === 1); // $isUndef = ($flags & 1 === 1); // if true, "used for initial sequence values" $exponent = $data[1] - 0x80; $number = ''; for ($i = 2; $i < 8; $i++) { $number .= dechex($data[$i]); } $number = substr($number, 0, 1) . '.' . substr($number, 1); $number = ($isNegative ? -1 : 1) * pow(10, $exponent) * ((float)$number); return (string)$number; } }
Install requirements now include SciPy. Used in the operators subpackage, and will likely be used elsewhere due to the sparse package being inside scipy.
from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) def readme(): with open('README.pandoc') as f: return f.read() setup( name = 'pyop' , version = '0.0.1' , description = 'Matrix free linear transformations' , long_description = readme() , keywords = [ 'Linear Algebra', 'Linear Transformations'] , author = 'Daniel Hensley and Ryan Orendorff' , author_email = '[email protected]' , license = 'BSD' , classifiers = [ 'Development Status :: 1 - Planning' , 'Intended Audience :: Science/Research' , 'License :: OSI Approved :: BSD License' , 'Programming Language :: Python' , 'Topic :: Scientific/Engineering :: Mathematics' , 'Topic :: Software Development :: Libraries :: Python Modules' ] , packages = ['pyop'] , install_requires = [ 'six >= 1.6' , 'numpy >= 1.8' , 'scipy >= 0.14.0' ] , zip_safe = False , tests_require = ['pytest'] , cmdclass = {'test': PyTest} )
from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) def readme(): with open('README.pandoc') as f: return f.read() setup( name = 'pyop' , version = '0.0.1' , description = 'Matrix free linear transformations' , long_description = readme() , keywords = [ 'Linear Algebra', 'Linear Transformations'] , author = 'Daniel Hensley and Ryan Orendorff' , author_email = '[email protected]' , license = 'BSD' , classifiers = [ 'Development Status :: 1 - Planning' , 'Intended Audience :: Science/Research' , 'License :: OSI Approved :: BSD License' , 'Programming Language :: Python' , 'Topic :: Scientific/Engineering :: Mathematics' , 'Topic :: Software Development :: Libraries :: Python Modules' ] , packages = ['pyop'] , install_requires = ['six >= 1.6', 'numpy >= 1.8'] , zip_safe = False , tests_require = ['pytest'] , cmdclass = {'test': PyTest} )
[BUGFIX] Make shuffle() a non-final operation Change-Id: I675ee102d9f799c023c07f7abcbf839b48656429 Releases: master Reviewed-on: https://review.typo3.org/27584 Reviewed-by: Karsten Dambekalns Tested-by: Karsten Dambekalns Reviewed-by: Christopher Hlubek Original-Commit-Hash: cdc83573e41778089143dc5cdb2413b825e9c200
<?php namespace TYPO3\Eel\FlowQuery\Operations; /* * * This script belongs to the TYPO3 Flow package "TYPO3.Eel". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Eel\FlowQuery\FlowQuery; use TYPO3\Flow\Annotations as Flow; /** * Get a random element index from the context. * * This operation randomizes the order of elements contained * in the context. */ class ShuffleOperation extends AbstractOperation { /** * {@inheritdoc} * * @var string */ static protected $shortName = 'shuffle'; /** * {@inheritdoc} * * @param FlowQuery $flowQuery the FlowQuery object * @param array $arguments the arguments for this operation * @return mixed */ public function evaluate(FlowQuery $flowQuery, array $arguments) { $context = $flowQuery->getContext(); if (count($context) > 0) { shuffle($context); $flowQuery->setContext($context); } } }
<?php namespace TYPO3\Eel\FlowQuery\Operations; /* * * This script belongs to the TYPO3 Flow package "TYPO3.Eel". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Eel\FlowQuery\FlowQuery; use TYPO3\Flow\Annotations as Flow; /** * Get a random element index from the context. * * This operation randomizes the order of elements contained * in the context. */ class ShuffleOperation extends AbstractOperation { /** * {@inheritdoc} * * @var string */ static protected $shortName = 'shuffle'; /** * {@inheritdoc} * * @var boolean */ static protected $final = TRUE; /** * {@inheritdoc} * * @param FlowQuery $flowQuery the FlowQuery object * @param array $arguments the arguments for this operation * @return mixed */ public function evaluate(FlowQuery $flowQuery, array $arguments) { $context = $flowQuery->getContext(); if (count($context) > 0) { shuffle($context); $flowQuery->setContext($context); } } }
Change isinstance check to duck typing because this is Python lol
from discord.ext.commands import Bot, CommandInvokeError from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument class BeattieBot(Bot): async def reply(self, ctx, message): return await ctx.send(f'{ctx.message.author.mention}\n{message}') async def handle_error(self, exception, ctx): if isinstance(exception, MissingRequiredArgument): await ctx.send('Missing required arguments.') elif not isinstance(exception, CommandNotFound): await ctx.send('Generic error handler triggered. ' 'This should never happen.') try: raise exception.original except AttributeError: raise exception async def on_ready(self): print('Logged in as') print(self.user.name) print(self.user.id) print('------') async def on_message(self, message): msg = message.content.split(None, 1) msg[0] = msg[0].lower() message.content = ' '.join(msg) await self.process_commands(message) async def on_command_error(self, exception, ctx): if ctx.command is None or not hasattr(ctx.command, 'on_error'): await self.handle_error(exception, ctx)
from discord.ext.commands import Bot, CommandInvokeError from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument class BeattieBot(Bot): async def reply(self, ctx, message): return await ctx.send(f'{ctx.message.author.mention}\n{message}') async def handle_error(self, exception, ctx): if isinstance(exception, MissingRequiredArgument): await ctx.send('Missing required arguments.') elif not isinstance(exception, CommandNotFound): await ctx.send('Generic error handler triggered. ' 'This should never happen.') if isinstance(exception, CommandInvokeError): exception = exception.original raise exception async def on_ready(self): print('Logged in as') print(self.user.name) print(self.user.id) print('------') async def on_message(self, message): msg = message.content.split(None, 1) msg[0] = msg[0].lower() message.content = ' '.join(msg) await self.process_commands(message) async def on_command_error(self, exception, ctx): if ctx.command is None or not hasattr(ctx.command, 'on_error'): await self.handle_error(exception, ctx)
Use singular for project, visualization directories.
TileMill.controller.list = function() { TileMill.backend.list('project', function(projects) { TileMill.backend.list('visualization', function(visualizations) { var page = $(TileMill.template('list', { projects: TileMill.template('column', { 'name': 'Projects', 'type': 'project', 'data': projects }), visualizations: TileMill.template('column', { 'name': 'Visualizations', 'type': 'visualization', 'data': visualizations }), })); $('input[type=submit]', page).bind('click', function() { if ($(this).is('.ajaxing')) { return; } $(this).addClass('ajaxing'); var type = $(this).parents('form').attr('id'), name = $(this).parents('form').find('.text').val(), self = this; if (!name) { TileMill.popup.show({ title: 'Error', content: 'Name field is required.' }); return false; } TileMill.backend.servers.python.add(name, type, function(data) { if (data.status) { console.log('success'); } else { TileMill.popup.show({ title: 'Error', content: data.message }); } $(self).removeClass('ajaxing'); }) return false; }); TileMill.show(page); }); }); }
TileMill.controller.list = function() { TileMill.backend.list('projects', function(projects) { TileMill.backend.list('visualizations', function(visualizations) { var page = $(TileMill.template('list', { projects: TileMill.template('column', { 'name': 'Projects', 'type': 'project', 'data': projects }), visualizations: TileMill.template('column', { 'name': 'Visualizations', 'type': 'visualization', 'data': visualizations }), })); $('input[type=submit]', page).bind('click', function() { if ($(this).is('.ajaxing')) { return; } $(this).addClass('ajaxing'); var type = $(this).parents('form').attr('id'), name = $(this).parents('form').find('.text').val(), self = this; if (!name) { TileMill.popup.show({ title: 'Error', content: 'Name field is required.' }); return false; } TileMill.backend.servers.python.add(name, type, function(data) { if (data.status) { console.log('success'); } else { TileMill.popup.show({ title: 'Error', content: data.message }); } $(self).removeClass('ajaxing'); }) return false; }); TileMill.show(page); }); }); }
Add a secrets file in rnac notify Nextflow doesn't propagate environment variables from the profile into the event handler closures. This is the simplest workaround for that. secrets.py should be on the cluster and symlinked into rnacentral_pipeline
""" Send a notification to slack. NB: The webhook should be configured in the nextflow profile """ import os import requests def send_notification(title, message, plain=False): """ Send a notification to the configured slack webhook. """ SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK') if SLACK_WEBHOOK is None: try: from rnacentral_pipeline.secrets import SLACK_WEBHOOK except: raise SystemExit("SLACK_WEBHOOK environment variable not defined, and couldn't find a secrets file") if plain: slack_json = { "text" : title + ': ' + message } else: slack_json = { "text" : title, "blocks" : [ { "type": "section", "text": { "type": "mrkdwn", "text": message }, }, ] } try: response = requests.post(SLACK_WEBHOOK, json=slack_json, headers={'Content-Type':'application/json'} ) response.raise_for_status() except Exception as request_exception: raise SystemExit from request_exception
""" Send a notification to slack. NB: The webhook should be configured in the nextflow profile """ import os import requests def send_notification(title, message, plain=False): """ Send a notification to the configured slack webhook. """ SLACK_WEBHOOK = os.getenv('SLACK_WEBHOOK') if SLACK_WEBHOOK is None: raise SystemExit("SLACK_WEBHOOK environment variable not defined") if plain: slack_json = { "text" : title + ': ' + message } else: slack_json = { "text" : title, "blocks" : [ { "type": "section", "text": { "type": "mrkdwn", "text": message }, }, ] } try: response = requests.post(SLACK_WEBHOOK, json=slack_json, headers={'Content-Type':'application/json'} ) response.raise_for_status() except Exception as request_exception: raise SystemExit from request_exception
Correct french translation module documents
/* eslint-disable no-undef */ import { Bert } from 'meteor/themeteorchef:bert'; import { upsertDocument } from '/imports/api/documents/methods'; import '/imports/lib/validation'; let component; const handleUpsert = () => { const { doc, history } = component.props; const confirmation = doc && doc._id ? 'Document mis à jour !' : 'Document ajouté !'; const upsert = { title: document.querySelector('[name="title"]').value.trim(), body: document.querySelector('[name="body"]').value.trim(), }; if (doc && doc._id) upsert._id = doc._id; upsertDocument.call(upsert, (error, response) => { if (error) { Bert.alert(error.reason, 'danger'); } else { component.documentEditorForm.reset(); Bert.alert(confirmation, 'success'); history.push(`/documents/${response.insertedId || doc._id}`); } }); }; const validate = () => { $(component.documentEditorForm).validate({ rules: { title: { required: true, }, body: { required: true, }, }, messages: { title: { required: 'Le titre est requis', }, body: { required: 'Le corp est requis', }, }, submitHandler() { handleUpsert(); }, }); }; export default function documentEditor(options) { component = options.component; validate(); }
/* eslint-disable no-undef */ import { Bert } from 'meteor/themeteorchef:bert'; import { upsertDocument } from '/imports/api/documents/methods'; import '/imports/lib/validation'; let component; const handleUpsert = () => { const { doc, history } = component.props; const confirmation = doc && doc._id ? 'Document mise à jour !' : 'Document ajouté !'; const upsert = { title: document.querySelector('[name="title"]').value.trim(), body: document.querySelector('[name="body"]').value.trim(), }; if (doc && doc._id) upsert._id = doc._id; upsertDocument.call(upsert, (error, response) => { if (error) { Bert.alert(error.reason, 'danger'); } else { component.documentEditorForm.reset(); Bert.alert(confirmation, 'success'); history.push(`/documents/${response.insertedId || doc._id}`); } }); }; const validate = () => { $(component.documentEditorForm).validate({ rules: { title: { required: true, }, body: { required: true, }, }, messages: { title: { required: 'Le titre est requis', }, body: { required: 'Le corp est requis', }, }, submitHandler() { handleUpsert(); }, }); }; export default function documentEditor(options) { component = options.component; validate(); }
Update to Silverstripe 3.1.7 Included BootstrapLoadingFormAction for Submit Buttons
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class BootstrapNavbarLanguageForm extends Form { public function __construct($controller, $name, $fields = null, $actions = null) { $Laguages = array(); foreach(LocaleGeoip::get_available_languages() as $Locale => $Language){ $Languages[$Locale] = _t('BootstrapNavbarLanguageForm.'.$Language, $Language); } // Create fields $fields = new FieldList( $locale = new DropdownField('Locale', "", $Languages, i18n::get_locale()) ); if(self::config()->submitOnChange) $locale->setAttribute('onchange', 'this.form.submit();'); //$locale->addExtraClass('col-md-2'); // Create actions $actions = new FieldList( $submit = new BootstrapLoadingFormAction('updateLang', _t('BootstrapNavbarLanguageForm.SUBMIT','BootstrapNavbarLanguageForm.SUBMIT')) ); $submit->addExtraClass('btn btn-default'); parent::__construct( $controller, $name, $fields, $actions ); } public function updateLang(array $data){ if($o_Member = Member::currentUser()) { $o_Member->Locale = $data['Locale']; $o_Member->write(); } i18n::set_locale($data['Locale']); Session::set('Locale', $data['Locale']); Controller::curr()->redirectBack(); } }
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class BootstrapNavbarLanguageForm extends Form { public function __construct($controller, $name, $fields = null, $actions = null) { $Laguages = array(); foreach(LocaleGeoip::get_available_languages() as $Locale => $Language){ $Languages[$Locale] = _t('BootstrapNavbarLanguageForm.'.$Language, $Language); } // Create fields $fields = new FieldList( $locale = new DropdownField('Locale', "", $Languages, i18n::get_locale()) ); if(self::config()->submitOnChange) $locale->setAttribute('onchange', 'this.form.submit();'); //$locale->addExtraClass('col-md-2'); // Create actions $actions = new FieldList( $submit = new FormAction('updateLang', _t('BootstrapNavbarLanguageForm.SUBMIT','BootstrapNavbarLanguageForm.SUBMIT')) ); $submit->addExtraClass('btn btn-default'); parent::__construct( $controller, $name, $fields, $actions ); } public function updateLang(array $data){ if($o_Member = Member::currentUser()) { $o_Member->Locale = $data['Locale']; $o_Member->write(); } i18n::set_locale($data['Locale']); Session::set('Locale', $data['Locale']); Controller::curr()->redirectBack(); } }
Clean up main context class
<?php use Behat\Behat\Context\Context; use Illuminate\Foundation\Testing\DatabaseMigrations; use Tests\TestCase; use Zeropingheroes\Lanager\Console\Kernel; use Zeropingheroes\Lanager\User; use Zeropingheroes\Lanager\UserOAuthAccount; /** * Defines application features from the specific context. */ class FeatureContext extends TestCase implements Context { use DatabaseMigrations; /** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. */ public function __construct() { parent::setUp(); $this->artisan('db:seed'); $this->app[Kernel::class]->setArtisan(null); } /** * @Given an admin with username :username exists */ public function anAdminWithUsernameExists($username) { $user = factory(User::class)->create( [ 'username' => $username, ] )->each( function ($user) { $user->accounts()->save(factory(UserOAuthAccount::class)->make()); } ); // Currently not required as UserObserver::class assigns super admin role when first user created // $role = Role::where('name', 'super-admin')->first(); // $user->roles()->attach($role->id, ['assigned_by' => $user->id]); } }
<?php use Behat\Behat\Context\Context; use Behat\Behat\Hook\Scope\BeforeScenarioScope; use Illuminate\Foundation\Testing\DatabaseMigrations; use Tests\TestCase; use Zeropingheroes\Lanager\Console\Kernel; use Zeropingheroes\Lanager\User; use Zeropingheroes\Lanager\UserOAuthAccount; /** * Defines application features from the specific context. */ class FeatureContext extends TestCase implements Context { use DatabaseMigrations; /** * @var Session */ private $session; /** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. */ public function __construct() { parent::setUp(); } /** @BeforeScenario */ public function before(BeforeScenarioScope $scope) { $this->artisan('db:seed'); $this->app[Kernel::class]->setArtisan(null); } /** * @Given an admin with username :username exists */ public function anAdminWithUsernameExists($username) { $user = factory(User::class)->create( [ 'username' => $username, ] )->each( function ($user) { $user->accounts()->save(factory(UserOAuthAccount::class)->make()); } ); // Currently not required as UserObserver::class assigns super admin role when first user created // $role = Role::where('name', 'super-admin')->first(); // $user->roles()->attach($role->id, ['assigned_by' => $user->id]); } }
Remove 'field' and 'icon' from column list
from Products.CMFCore.utils import getToolByName from Products.bika import logger from Products.bika.browser.bika_folder_contents import BikaFolderContentsView from plone.app.content.browser.interfaces import IFolderContentsView from zope.interface import implements class ClientFolderContentsView(BikaFolderContentsView): implements(IFolderContentsView) contentFilter = {'portal_type': 'Client'} content_add_buttons = ['Client', ] batch = True b_size = 100 show_editable_border = False columns = { 'title_or_id': {'title': 'Name'}, 'getEmailAddress': {'title': 'Email Address'}, 'getPhone': {'title': 'Phone'}, 'getFax': {'title': 'Fax'}, } wflist_states = [ {'title': 'All', 'id':'all', 'columns':['title_or_id', 'getEmailAddress', 'getPhone', 'getFax', ], 'buttons':[BikaFolderContentsView.default_buttons['delete']]}, ] def folderitems(self): items = BikaFolderContentsView.folderitems(self) for x in range(len(items)): items[x]['links'] = {'title_or_id': items[x]['url']} return items def __call__(self): return self.template()
from Products.CMFCore.utils import getToolByName from Products.bika import logger from Products.bika.browser.bika_folder_contents import BikaFolderContentsView from plone.app.content.browser.interfaces import IFolderContentsView from zope.interface import implements class ClientFolderContentsView(BikaFolderContentsView): implements(IFolderContentsView) contentFilter = {'portal_type': 'Client'} content_add_buttons = ['Client', ] batch = True b_size = 100 show_editable_border = False columns = { 'title_or_id': {'title': 'Name', 'field': 'title_or_id', 'icon': 'client.png'}, 'getEmailAddress': {'title': 'Email Address', 'field':'getEmailAddress'}, 'getPhone': {'title': 'Phone', 'field':'getPhone'}, 'getFax': {'title': 'Fax', 'field':'getFax'}, } wflist_states = [ {'title': 'All', 'id':'all', 'columns':['title_or_id', 'getEmailAddress', 'getPhone', 'getFax', ], 'buttons':[BikaFolderContentsView.default_buttons['delete']]}, ] def folderitems(self): items = BikaFolderContentsView.folderitems(self) for x in range(len(items)): items[x]['links'] = {'title_or_id': items[x]['url']} return items def __call__(self): return self.template()
Convert atomno to int in case it is a different numpy dtype.
""" cclib (http://cclib.sf.net) is (c) 2006, the cclib development team and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html). """ __revision__ = "$Revision$" import openbabel as ob def makeopenbabel(atomcoords, atomnos, charge=0, mult=1): """Create an Open Babel molecule. >>> import numpy, openbabel >>> atomnos = numpy.array([1,8,1],"i") >>> coords = numpy.array([[-1.,1.,0.],[0.,0.,0.],[1.,1.,0.]]) >>> obmol = makeopenbabel(coords, atomnos) >>> obconversion = openbabel.OBConversion() >>> formatok = obconversion.SetOutFormat("inchi") >>> print obconversion.WriteString(obmol).strip() InChI=1/H2O/h1H2 """ obmol = ob.OBMol() for i in range(len(atomnos)): # Note that list(atomcoords[i]) is not equivalent!!! coords = atomcoords[i].tolist() atomno = int(atomnos[i]) obatom = ob.OBAtom() obatom.SetAtomicNum(atomno) obatom.SetVector(*coords) obmol.AddAtom(obatom) obmol.ConnectTheDots() obmol.PerceiveBondOrders() obmol.SetTotalSpinMultiplicity(mult) obmol.SetTotalCharge(charge) return obmol if __name__ == "__main__": import doctest doctest.testmod()
""" cclib (http://cclib.sf.net) is (c) 2006, the cclib development team and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html). """ __revision__ = "$Revision$" import openbabel as ob def makeopenbabel(atomcoords, atomnos, charge=0, mult=1): """Create an Open Babel molecule. >>> import numpy, openbabel >>> atomnos = numpy.array([1,8,1],"i") >>> coords = numpy.array([[-1.,1.,0.],[0.,0.,0.],[1.,1.,0.]]) >>> obmol = makeopenbabel(coords, atomnos) >>> obconversion = openbabel.OBConversion() >>> formatok = obconversion.SetOutFormat("inchi") >>> print obconversion.WriteString(obmol).strip() InChI=1/H2O/h1H2 """ obmol = ob.OBMol() for i in range(len(atomnos)): # Note that list(atomcoords[i]) is not equivalent!!! coords = atomcoords[i].tolist() atomno = atomnos[i] obatom = ob.OBAtom() obatom.SetAtomicNum(atomno) obatom.SetVector(*coords) obmol.AddAtom(obatom) obmol.ConnectTheDots() obmol.PerceiveBondOrders() obmol.SetTotalSpinMultiplicity(mult) obmol.SetTotalCharge(charge) return obmol if __name__ == "__main__": import doctest doctest.testmod()
Remove support for end-of-life Python 3.6 in next release Checked again just now and we are still waiting on Python 3.10 stability
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import find_packages, setup with open("README.md") as readme_file: readme = readme_file.read() requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"] setup( author="Ryan Gibson", author_email="[email protected]", name="stego_lsb", version="1.3.1", description="stego lsb", keywords="stego lsb", license="MIT", long_description=readme, long_description_content_type="text/markdown", url="https://github.com/ragibson/Steganography", install_requires=requirements, entry_points=""" [console_scripts] stegolsb=stego_lsb.cli:main """, include_package_data=True, packages=find_packages(include=["stego_lsb"]), zip_safe=False, python_requires=">=3.7", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3 :: Only", ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import find_packages, setup with open("README.md") as readme_file: readme = readme_file.read() requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"] setup( author="Ryan Gibson", author_email="[email protected]", name="stego_lsb", version="1.3.1", description="stego lsb", keywords="stego lsb", license="MIT", long_description=readme, long_description_content_type="text/markdown", url="https://github.com/ragibson/Steganography", install_requires=requirements, entry_points=""" [console_scripts] stegolsb=stego_lsb.cli:main """, include_package_data=True, packages=find_packages(include=["stego_lsb"]), zip_safe=False, python_requires=">=3.6", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3 :: Only", ], )
Introduce scope_types in migrate server oslo.policy introduced the scope_type feature which can control the access level at system-level and project-level. - https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope - http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/system-scope.html Appropriate scope_type for nova case: - https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope This commit introduce scope_type for migrate server API policies as 'system'. Also adds the test case with scope_type enabled and verify we pass and fail the policy check with expected context. Partial implement blueprint policy-defaults-refresh Change-Id: Icba4c14f240215fd56f1cdd9814cc81ebf2796be
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base POLICY_ROOT = 'os_compute_api:os-migrate-server:%s' migrate_server_policies = [ policy.DocumentedRuleDefault( name=POLICY_ROOT % 'migrate', check_str=base.RULE_ADMIN_API, description="Cold migrate a server to a host", operations=[ { 'method': 'POST', 'path': '/servers/{server_id}/action (migrate)' } ], scope_types=['system', 'project']), policy.DocumentedRuleDefault( name=POLICY_ROOT % 'migrate_live', check_str=base.RULE_ADMIN_API, description="Live migrate a server to a new host without a reboot", operations=[ { 'method': 'POST', 'path': '/servers/{server_id}/action (os-migrateLive)' } ], scope_types=['system', 'project']), ] def list_rules(): return migrate_server_policies
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base POLICY_ROOT = 'os_compute_api:os-migrate-server:%s' migrate_server_policies = [ policy.DocumentedRuleDefault( POLICY_ROOT % 'migrate', base.RULE_ADMIN_API, "Cold migrate a server to a host", [ { 'method': 'POST', 'path': '/servers/{server_id}/action (migrate)' } ]), policy.DocumentedRuleDefault( POLICY_ROOT % 'migrate_live', base.RULE_ADMIN_API, "Live migrate a server to a new host without a reboot", [ { 'method': 'POST', 'path': '/servers/{server_id}/action (os-migrateLive)' } ]), ] def list_rules(): return migrate_server_policies
Use the mint database for capsule data
# # Copyright (c) 2009 rPath, Inc. # # All Rights Reserved # from conary.lib import util from mint.rest.db import manager import rpath_capsule_indexer class CapsuleManager(manager.Manager): def getIndexerConfig(self): capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules') cfg = rpath_capsule_indexer.IndexerConfig() dbDriver = self.db.db.driver dbConnectString = self.db.db.db.database cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString)) cfg.configLine("indexDir %s/packages" % capsuleDataDir) cfg.configLine("systemsPath %s/systems" % capsuleDataDir) dataSources = self.db.platformMgr.listPlatformSources().platformSource # XXX we only deal with RHN for now if dataSources: cfg.configLine("user RHN %s %s" % (dataSources[0].username, dataSources[0].password)) # XXX channels are hardcoded for now cfg.configLine("channels rhel-i386-as-4") cfg.configLine("channels rhel-x86_64-as-4") cfg.configLine("channels rhel-i386-server-5") cfg.configLine("channels rhel-x86_64-server-5") util.mkdirChain(capsuleDataDir) return cfg def getIndexer(self): cfg = self.getIndexerConfig() return rpath_capsule_indexer.Indexer(cfg)
# # Copyright (c) 2009 rPath, Inc. # # All Rights Reserved # from conary.lib import util from mint.rest.db import manager import rpath_capsule_indexer class CapsuleManager(manager.Manager): def getIndexerConfig(self): capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules') cfg = rpath_capsule_indexer.IndexerConfig() cfg.configLine("store sqlite:///%s/database.sqlite" % capsuleDataDir) cfg.configLine("indexDir %s/packages" % capsuleDataDir) cfg.configLine("systemsPath %s/systems" % capsuleDataDir) dataSources = self.db.platformMgr.listPlatformSources().platformSource # XXX we only deal with RHN for now if dataSources: cfg.configLine("user RHN %s %s" % (dataSources[0].username, dataSources[0].password)) # XXX channels are hardcoded for now cfg.configLine("channels rhel-i386-as-4") cfg.configLine("channels rhel-x86_64-as-4") cfg.configLine("channels rhel-i386-server-5") cfg.configLine("channels rhel-x86_64-server-5") util.mkdirChain(capsuleDataDir) return cfg def getIndexer(self): cfg = self.getIndexerConfig() return rpath_capsule_indexer.Indexer(cfg)
Fix for IE + Edge
'use strict'; (function (document) { document.addEventListener('DOMContentLoaded', function () { const details = document.getElementsByTagName('details'); if (details.length <= 0 || typeof details[0].open === 'boolean') { return; } document.documentElement.setAttribute('data-shim-details', 'true'); Array.prototype.forEach.call(details, function (item) { // Define open property Object.defineProperty(item, 'open', { get: function () { return this.hasAttribute('open'); }, set: function (state) { if (state) { this.setAttribute('open', ''); } else { this.removeAttribute('open'); } } }); // Summary element let summary = item.firstElementChild; if (!summary || summary.tagName.toLowerCase() !== 'summary') { summary = document.createElement('summary'); summary.innerText = 'Summary'; item.insertBefore(summary, item.firstChild); } summary.addEventListener('click', function () { this.parentNode.open = !this.parentNode.hasAttribute('open'); }); // Wrap text nodes let b = 0; let child; while (child = item.childNodes[b++]) { if (child.nodeType === 3 && /[^\t\n\r ]/.test(child.data)) { let span = document.createElement('span'); item.insertBefore(span, child); span.textContent = child.data; item.removeChild(child); } } }); }); })(document, window);
'use strict'; (function (document) { document.addEventListener('DOMContentLoaded', function () { const details = document.getElementsByTagName('details'); if (details.length <= 0 || typeof details[0].open === 'boolean') { return; } document.documentElement.setAttribute('data-shim-details', 'true'); Array.prototype.forEach.call(details, function (item) { // Define open property Object.defineProperty(item, 'open', { get: function () { return this.hasAttribute('open'); }, set: function (state) { if (state) { this.setAttribute('open', ''); } else { this.removeAttribute('open'); } } }); // Summary element let summary = item.firstChild; if (!summary || summary.tagName.toLowerCase() !== 'summary') { summary = document.createElement('summary'); summary.innerText = 'Summary'; item.insertBefore(summary, item.firstChild); } summary.addEventListener('click', function () { this.parentNode.open = !this.parentNode.hasAttribute('open'); }); // Wrap text nodes let b = 0; let child; while (child = item.childNodes[b++]) { if (child.nodeType === 3 && /[^\t\n\r ]/.test(child.data)) { let span = document.createElement('span'); item.insertBefore(span, child); span.textContent = child.data; item.removeChild(child); } } }); }); })(document, window);
Add credit where credit is due
<?php namespace Modules\Menu\Support; use Illuminate\Database\Eloquent\Collection; /** * Class NestedCollection * Credit: TypiCMS - https://github.com/sdebacker/TypiCMS/blob/master/app/TypiCMS/NestableCollection.php * * @package Modules\Menu\Support */ class NestedCollection extends Collection { private $total = 0; public function __construct(array $items = array()) { parent::__construct($items); $this->total = count($items); } /** * Nest items * * @return NestedCollection */ public function nest() { // Set id as keys $this->items = $this->getDictionary($this); // Set children $deleteArray = array(); foreach ($this->items as $item) { if ($item->parent_id && isset($this->items[$item->parent_id])) { if ( ! $this->items[$item->parent_id]->children) { $this->items[$item->parent_id]->children = new \Illuminate\Support\Collection; } $this->items[$item->parent_id]->children->put($item->id, $item); $deleteArray[] = $item->id; } } // Delete moved items $this->items = array_except($this->items, $deleteArray); return $this; } /** * Get total items in nested collection * * @return int */ public function getTotal() { return $this->total; } }
<?php namespace Modules\Menu\Support; use Illuminate\Database\Eloquent\Collection; class NestedCollection extends Collection { private $total = 0; public function __construct(array $items = array()) { parent::__construct($items); $this->total = count($items); } /** * Nest items * * @return NestedCollection */ public function nest() { // Set id as keys $this->items = $this->getDictionary($this); // Set children $deleteArray = array(); foreach ($this->items as $item) { if ($item->parent_id && isset($this->items[$item->parent_id])) { if ( ! $this->items[$item->parent_id]->children) { $this->items[$item->parent_id]->children = new \Illuminate\Support\Collection; } $this->items[$item->parent_id]->children->put($item->id, $item); $deleteArray[] = $item->id; } } // Delete moved items $this->items = array_except($this->items, $deleteArray); return $this; } /** * Get total items in nested collection * * @return int */ public function getTotal() { return $this->total; } }
Make sure to keep the property 'name'
'use strict'; const _ = require('underscore'); function buildSlots(slots) { const res = {}; _.each(slots, (value, key) => { if ( _.isString(value)) { res[key] = { name: key, value: value }; } else { res[key] = { ...value, name: key }; } }); return res; } function buildSession(e) { return e ? e.sessionAttributes : {}; } function init(options) { let isNew = true; // public API const api = { init, build }; function build(intentName, slots, prevEvent) { if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request'); const res = { // override more stuff later as we need session: { sessionId: options.sessionId, application: { applicationId: options.appId }, attributes: buildSession(prevEvent), user: { userId: options.userId, accessToken: options.accessToken }, new: isNew }, request: { type: 'IntentRequest', requestId: options.requestId, locale: options.locale, timestamp: (new Date()).toISOString(), intent: { name: intentName, slots: buildSlots(slots) } }, version: '1.0' }; isNew = false; return res; } return api; } module.exports = {init};
'use strict'; const _ = require('underscore'); function buildSlots(slots) { const res = {}; _.each(slots, (value, key) => { if ( _.isString(value)) { res[key] = { name: key, value: value }; } else { res[key] = { name: key, ...value }; } }); return res; } function buildSession(e) { return e ? e.sessionAttributes : {}; } function init(options) { let isNew = true; // public API const api = { init, build }; function build(intentName, slots, prevEvent) { if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request'); const res = { // override more stuff later as we need session: { sessionId: options.sessionId, application: { applicationId: options.appId }, attributes: buildSession(prevEvent), user: { userId: options.userId, accessToken: options.accessToken }, new: isNew }, request: { type: 'IntentRequest', requestId: options.requestId, locale: options.locale, timestamp: (new Date()).toISOString(), intent: { name: intentName, slots: buildSlots(slots) } }, version: '1.0' }; isNew = false; return res; } return api; } module.exports = {init};
Make Room.getLOIs clone this.memory.sources instead of a directly using it
SetupPrototypes(); SetupRooms(); SpawnCreeps(); HandleCreeps(); EndTick(); function SetupPrototypes() { Room.prototype.getLOIs = function() { var lois = []; this.memory.sources.forEach(function(sourceId) { lois.push(sourceId); }); if(this.controller) { lois.push(this.controller.id); } return lois; }; } function SetupRooms() { Object.keys(Game.rooms).forEach(function (roomName) { var room = Game.rooms[roomName]; if (!room.memory.calcComplete || Memory.recalcRooms) { // Do one time room calculations here if(!room.memory.sources) { room.memory.sources = room.find(FIND_SOURCES).map(function (sourceObject) { return sourceObject.id; }); } room.memory.calcComplete = true; } }); } function SpawnCreeps() { if(Object.keys(Game.creeps).length < 4) { // Spawn a new creep } } function HandleCreeps() { Object.keys(Game.creeps).forEach(function (creepName) { var creep = Game.creeps[creepName]; if(creep.carry.energy < creep.carryCapacity) { // Move to source or harvest } else { // Move to spawn or transfer } }); } function EndTick() { Memory.recalcRooms = false; console.log(Game.getUsedCpu()); }
SetupPrototypes(); SetupRooms(); SpawnCreeps(); HandleCreeps(); EndTick(); function SetupPrototypes() { Room.prototype.getLOIs = function() { var lois = this.memory.sources || []; // Need to clone that if(this.controller) { lois.push(this.controller.id); } return lois; }; } function SetupRooms() { Object.keys(Game.rooms).forEach(function (roomName) { var room = Game.rooms[roomName]; if (!room.memory.calcComplete || Memory.recalcRooms) { // Do one time room calculations here if(!room.memory.sources) { room.memory.sources = room.find(FIND_SOURCES).map(function (sourceObject) { return sourceObject.id; }); } room.memory.calcComplete = true; } }); } function SpawnCreeps() { if(Object.keys(Game.creeps).length < 4) { // Spawn a new creep } } function HandleCreeps() { Object.keys(Game.creeps).forEach(function (creepName) { var creep = Game.creeps[creepName]; if(creep.carry.energy < creep.carryCapacity) { // Move to source or harvest } else { // Move to spawn or transfer } }); } function EndTick() { Memory.recalcRooms = false; console.log(Game.getUsedCpu()); }
Set default zIndex to 10000
/** * @name jquery-steamytext * @version 1.1.0 * @description jQuery SteamyText animation plugin * @author Maxim Zalysin <[email protected]> */ (function($){ $.fn.steamyText = function(data){ var defaults = { text: '', duration: 1500, displace: 50, tag: 'span', zIndex: 10000 } , options switch(typeof data){ case 'string': defaults.text = data options = defaults break case 'object': if(data === null) return this options = $.extend({}, defaults, data) break default: return this } var $text = $('<'+options.tag+' style="position: absolute; z-index: '+options.zIndex+'; display: none;">'+options.text+'</'+options.tag+'>').appendTo('body') , textWidth = $text.outerWidth() , thisWidth = this.outerWidth() , thisOffset = this.offset() , thisOffsetLeft if(thisWidth > textWidth) thisOffsetLeft = thisOffset.left + ((thisWidth - textWidth)/2) else thisOffsetLeft = thisOffset.left - ((textWidth - thisWidth)/2) $text.css({'top': thisOffset.top, 'left': thisOffsetLeft}).show() .animate({top: '-='+options.displace+'px', opacity: 'toggle'}, options.duration, function(){ /*$(this).remove()*/ }) return this } }(jQuery))
/** * @name jquery-steamytext * @version 1.0.0 * @description jQuery SteamyText animation plugin * @author Maxim Zalysin <[email protected]> */ (function($){ $.fn.steamyText = function(data){ var defaults = { text: '' , duration: 1500 , displace: 50 , tag: 'span' , zIndex: 0 } , options switch(typeof data){ case 'string': defaults.text = data options = defaults break case 'object': if(data === null) return this options = $.extend({}, defaults, data) break default: return this } var $text = $('<'+options.tag+' style="position: absolute; z-index: '+options.zIndex+'; display: none;">'+options.text+'</'+options.tag+'>').appendTo('body') , textWidth = $text.outerWidth() , thisWidth = this.outerWidth() , thisOffset = this.offset() , thisOffsetLeft if(thisWidth > textWidth) thisOffsetLeft = thisOffset.left + ((thisWidth - textWidth)/2) else thisOffsetLeft = thisOffset.left - ((textWidth - thisWidth)/2) $text.css({'top': thisOffset.top, 'left': thisOffsetLeft}).show() .animate({top: '-='+options.displace+'px', opacity: 'toggle'}, options.duration, function(){ /*$(this).remove()*/ }) return this } }(jQuery))
Fix viewBox pre condition warning
const meetOrSliceTypes = { meet: 0, slice: 1, none: 2, }; const alignEnum = [ "xMinYMin", "xMidYMin", "xMaxYMin", "xMinYMid", "xMidYMid", "xMaxYMid", "xMinYMax", "xMidYMax", "xMaxYMax", "none", ].reduce((prev, name) => { prev[name] = name; return prev; }, {}); const spacesRegExp = /\s+/; export default function(props) { const { viewBox, preserveAspectRatio } = props; if (!viewBox) { return null; } const params = viewBox .trim() .split(spacesRegExp) .map(Number); if (params.length !== 4 || params.some(isNaN)) { console.warn("Invalid `viewBox` prop:" + viewBox); return null; } const modes = preserveAspectRatio ? preserveAspectRatio.trim().split(spacesRegExp) : []; const meetOrSlice = meetOrSliceTypes[modes[1]] || 0; const align = alignEnum[modes[0]] || "xMidYMid"; const [minX, minY, vbWidth, vbHeight] = params; return { minX, minY, vbWidth, vbHeight, align, meetOrSlice, }; } export { meetOrSliceTypes, alignEnum };
const meetOrSliceTypes = { meet: 0, slice: 1, none: 2, }; const alignEnum = [ "xMinYMin", "xMidYMin", "xMaxYMin", "xMinYMid", "xMidYMid", "xMaxYMid", "xMinYMax", "xMidYMax", "xMaxYMax", "none", ].reduce((prev, name) => { prev[name] = name; return prev; }, {}); const spacesRegExp = /\s+/; export default function(props) { const { viewBox, preserveAspectRatio } = props; if (!viewBox) { return null; } const params = viewBox .trim() .split(spacesRegExp) .map(Number); if (params.length === 4 && params.some(isNaN)) { console.warn("Invalid `viewBox` prop:" + viewBox); return null; } const modes = preserveAspectRatio ? preserveAspectRatio.trim().split(spacesRegExp) : []; const meetOrSlice = meetOrSliceTypes[modes[1]] || 0; const align = alignEnum[modes[0]] || "xMidYMid"; const [minX, minY, vbWidth, vbHeight] = params; return { minX, minY, vbWidth, vbHeight, align, meetOrSlice, }; } export { meetOrSliceTypes, alignEnum };
Fix script for release file already present case This avoids a: "AttributeError: 'HTTPError' object has no attribute 'message'" Signed-off-by: Ulysses Souza <[email protected]>
from __future__ import absolute_import from __future__ import unicode_literals from configparser import Error from requests.exceptions import HTTPError from twine.commands.upload import main as twine_upload from twine.utils import get_config from .utils import ScriptError def pypi_upload(args): print('Uploading to PyPi') try: rel = args.release.replace('-rc', 'rc') twine_upload([ 'dist/docker_compose-{}*.whl'.format(rel), 'dist/docker-compose-{}*.tar.gz'.format(rel) ]) except HTTPError as e: if e.response.status_code == 400 and 'File already exists' in str(e): if not args.finalize_resume: raise ScriptError( 'Package already uploaded on PyPi.' ) print('Skipping PyPi upload - package already uploaded') else: raise ScriptError('Unexpected HTTP error uploading package to PyPi: {}'.format(e)) def check_pypirc(): try: config = get_config() except Error as e: raise ScriptError('Failed to parse .pypirc file: {}'.format(e)) if config is None: raise ScriptError('Failed to parse .pypirc file') if 'pypi' not in config: raise ScriptError('Missing [pypi] section in .pypirc file') if not (config['pypi'].get('username') and config['pypi'].get('password')): raise ScriptError('Missing login/password pair for pypi repo')
from __future__ import absolute_import from __future__ import unicode_literals from configparser import Error from requests.exceptions import HTTPError from twine.commands.upload import main as twine_upload from twine.utils import get_config from .utils import ScriptError def pypi_upload(args): print('Uploading to PyPi') try: rel = args.release.replace('-rc', 'rc') twine_upload([ 'dist/docker_compose-{}*.whl'.format(rel), 'dist/docker-compose-{}*.tar.gz'.format(rel) ]) except HTTPError as e: if e.response.status_code == 400 and 'File already exists' in e.message: if not args.finalize_resume: raise ScriptError( 'Package already uploaded on PyPi.' ) print('Skipping PyPi upload - package already uploaded') else: raise ScriptError('Unexpected HTTP error uploading package to PyPi: {}'.format(e)) def check_pypirc(): try: config = get_config() except Error as e: raise ScriptError('Failed to parse .pypirc file: {}'.format(e)) if config is None: raise ScriptError('Failed to parse .pypirc file') if 'pypi' not in config: raise ScriptError('Missing [pypi] section in .pypirc file') if not (config['pypi'].get('username') and config['pypi'].get('password')): raise ScriptError('Missing login/password pair for pypi repo')
Set a initial $scope.model.value for true/false
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); if( $scope.model && !$scope.model.value ) { $scope.model.value = ($scope.renderModel.value === true) ? '1' : '0'; } //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
Fix marked compatibility on API Doc
/** * Display a SwaggerUI documentation */ import '../less/udata/swagger.less'; import $ from 'expose?$!expose?jQuery!jquery'; import commonmark from 'helpers/commonmark'; import hljs from 'highlight.js'; import log from 'logger'; // Required jQuery plugins import 'jquery.browser'; import 'swaggerui/lib/jquery.slideto.min'; import 'swaggerui/lib/jquery.wiggle.min'; import 'script!swaggerui/lib/jquery.ba-bbq.min'; import 'expose?Handlebars!handlebars'; import 'script!swaggerui/lib/underscore-min'; import 'script!swaggerui/lib/backbone-min'; import 'script!swaggerui/swagger-ui.min'; SwaggerUi = window.SwaggerUi; // Marked compatibility for SwaggerUI window.marked = commonmark; marked.setOptions = function() {}; $(function() { hljs.initHighlightingOnLoad(); $('pre code').each(function(i, e) { hljs.highlightBlock(e); }); const swaggerUi = new SwaggerUi({ url: $('meta[name="swagger-specs"]').attr('content'), dom_id: 'swagger-ui-container', supportedSubmitMethods: ['get'], onComplete: function(swaggerApi, swaggerUi) { log.debug('Loaded SwaggerUI'); $('#swagger-ui-container pre code').each(function(i, e) { hljs.highlightBlock(e); }); }, onFailure: function() { log.error('Unable to Load SwaggerUI'); }, docExpansion: 'none', sorter: 'alpha' }); swaggerUi.load(); });
/** * Display a SwaggerUI documentation */ import '../less/udata/swagger.less'; import $ from 'expose?$!expose?jQuery!jquery'; import hljs from 'highlight.js'; import log from 'logger'; // Required jQuery plugins import 'jquery.browser'; import 'swaggerui/lib/jquery.slideto.min'; import 'swaggerui/lib/jquery.wiggle.min'; import 'script!swaggerui/lib/jquery.ba-bbq.min'; import 'expose?Handlebars!handlebars'; import 'script!swaggerui/lib/underscore-min'; import 'script!swaggerui/lib/backbone-min'; import 'script!swaggerui/swagger-ui.min'; SwaggerUi = window.SwaggerUi; $(function() { hljs.initHighlightingOnLoad(); $('pre code').each(function(i, e) { hljs.highlightBlock(e); }); const swaggerUi = new SwaggerUi({ url: $('meta[name="swagger-specs"]').attr('content'), dom_id: 'swagger-ui-container', supportedSubmitMethods: ['get'], onComplete: function(swaggerApi, swaggerUi) { log.debug('Loaded SwaggerUI'); $('#swagger-ui-container pre code').each(function(i, e) { hljs.highlightBlock(e); }); }, onFailure: function() { log.error('Unable to Load SwaggerUI'); }, docExpansion: 'none', sorter: 'alpha' }); swaggerUi.load(); });
Rename to be consistent with backend name
""" Google App Engine support using User API """ from __future__ import absolute_import from google.appengine.api import users from social.backends.base import BaseAuth from social.exceptions import AuthException class GoogleAppEngineAuth(BaseAuth): """GoogleAppengine authentication backend""" name = 'google-appengine' def get_user_id(self, details, response): """Return current user id.""" user = users.get_current_user() if user: return user.user_id() def get_user_details(self, response): """Return user basic information (id and email only).""" user = users.get_current_user() return {'username': user.user_id(), 'email': user.email(), 'fullname': '', 'first_name': '', 'last_name': ''} def auth_url(self): """Build and return complete URL.""" return users.create_login_url(self.redirect_uri) def auth_complete(self, *args, **kwargs): """Completes login process, must return user instance.""" if not users.get_current_user(): raise AuthException('Authentication error') kwargs.update({'response': '', 'backend': self}) return self.strategy.authenticate(*args, **kwargs) BACKENDS = { 'google-appengine': GoogleAppEngineAuth }
""" Google App Engine support using User API """ from __future__ import absolute_import from google.appengine.api import users from social.backends.base import BaseAuth from social.exceptions import AuthException class GoogleAppEngineAuth(BaseAuth): """GoogleAppengine authentication backend""" name = 'google-appengine' def get_user_id(self, details, response): """Return current user id.""" user = users.get_current_user() if user: return user.user_id() def get_user_details(self, response): """Return user basic information (id and email only).""" user = users.get_current_user() return {'username': user.user_id(), 'email': user.email(), 'fullname': '', 'first_name': '', 'last_name': ''} def auth_url(self): """Build and return complete URL.""" return users.create_login_url(self.redirect_uri) def auth_complete(self, *args, **kwargs): """Completes login process, must return user instance.""" if not users.get_current_user(): raise AuthException('Authentication error') kwargs.update({'response': '', 'backend': self}) return self.strategy.authenticate(*args, **kwargs) BACKENDS = { 'gae': GoogleAppEngineAuth }
Fix Stream title alignment issue on Android
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import type { Narrow, Stream } from '../types'; import StreamIcon from '../streams/StreamIcon'; import { isTopicNarrow } from '../utils/narrow'; const styles = StyleSheet.create({ wrapper: { alignItems: 'flex-start', flex: 1, }, streamRow: { flexDirection: 'row', alignItems: 'center', }, streamText: { marginLeft: 4, fontSize: 18, }, topic: { fontSize: 13, opacity: 0.8, }, }); type Props = { narrow: Narrow, stream: Stream, color: string, }; export default class TitleStream extends PureComponent<Props> { props: Props; render() { const { narrow, stream, color } = this.props; return ( <View style={styles.wrapper}> <View style={styles.streamRow}> <StreamIcon isMuted={!stream.in_home_view} isPrivate={stream.invite_only} color={color} size={20} /> <Text style={[styles.streamText, { color }]} numberOfLines={1} ellipsizeMode="tail"> {stream.name} </Text> </View> {isTopicNarrow(narrow) && ( <Text style={[styles.topic, { color }]} numberOfLines={1} ellipsizeMode="tail"> {narrow[1].operand} </Text> )} </View> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import type { Narrow, Stream } from '../types'; import StreamIcon from '../streams/StreamIcon'; import { isTopicNarrow } from '../utils/narrow'; const styles = StyleSheet.create({ wrapper: { alignItems: 'flex-start', flex: 1, }, streamRow: { flexDirection: 'row', }, streamText: { marginLeft: 4, fontSize: 18, }, topic: { fontSize: 13, opacity: 0.8, }, }); type Props = { narrow: Narrow, stream: Stream, color: string, }; export default class TitleStream extends PureComponent<Props> { props: Props; render() { const { narrow, stream, color } = this.props; return ( <View style={styles.wrapper}> <View style={styles.streamRow}> <StreamIcon isMuted={!stream.in_home_view} isPrivate={stream.invite_only} color={color} size={20} /> <Text style={[styles.streamText, { color }]} numberOfLines={1} ellipsizeMode="tail"> {stream.name} </Text> </View> {isTopicNarrow(narrow) && ( <Text style={[styles.topic, { color }]} numberOfLines={1} ellipsizeMode="tail"> {narrow[1].operand} </Text> )} </View> ); } }
Fix __repl__ implementation for TupleVal
from .environment import Environment from viper.parser.ast.nodes import Expr class Value: pass class TupleVal(Value): def __init__(self, *vals: Value): self.vals = list(vals) def __repr__(self) -> str: return f"TupleVal({', '.join(map(str, self.vals))})" class NumVal(Value): def __init__(self, val: str): self.val = val def __repr__(self) -> str: return f"NumVal({self.val})" class CloVal(Value): def __init__(self, name: str, expr: Expr, env: Environment): self.name = name self.expr = expr self.env = env def __repr__(self) -> str: return f"CloVal({self.name}, {self.expr}, {self.env})" class BoolVal(Value): def __repr__(self) -> str: return "BoolVal" class TrueVal(BoolVal): def __repr__(self) -> str: return "TrueVal" class FalseVal(BoolVal): def __repr__(self) -> str: return "FalseVal" class UnitVal(Value): def __repr__(self) -> str: return "UnitVal" class BottomVal(Value): def __repr__(self) -> str: return "BottomVal" class EllipsisVal(Value): def __repr__(self) -> str: return "EllipsisVal"
from .environment import Environment from viper.parser.ast.nodes import Expr class Value: pass class TupleVal(Value): def __init__(self, *vals: Value): self.vals = list(vals) def __repr__(self) -> str: return f"TupleVal({', '.join(self.vals)})" class NumVal(Value): def __init__(self, val: str): self.val = val def __repr__(self) -> str: return f"NumVal({self.val})" class CloVal(Value): def __init__(self, name: str, expr: Expr, env: Environment): self.name = name self.expr = expr self.env = env def __repr__(self) -> str: return f"CloVal({self.name}, {self.expr}, {self.env})" class BoolVal(Value): def __repr__(self) -> str: return "BoolVal" class TrueVal(BoolVal): def __repr__(self) -> str: return "TrueVal" class FalseVal(BoolVal): def __repr__(self) -> str: return "FalseVal" class UnitVal(Value): def __repr__(self) -> str: return "UnitVal" class BottomVal(Value): def __repr__(self) -> str: return "BottomVal" class EllipsisVal(Value): def __repr__(self) -> str: return "EllipsisVal"
Remove debug console.log - Rain IA Remove debug console.log - Rain IA
(function(env) { "use strict"; env.ddg_spice_rain = function(api_result) { // Check for errors. if(!api_result || api_result.error || !api_result.currently || !api_result.flags['ddg-location']) { return Spice.failed('rain'); } Spice.add({ id: 'rain', name: 'Rain', data: api_result, meta: { sourceName: "Forecast.io", sourceUrl: "http://forecast.io/#/f/" + api_result.latitude + "," + api_result.longitude, }, normalize: function(item) { var is_raining = ["hail", "thunderstorm", "tornado", "sleet", "rain"].indexOf(item.currently.icon) >= 0; return { title: is_raining ? "Yes!" : "No.", location: item.flags['ddg-location'], is_raining: is_raining }; }, templates: { group: 'text', options: { content: Spice.rain.content, moreAt: true, moreText: { href: "/?ia=weather&q=weather+" + api_result.flags['ddg-location'], text: "Weather Forecast for " + api_result.flags['ddg-location'], } } } }); } }(this));
(function(env) { "use strict"; env.ddg_spice_rain = function(api_result) { console.log(api_result); // Check for errors. if(!api_result || api_result.error || !api_result.currently || !api_result.flags['ddg-location']) { return Spice.failed('rain'); } Spice.add({ id: 'rain', name: 'Rain', data: api_result, meta: { sourceName: "Forecast.io", sourceUrl: "http://forecast.io/#/f/" + api_result.latitude + "," + api_result.longitude, }, normalize: function(item) { var is_raining = ["hail", "thunderstorm", "tornado", "sleet", "rain"].indexOf(item.currently.icon) >= 0; return { title: is_raining ? "Yes!" : "No.", location: item.flags['ddg-location'], is_raining: is_raining }; }, templates: { group: 'text', options: { content: Spice.rain.content, moreAt: true, moreText: { href: "/?ia=weather&q=weather+" + api_result.flags['ddg-location'], text: "Weather Forecast for " + api_result.flags['ddg-location'], } } } }); } }(this));
Add field 'creator' to table 'runs' Example of values stored into *.tcx files: runtastic - makes sports funtastic, http://www.runtastic.com
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(db=DEFAULT_DB): conn = sqlite3.connect(db) c = conn.cursor() # Create tables c.execute('''CREATE TABLE runs ( id INTEGER PRIMARY KEY, start_time TEXT, time_s INTEGER, distance_m INTEGER, calories INTEGER, creator TEXT)''') c.execute('''CREATE TABLE points ( id INTEGER PRIMARY KEY, run_id INTEGER, datetime TEXT, latitude_d REAL, longitude_d REAL, altitude_m REAL, distance_m INTEGER, FOREIGN KEY(run_id) REFERENCES runs(id))''') # Commit the changes # and close the connection conn.commit() conn.close() if __name__ == '__main__': generate_tables(DEFAULT_DB)
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(filename_db): conn = sqlite3.connect(filename_db) c = conn.cursor() # Create tables c.execute('''CREATE TABLE runs ( id INTEGER PRIMARY KEY, start_time TEXT, time_s INTEGER, distance_m INTEGER, calories INTEGER)''') c.execute('''CREATE TABLE points ( id INTEGER PRIMARY KEY, run_id INTEGER, datetime TEXT, latitude_d REAL, longitude_d REAL, altitude_m REAL, distance_m INTEGER, FOREIGN KEY(run_id) REFERENCES runs(id))''') # Commit the changes # and close the connection conn.commit() conn.close() if __name__ == '__main__': generate_tables(DEFAULT_DB)
Refactor key to access files from a folder's JSON
from .core import OSFCore from .file import File class Storage(OSFCore): def _update_attributes(self, storage): if not storage: return # XXX does this happen? if 'data' in storage: storage = storage['data'] self.id = self._get_attribute(storage, 'id') self.path = self._get_attribute(storage, 'attributes', 'path') self.name = self._get_attribute(storage, 'attributes', 'name') self.node = self._get_attribute(storage, 'attributes', 'node') self.provider = self._get_attribute(storage, 'attributes', 'provider') self._files_key = ('relationships', 'files', 'links', 'related', 'href') self._files_url = self._get_attribute(storage, *self._files_key) def __str__(self): return '<Storage [{0}]>'.format(self.id) @property def files(self): """Iterate over all files in this storage""" files = self._follow_next(self._files_url) while files: file = files.pop() kind = self._get_attribute(file, 'attributes', 'kind') if kind == 'file': yield File(file) else: # recurse into a folder and add entries to `files` url = self._get_attribute(file, *self._files_key) files.extend(self._follow_next(url))
from .core import OSFCore from .file import File class Storage(OSFCore): def _update_attributes(self, storage): if not storage: return # XXX does this happen? if 'data' in storage: storage = storage['data'] self.id = self._get_attribute(storage, 'id') self.path = self._get_attribute(storage, 'attributes', 'path') self.name = self._get_attribute(storage, 'attributes', 'name') self.node = self._get_attribute(storage, 'attributes', 'node') self.provider = self._get_attribute(storage, 'attributes', 'provider') files = ['relationships', 'files', 'links', 'related', 'href'] self._files_url = self._get_attribute(storage, *files) def __str__(self): return '<Storage [{0}]>'.format(self.id) @property def files(self): """Iterate over all files in this storage""" files = self._follow_next(self._files_url) while files: file = files.pop() kind = self._get_attribute(file, 'attributes', 'kind') if kind == 'file': yield File(file) else: sub_dir_url = ('relationships', 'files', 'links', 'related', 'href') url = self._get_attribute(file, *sub_dir_url) files.extend(self._follow_next(url))
Add ItemID response field to relist fixed price item command
package ebay import "encoding/xml" type RelistFixedPriceItem struct { ItemID string StartPrice string `xml:",omitempty"` ConditionID uint `xml:",omitempty"` Quantity uint `xml:",omitempty"` Title string `xml:",omitempty"` Description string `xml:",omitempty"` PayPalEmailAddress string `xml:",omitempty"` PictureDetails *PictureDetails `xml:",omitempty"` ShippingDetails *ShippingDetails `xml:",omitempty"` ProductListingDetails *ProductListingDetails `xml:",omitempty"` ItemSpecifics []ItemSpecifics `xml:",omitempty"` } func (c RelistFixedPriceItem) CallName() string { return "RelistFixedPriceItem" } func (c RelistFixedPriceItem) Body() interface{} { type Item struct { RelistFixedPriceItem } return Item{c} } func (c RelistFixedPriceItem) ParseResponse(r []byte) (EbayResponse, error) { var xmlResponse RelistFixedPriceItemResponse err := xml.Unmarshal(r, &xmlResponse) return xmlResponse, err } type RelistFixedPriceItemResponse struct { ebayResponse ItemID string } func (r RelistFixedPriceItemResponse) ResponseErrors() ebayErrors { return r.ebayResponse.Errors }
package ebay import "encoding/xml" type RelistFixedPriceItem struct { ItemID string StartPrice string `xml:",omitempty"` ConditionID uint `xml:",omitempty"` Quantity uint `xml:",omitempty"` Title string `xml:",omitempty"` Description string `xml:",omitempty"` PayPalEmailAddress string `xml:",omitempty"` PictureDetails *PictureDetails `xml:",omitempty"` ShippingDetails *ShippingDetails `xml:",omitempty"` ProductListingDetails *ProductListingDetails `xml:",omitempty"` ItemSpecifics []ItemSpecifics `xml:",omitempty"` } func (c RelistFixedPriceItem) CallName() string { return "RelistFixedPriceItem" } func (c RelistFixedPriceItem) Body() interface{} { type Item struct { RelistFixedPriceItem } return Item{c} } func (c RelistFixedPriceItem) ParseResponse(r []byte) (EbayResponse, error) { var xmlResponse RelistFixedPriceItemResponse err := xml.Unmarshal(r, &xmlResponse) return xmlResponse, err } type RelistFixedPriceItemResponse struct { ebayResponse } func (r RelistFixedPriceItemResponse) ResponseErrors() ebayErrors { return r.ebayResponse.Errors }
Fix a call to environment->debug
<?php namespace Infinario; class SynchronousTransport implements Transport { public function postAndForget(Environment $environment, $url, $payload) { $this->post($environment, $url, $payload); } public function post(Environment $environment, $url, $payload) { $ch = curl_init($url); if ($ch === false) { $environment->exception(new Exception('Failed to init curl handle')); return false; } $payload = json_encode($payload); $environment->debug('posting to ' . $url, array('body' => $payload)); $headers = array('Content-Type:application/json'); if (curl_setopt($ch, CURLOPT_POSTFIELDS, $payload) === false) { $environment->exception(new Exception('failed setting payload')); curl_close($ch); return false; } if (curl_setopt($ch, CURLOPT_HTTPHEADER, $headers) === false) { $environment->exception(new Exception('failed setting headers')); curl_close($ch); return false; } if (curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) === false) { $environment->exception(new Exception('failed setting returntransfer')); curl_close($ch); return false; } $result = curl_exec($ch); curl_close($ch); return $result; } public function check(Environment $environment) { if (!function_exists('curl_init')) { $environment->exception(new Exception('php curl module not available')); } } }
<?php namespace Infinario; class SynchronousTransport implements Transport { public function postAndForget(Environment $environment, $url, $payload) { $this->post($environment, $url, $payload); } public function post(Environment $environment, $url, $payload) { $ch = curl_init($url); if ($ch === false) { $environment->exception(new Exception('Failed to init curl handle')); return false; } $payload = json_encode($payload); $environment->debug('posting to ' . $url, $payload); $headers = array('Content-Type:application/json'); if (curl_setopt($ch, CURLOPT_POSTFIELDS, $payload) === false) { $environment->exception(new Exception('failed setting payload')); curl_close($ch); return false; } if (curl_setopt($ch, CURLOPT_HTTPHEADER, $headers) === false) { $environment->exception(new Exception('failed setting headers')); curl_close($ch); return false; } if (curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) === false) { $environment->exception(new Exception('failed setting returntransfer')); curl_close($ch); return false; } $result = curl_exec($ch); curl_close($ch); return $result; } public function check(Environment $environment) { if (!function_exists('curl_init')) { $environment->exception(new Exception('php curl module not available')); } } }
MINOR: Print debug info to stderr
from __future__ import print_function import sys import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END def log(*args): print(*args, file=sys.stderr) sys.stderr.flush() class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 log(red(str(timedelta(milliseconds=elapsed_time)))) log("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
#!/usr/bin/env python3 import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): print("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 print(red(str(timedelta(milliseconds=elapsed_time)))) print("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
[utils] Add a function to clean dict keys Remove None values.
from flask_restful import reqparse from flask import request class ArgsMixin(object): """ Helpers to retrieve parameters from GET or POST queries. """ def get_args(self, descriptors): parser = reqparse.RequestParser() for descriptor in descriptors: action = None if len(descriptor) == 4: (name, default, required, action) = descriptor else: (name, default, required) = descriptor parser.add_argument( name, required=required, default=default, action=action ) return parser.parse_args() def clear_empty_fields(self, data): """ Remove fiels set to None from data dict. """ for key in list(data.keys()): if data[key] is None: del data[key] return data def get_page(self): """ Returns page requested by the user. """ options = request.args return int(options.get("page", "-1")) def get_force(self): """ Returns force parameter. """ options = request.args return options.get("force", "false") == "true" def get_relations(self): """ Returns force parameter. """ options = request.args return options.get("relations", "false") == "true" def get_episode_id(self): """ Returns episode ID parameter. """ options = request.args return options.get("episode_id", None)
from flask_restful import reqparse from flask import request class ArgsMixin(object): """ Helpers to retrieve parameters from GET or POST queries. """ def get_args(self, descriptors): parser = reqparse.RequestParser() for descriptor in descriptors: action = None if len(descriptor) == 4: (name, default, required, action) = descriptor else: (name, default, required) = descriptor parser.add_argument( name, required=required, default=default, action=action ) return parser.parse_args() def get_page(self): """ Returns page requested by the user. """ options = request.args return int(options.get("page", "-1")) def get_force(self): """ Returns force parameter. """ options = request.args return options.get("force", "false") == "true" def get_relations(self): """ Returns force parameter. """ options = request.args return options.get("relations", "false") == "true" def get_episode_id(self): """ Returns episode ID parameter. """ options = request.args return options.get("episode_id", None)
Fix resizer for election's embeds
colette.iframeResizer = (function() { 'use strict'; var pub = {}, cfg = { selector: '#iframeContent', el: null, delay: 0, resizeInternal: false, iframeId: 'iframeId' }; pub.init = function(args) { cfg.delay = args.delay || cfg.delay; cfg.iframeId = args.iframeId || cfg.iframeId; cfg.el = document.querySelector(args.selector || cfg.selector); window.addEventListener('message', function(e) { // resizeComplete if ('resizeComplete' === e.data) { iframeResizeComplete(); } }); window.addEventListener('load', function(e) { height(); }); window.addEventListener('resize', function(e) { height(); }); }; var iframeResizeComplete = function() { setTimeout(function() { cfg.resizeInternal = false; }, 500); }; var height = function() { if (!cfg.resizeInternal) { setTimeout(function() { sendHeight(); }, cfg.delay); } }; var sendHeight = function() { window.top.postMessage({type: 'doResize', height: cfg.el.offsetHeight, iframeId: cfg.iframeId}, '*'); cfg.resizeInternal = true; }; return pub; })();
colette.iframeResizer = (function() { 'use strict'; var pub = {}, cfg = { selector: '#iframeContent', el: null, delay: 0, resizeInternal: false }; pub.init = function(args) { cfg.delay = args.delay || cfg.delay; cfg.el = document.querySelector(args.selector || cfg.selector); window.addEventListener('message', function(e) { // resizeComplete if ('resizeComplete' === e.data) { iframeResizeComplete(); } }); window.addEventListener('load', function(e) { height(); }); window.addEventListener('resize', function(e) { height(); }); }; var iframeResizeComplete = function() { setTimeout(function() { cfg.resizeInternal = false; }, 500); }; var height = function() { if (!cfg.resizeInternal) { setTimeout(function() { sendHeight(); }, cfg.delay); } }; var sendHeight = function() { window.top.postMessage({type: 'doResize', height: cfg.el.offsetHeight}, '*'); cfg.resizeInternal = true; }; return pub; })();
Allow editing of 'notes' field when creating new StockItem
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', 'notes', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): note = forms.CharField(label='Notes', required=True, help_text='Add note (required)') class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'supplier_part', 'batch', 'status', 'notes', 'URL', ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): note = forms.CharField(label='Notes', required=True, help_text='Add note (required)') class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'supplier_part', 'batch', 'status', 'notes', 'URL', ]
Use FIREBASE_URL in waitList module.
(function() { 'use strict'; angular .module('app.waitList') .controller('WaitListController', WaitListController); WaitListController.$inject = ['$firebaseArray', 'FIREBASE_URL']; function WaitListController($firebaseArray, FIREBASE_URL) { var vm = this; var fireParties = new Firebase(FIREBASE_URL + 'parties'); var fireTextMessages = new Firebase(FIREBASE_URL + 'textMessages'); function Party() { this.name = ''; this.phone = ''; this.size = ''; this.done = false; this.notified = false; } vm.newParty = new Party(); vm.parties = $firebaseArray(fireParties); vm.addParty = addParty; vm.removeParty = removeParty; vm.sendTextMessage = sendTextMessage; vm.toggleDone = toggleDone; function addParty() { vm.parties.$add(vm.newParty); vm.newParty = new Party(); } function removeParty(party) { vm.parties.$remove(party); } function sendTextMessage(party) { var newTextMessage = { phoneNumber: party.phone, size: party.size, name: party.name }; fireTextMessages.push(newTextMessage); party.notified = true; vm.parties.$save(party); } function toggleDone(party) { vm.parties.$save(party); } } })();
(function() { 'use strict'; angular .module('app.waitList') .controller('WaitListController', WaitListController); WaitListController.$inject = ['$firebaseArray']; function WaitListController($firebaseArray) { var vm = this; var fireParties = new Firebase('https://waitandeat-v2-demo.firebaseio.com/parties'); var fireTextMessages = new Firebase('https://waitandeat-v2-demo.firebaseio.com/textMessages'); function Party() { this.name = ''; this.phone = ''; this.size = ''; this.done = false; this.notified = false; } vm.newParty = new Party(); vm.parties = $firebaseArray(fireParties); vm.addParty = addParty; vm.removeParty = removeParty; vm.sendTextMessage = sendTextMessage; vm.toggleDone = toggleDone; function addParty() { vm.parties.$add(vm.newParty); vm.newParty = new Party(); } function removeParty(party) { vm.parties.$remove(party); } function sendTextMessage(party) { var newTextMessage = { phoneNumber: party.phone, size: party.size, name: party.name }; fireTextMessages.push(newTextMessage); party.notified = true; vm.parties.$save(party); } function toggleDone(party) { vm.parties.$save(party); } } })();
Fix compile error after rebase
package org.ovirt.mobile.movirt.ui.dashboard; import android.os.Handler; import android.util.Log; import android.view.WindowManager; import android.widget.ProgressBar; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import org.ovirt.mobile.movirt.R; import org.ovirt.mobile.movirt.ui.MovirtActivity; @EActivity(R.layout.activity_dashboard) public class DashboardActivity extends MovirtActivity { private static final String TAG = DashboardActivity.class.getSimpleName(); private static final long SYNC_PERIOD_MILLIS = 3 * 60 * 1000; @ViewById ProgressBar progress; private Handler handler = new Handler(); @AfterViews void init() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setProgressBar(progress); } @Override protected void onResume() { super.onResume(); handler.post(syncRunnable); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(syncRunnable); } private Runnable syncRunnable = new Runnable( ) { public void run ( ) { Log.d(TAG, "Sync data"); onRefresh(); handler.postDelayed(syncRunnable, SYNC_PERIOD_MILLIS); } }; }
package org.ovirt.mobile.movirt.ui.dashboard; import android.os.Handler; import android.util.Log; import android.view.WindowManager; import android.widget.ProgressBar; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import org.ovirt.mobile.movirt.R; import org.ovirt.mobile.movirt.ui.MoVirtActivity; @EActivity(R.layout.activity_dashboard) public class DashboardActivity extends MoVirtActivity { private static final String TAG = DashboardActivity.class.getSimpleName(); private static final long SYNC_PERIOD_MILLIS = 3 * 60 * 1000; @ViewById ProgressBar progress; private Handler handler = new Handler(); @AfterViews void init() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setProgressBar(progress); } @Override protected void onResume() { super.onResume(); handler.post(syncRunnable); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(syncRunnable); } private Runnable syncRunnable = new Runnable( ) { public void run ( ) { Log.d(TAG, "Sync data"); onRefresh(); handler.postDelayed(syncRunnable, SYNC_PERIOD_MILLIS); } }; }
Allow user to type :)
import React, {PropTypes} from 'react' const ENTER = 13 const ESCAPE = 27 const RawQueryEditor = React.createClass({ propTypes: { query: PropTypes.shape({ rawText: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func.isRequired, }, getInitialState() { return { value: this.props.query.rawText, } }, componentWillReceiveProps(nextProps) { if (nextProps.query.rawText !== this.props.query.rawText) { this.setState({value: nextProps.query.rawText}) } }, handleKeyDown(e) { if (e.keyCode === ENTER) { e.preventDefault() this.handleUpdate(); } else if (e.keyCode === ESCAPE) { this.setState({value: this.props.query.rawText}, () => { this.editor.blur() }) } }, handleChange() { this.setState({ value: this.editor.value, }) }, handleUpdate() { this.props.onUpdate(this.state.value) }, render() { const {value} = this.state return ( <div className="raw-text"> <textarea className="raw-text--field" onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleUpdate} ref={(editor) => this.editor = editor} value={value} placeholder="Blank query" /> </div> ) }, }) export default RawQueryEditor
import React, {PropTypes} from 'react' const ENTER = 13 const ESCAPE = 27 const RawQueryEditor = React.createClass({ propTypes: { query: PropTypes.shape({ rawText: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func.isRequired, }, getInitialState() { return { value: this.props.query.rawText, } }, componentWillReceiveProps(nextProps) { if (nextProps.query.rawText !== this.props.query.rawText) { this.setState({value: nextProps.query.rawText}) } }, handleKeyDown(e) { e.preventDefault() if (e.keyCode === ENTER) { this.handleUpdate(); } else if (e.keyCode === ESCAPE) { this.setState({value: this.props.query.rawText}, () => { this.editor.blur() }) } }, handleChange() { this.setState({ value: this.editor.value, }) }, handleUpdate() { this.props.onUpdate(this.state.value) }, render() { const {value} = this.state return ( <div className="raw-text"> <textarea className="raw-text--field" onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleUpdate} ref={(editor) => this.editor = editor} value={value} placeholder="Blank query" /> </div> ) }, }) export default RawQueryEditor
Read ApiKey from parent only if it is set
import invariant from 'invariant'; import PathStrategy from '../path'; import NativeStrategy from './nativeStrategy'; import FetchStrategy from './fetchStrategy'; const directionStrategy = ({ props, type: { defaultProps } }, parentProps) => { const { baseURL, requestStrategy, origin, destination, apiKey, waypoints, avoid, mode, transitMode, transitRoutingPreference, weight, color, fillcolor, geodesic, ...rest } = props; invariant(origin, 'Origin prop is required'); invariant(destination, 'Destination prop is required'); // Use the parent's API key if one isn't set here. const key = apiKey ? apiKey : parentProps ? parentProps.apiKey : ''; const data = { key, baseURL, origin, destination, waypoints, avoid, mode, transitMode, transitRoutingPreference, ...rest, }; let pathPromise; if (typeof requestStrategy !== 'string') { pathPromise = requestStrategy(data); } else { switch (requestStrategy) { case 'native': pathPromise = NativeStrategy(data); break; case 'fetch': pathPromise = FetchStrategy(data); break; default: throw new Error('Specify a Request strategy to get directions from'); } } return pathPromise.then(path => PathStrategy({ props: { weight, color, fillcolor, geodesic, points: `enc:${path}` }, type: { defaultProps }, }) ); }; export default directionStrategy;
import invariant from 'invariant'; import PathStrategy from '../path'; import NativeStrategy from './nativeStrategy'; import FetchStrategy from './fetchStrategy'; const directionStrategy = ({ props, type: { defaultProps } }, parentProps) => { const { baseURL, requestStrategy, origin, destination, apiKey, waypoints, avoid, mode, transitMode, transitRoutingPreference, weight, color, fillcolor, geodesic, ...rest } = props; invariant(origin, 'Origin prop is required'); invariant(destination, 'Destination prop is required'); // Use the parent's API key if one isn't set here. const key = apiKey ? apiKey : parentProps.apiKey; const data = { key, baseURL, origin, destination, waypoints, avoid, mode, transitMode, transitRoutingPreference, ...rest, }; let pathPromise; if (typeof requestStrategy !== 'string') { pathPromise = requestStrategy(data); } else { switch (requestStrategy) { case 'native': pathPromise = NativeStrategy(data); break; case 'fetch': pathPromise = FetchStrategy(data); break; default: throw new Error('Specify a Request strategy to get directions from'); } } return pathPromise.then(path => PathStrategy({ props: { weight, color, fillcolor, geodesic, points: `enc:${path}` }, type: { defaultProps }, }) ); }; export default directionStrategy;
Stop travis/phpunit complaining about defined constants Local phpunit didn't throw this error
<?php namespace Jadu\Pulsar\Twig\Extension; class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->ext = new GetConstantExtension(array()); defined('STRING') or define('STRING', 'foo'); defined('BOOL') or define('BOOL', true); defined('INT') or define('INT', 42); defined('NULL') or define('NULL', null); } public function testGetName() { $this->assertEquals('get_constant_extension', $this->ext->getName()); } public function testGetConstantReturnsNullByDefault() { $this->assertEquals(null, $this->ext->getConstant()); } public function testGetUndefinedConstantReturnsNull() { $this->assertEquals(null, $this->ext->getConstant('WAT')); } public function testGetStringConstantReturnsString() { $this->assertEquals('foo', $this->ext->getConstant('STRING')); } public function testGetBoolConstantReturnsBool() { $this->assertEquals(true, $this->ext->getConstant('BOOL')); } public function testGetIntConstantReturnsInt() { $this->assertEquals(42, $this->ext->getConstant('INT')); } public function testGetNullConstantReturnsNull() { $this->assertEquals(null, $this->ext->getConstant('NULL')); } }
<?php namespace Jadu\Pulsar\Twig\Extension; class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->ext = new GetConstantExtension(array()); define('STRING', 'foo'); define('BOOL', true); define('INT', 42); define('NULL', null); } public function testGetName() { $this->assertEquals('get_constant_extension', $this->ext->getName()); } public function testGetConstantReturnsNullByDefault() { $this->assertEquals(null, $this->ext->getConstant()); } public function testGetUndefinedConstantReturnsNull() { $this->assertEquals(null, $this->ext->getConstant('WAT')); } public function testGetStringConstantReturnsString() { $this->assertEquals('foo', $this->ext->getConstant('STRING')); } public function testGetBoolConstantReturnsBool() { $this->assertEquals(true, $this->ext->getConstant('BOOL')); } public function testGetIntConstantReturnsInt() { $this->assertEquals(42, $this->ext->getConstant('INT')); } public function testGetNullConstantReturnsNull() { $this->assertEquals(null, $this->ext->getConstant('NULL')); } }