text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove quotes from string because they break e.g. box shadows
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return value } return JSON.stringify(value) } module.exports = convertJsToSass
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function withQuotesIfNecessary(value) { const hasQuotes = /^['"](\n|.)*['"]$/gm.test(value) const requiresQuotes = /^[0 ]/.test(value) return hasQuotes || !requiresQuotes ? value : `"${value}"` } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return withQuotesIfNecessary(value) } return JSON.stringify(value) } module.exports = convertJsToSass
Remove <Skills /> warning when running tests
import React from 'react'; import { expect } from 'chai'; import Skills from '../Skills'; import LinearProgress from 'material-ui/LinearProgress'; import shallowWithContext from 'testing/shallowWithContext'; describe('Component', function() { describe('<Skills />', function () { it('should render null if no skills are given', function () { const wrapper = shallowWithContext( <Skills skills={[]} containerWidth={300} /> ); expect(wrapper.node).to.be.null; }); it('should render one skill', function () { const mockSkills = [{ name: 'Javascript', level: 0.75, }]; const wrapper = shallowWithContext( <Skills skills={mockSkills} containerWidth={300} /> ); expect(wrapper.find(LinearProgress)).to.have.length(1); }); }); });
import React from 'react'; import { expect } from 'chai'; import Skills from '../Skills'; import LinearProgress from 'material-ui/LinearProgress'; import shallowWithContext from 'testing/shallowWithContext'; describe('Component', function() { describe('<Skills />', function () { it('should render null if no skills are given', function () { const wrapper = shallowWithContext(<Skills skills={[]} />); expect(wrapper.node).to.be.null; }); it('should render one skill', function () { const mockSkills = [{ name: 'Javascript', level: 0.75, }]; const wrapper = shallowWithContext(<Skills skills={mockSkills} />); expect(wrapper.find(LinearProgress)).to.have.length(1); }); }); });
Make sure moment only loads in server
Package.describe({ name: 'd4nyll:moment', version: '0.0.4', // Brief, one-line summary of the package. summary: 'Meteor wrapper for Moment and Moment Timezone', // URL to the Git repository containing the source code for this package. git: 'https://github.com/d4nyll/epic.git', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Npm.depends({ 'moment': '2.10.6', 'moment-timezone': '0.4.0' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.3'); api.addFiles('moment.js', 'server'); api.export('moment'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('d4nyll:moment'); api.addFiles('moment-tests.js'); });
Package.describe({ name: 'd4nyll:moment', version: '0.0.3', // Brief, one-line summary of the package. summary: 'Meteor wrapper for Moment and Moment Timezone', // URL to the Git repository containing the source code for this package. git: 'https://github.com/d4nyll/epic.git', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Npm.depends({ 'moment': '2.10.6', 'moment-timezone': '0.4.0' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.3'); api.addFiles('moment.js'); api.export('moment'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('d4nyll:moment'); api.addFiles('moment-tests.js'); });
Add comment for full url with non guest user
# coding=utf-8 # # Must be called in roche root dir # import os from os import walk from eulexistdb.db import ExistDB # # Timeout higher? # # # http://username:password@54.220.97.75:8080/exist # xmldb = ExistDB('http://54.220.97.75:8080/exist') xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: print "--" + dirpath + '/' + filename xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
# coding=utf-8 # # Must be called in roche root dir # import os from os import walk from eulexistdb.db import ExistDB # # Timeout higher? # xmldb = ExistDB('http://54.220.97.75:8080/exist') xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: print "--" + dirpath + '/' + filename xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
Fix bug where ONESTOP_REGISTRY env var was not checked
"""Read and write Onestop data.""" import sys import os import glob import json import argparse import urllib import mzgeohash import util import entities import errors class OnestopRegistry(object): """Onestop Registry.""" def __init__(self, path=None): """Path to directory containing feeds.""" # Path to registry self.path = path or os.getenv('ONESTOP_REGISTRY') or '.' if not os.path.exists(os.path.join(self.path, 'feeds')): raise errors.OnestopInvalidRegistry( 'Invalid Onestop Registry directory: %s'%self.path ) def _registered(self, path, prefix): return [ os.path.basename(i).partition('.')[0] for i in glob.glob( os.path.join(self.path, path, '%s-*.*json'%prefix) ) ] def feeds(self): return self._registered('feeds', 'f') def feed(self, onestopId): """Load a feed by onestopId.""" filename = os.path.join(self.path, 'feeds', '%s.json'%onestopId) with open(filename) as f: data = json.load(f) return entities.OnestopFeed.from_json(data)
"""Read and write Onestop data.""" import sys import os import glob import json import argparse import urllib import mzgeohash import util import entities import errors class OnestopRegistry(object): """Onestop Registry.""" def __init__(self, path='.'): """Path to directory containing feeds.""" # Path to registry self.path = path or os.getenv('ONESTOP_REGISTRY') or '.' if not os.path.exists(os.path.join(self.path, 'feeds')): raise errors.OnestopInvalidRegistry( 'Invalid Onestop Registry directory: %s'%self.path ) def _registered(self, path, prefix): return [ os.path.basename(i).partition('.')[0] for i in glob.glob( os.path.join(self.path, path, '%s-*.*json'%prefix) ) ] def feeds(self): return self._registered('feeds', 'f') def feed(self, onestopId): """Load a feed by onestopId.""" filename = os.path.join(self.path, 'feeds', '%s.json'%onestopId) with open(filename) as f: data = json.load(f) return entities.OnestopFeed.from_json(data)
Order the same way collection is ordered in the game.
<?php require_once(__DIR__ . '/hs-www.php'); class HearthstoneTextSearch { public function go() { $q = isset($_GET['q']) ? $_GET['q'] : ''; $args['q'] = $q; $args['results'] = $this->search($q); $args['numResults'] = count($args['results']); $args['pluralResults'] = count($args['results']) === 1 ? '' : 's'; $args['urlPrefix'] = U(''); return T()->index($args); } private function search($q) { $search = new Search($q); $where = $search->whereClause(); if ($where === null || trim($q) === '') { return []; } $sql = 'SELECT * FROM card AS c INNER JOIN card_set AS cs ON c.id = cs.card_id WHERE ' . $where . " ORDER BY IF(player_class = '', 'Z_NEUTRAL', player_class), cost, name"; try { $cards = D()->execute($sql); } catch (DatabaseException $e) { return []; } $results = []; foreach ($cards as $card) { $results[] = ['systemId' => $card['system_id']]; } return $results; } } echo (new HearthstoneTextSearch())->go();
<?php require_once(__DIR__ . '/hs-www.php'); class HearthstoneTextSearch { public function go() { $q = isset($_GET['q']) ? $_GET['q'] : ''; $args['q'] = $q; $args['results'] = $this->search($q); $args['numResults'] = count($args['results']); $args['pluralResults'] = count($args['results']) === 1 ? '' : 's'; $args['urlPrefix'] = U(''); return T()->index($args); } private function search($q) { $search = new Search($q); $where = $search->whereClause(); if ($where === null || trim($q) === '') { return []; } $sql = 'SELECT * FROM card AS c INNER JOIN card_set AS cs ON c.id = cs.card_id WHERE ' . $where . ' ORDER BY name'; try { $cards = D()->execute($sql); } catch (DatabaseException $e) { return []; } $results = []; foreach ($cards as $card) { $results[] = ['systemId' => $card['system_id']]; } return $results; } } echo (new HearthstoneTextSearch())->go();
Fix async vendor lib AMD path
require.config({ baseUrl: '../src', paths: { // Vendor libraries async: '../bower_components/requirejs-plugins/src/async', sinon: '../bower_components/sinon/index', jasmine: '../bower_components/jasmine/lib/jasmine-core/jasmine', 'jasmine-html': '../bower_components/jasmine/lib/jasmine-core/jasmine-html', underscore: '../bower_components/underscore/underscore', // Test resources spec: '../test/spec', mock: '../test/mock' }, shim: { jasmine: { exports: 'jasmine' }, 'jasmine-html': { deps: ['jasmine'], exports: 'jasmine' }, sinon: { exports: 'sinon' }, underscore: { exports: '_' } } }); require([ 'jasmine', 'jasmine-html' ], function(jasmine) { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var reporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(reporter); jasmineEnv.specFilter = function(spec) { return reporter.specFilter(spec); }; require([ // Test specs go here 'spec/mock/require' ], function() { jasmineEnv.execute(); }); });
require.config({ baseUrl: '../src', paths: { // Vendor libraries async: '../bower_components/requirejs-plugins/async', sinon: '../bower_components/sinon/index', jasmine: '../bower_components/jasmine/lib/jasmine-core/jasmine', 'jasmine-html': '../bower_components/jasmine/lib/jasmine-core/jasmine-html', underscore: '../bower_components/underscore/underscore', // Test resources spec: '../test/spec', mock: '../test/mock' }, shim: { jasmine: { exports: 'jasmine' }, 'jasmine-html': { deps: ['jasmine'], exports: 'jasmine' }, sinon: { exports: 'sinon' }, underscore: { exports: '_' } } }); require([ 'jasmine', 'jasmine-html' ], function(jasmine) { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var reporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(reporter); jasmineEnv.specFilter = function(spec) { return reporter.specFilter(spec); }; require([ // Test specs go here 'spec/mock/require' ], function() { jasmineEnv.execute(); }); });
Fix textarea in frontend port to jquery
var $ = require('jQuery'); var fieldRegistry = require('kwf/frontend-form/field-registry'); var Field = require('kwf/frontend-form/field/field'); var kwfExtend = require('kwf/extend'); var TextArea = kwfExtend(Field, { initField: function() { var input = this.el.find('textarea'); if (input) { input.on('keypress', (function () { this.el.trigger('kwfUp-form-change', this.getValue()); }).bind(this)); this._initPlaceholder(input); } }, getFieldName: function() { return this.el.find('textarea').get(0).name; }, getValue: function() { return this.el.find('textarea').get(0).value; }, clearValue: function() { this.el.find('textarea').get(0).value = ''; }, clearValue: function(value) { this.el.find('textarea').get(0).value = value; } }); fieldRegistry.register('kwfFormFieldTextArea', TextArea); module.exports = TextArea;
var $ = require('jQuery'); var fieldRegistry = require('kwf/frontend-form/field-registry'); var Field = require('kwf/frontend-form/field/field'); var kwfExtend = require('kwf/extend'); var TextArea = kwfExtend(Field, { initField: function() { this.el.select('textarea').each((function(index, input) { $(input).on('keypress', (function() { this.el.trigger('kwfUp-form-change', this.getValue()); }).bind(this)); this._initPlaceholder(input); }).bind(this)); }, getFieldName: function() { return this.el.find('textarea').get(0).name; }, getValue: function() { return this.el.find('textarea').get(0).value; }, clearValue: function() { this.el.select('textarea').get(0).value = ''; }, clearValue: function(value) { this.el.select('textarea').get(0).value = value; } }); fieldRegistry.register('kwfFormFieldTextArea', TextArea); module.exports = TextArea;
Add blank object fallback for routes in integration tests
import Ember from 'ember'; const { get, set, guidFor, merge, getOwner } = Ember; function updateTitle(tokens) { set(this, 'title', tokens.toString()); } export default Ember.Helper.extend({ pageTitleList: Ember.inject.service(), headData: Ember.inject.service(), init() { this._super(); let tokens = get(this, 'pageTitleList'); tokens.push({ id: guidFor(this) }); }, compute(params, _hash) { let tokens = get(this, 'pageTitleList'); let hash = merge({}, _hash); hash.id = guidFor(this); hash.title = params.join(''); tokens.push(hash); Ember.run.scheduleOnce('afterRender', get(this, 'headData'), updateTitle, tokens); return ''; }, destroy() { let tokens = get(this, 'pageTitleList'); let id = guidFor(this); tokens.remove(id); let router = getOwner(this).lookup('router:main'); let routes = router._routerMicrolib || router.router; let { activeTransition } = routes || {}; let headData = get(this, 'headData'); if (activeTransition) { activeTransition.promise.finally(function () { if (headData.isDestroyed) { return; } Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens); }); } else { Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens); } } });
import Ember from 'ember'; const { get, set, guidFor, merge, getOwner } = Ember; function updateTitle(tokens) { set(this, 'title', tokens.toString()); } export default Ember.Helper.extend({ pageTitleList: Ember.inject.service(), headData: Ember.inject.service(), init() { this._super(); let tokens = get(this, 'pageTitleList'); tokens.push({ id: guidFor(this) }); }, compute(params, _hash) { let tokens = get(this, 'pageTitleList'); let hash = merge({}, _hash); hash.id = guidFor(this); hash.title = params.join(''); tokens.push(hash); Ember.run.scheduleOnce('afterRender', get(this, 'headData'), updateTitle, tokens); return ''; }, destroy() { let tokens = get(this, 'pageTitleList'); let id = guidFor(this); tokens.remove(id); let router = getOwner(this).lookup('router:main'); let routes = router._routerMicrolib || router.router; let { activeTransition } = routes; let headData = get(this, 'headData'); if (activeTransition) { activeTransition.promise.finally(function () { if (headData.isDestroyed) { return; } Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens); }); } else { Ember.run.scheduleOnce('afterRender', headData, updateTitle, tokens); } } });
Add pre-install protobuf gen script
#!/usr/bin/env python import os, sys from setuptools import setup, find_packages from setuptools.command.install import install as _install reqs_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , "requirements.txt") reqs = None with open(reqs_file) as f: reqs = f.readlines() def _pre_install(dir): from subprocess import check_call check_call(['scripts/build_grpc.sh'], cwd=dir) class install(_install): def run(self): self.execute(_pre_install, [os.path.dirname(__file__)], msg="Generating protobuf") _install.run(self) setup( version='0.1.0', name='mediachain-client', description='mediachain reader command line interface', author='Mediachain Labs', packages=find_packages('.'), entry_points={ 'console_scripts': [ 'mediachain = mediachain.cli.main:main' ] }, url='http://mediachain.io', install_requires=reqs, cmdclass={'install': install}, )
#!/usr/bin/env python import os from setuptools import setup, find_packages reqs_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , "requirements.txt") reqs = None with open(reqs_file) as f: reqs = f.readlines() setup( version='0.1.0', name='mediachain-client', description='mediachain reader command line interface', author='Mediachain Labs', packages=find_packages('.'), entry_points={ 'console_scripts': [ 'mediachain = mediachain.cli.main:main' ] }, url='http://mediachain.io', install_requires=reqs, )
Add links to idvidual inventory scenes
import React from 'react' import InventoryContainer from '../containers/InventoryContainer' import ShadowBox from '../Components/ShadowBox' import FlexDiv from '../Components/FlexDiv' const InventoryBox = ShadowBox.extend` width:100%; margin:10px; ` const InventoryDiv = FlexDiv.extend` width:50%; margin-top: 50px; ` const InventoryScene = () => { const maltColumns = [ {name: "Malt Name", type: "text"}, {name: "Amount", type: "number"} ] const yeastColumns = [ {name: "Yeast Name", type: "text"}, {name: "Amount", type: "number"} ] const hopColumns = [ {name: "Hop Name", type: "text"}, {name: "Amount", type: "number"} ] return( <InventoryDiv> <InventoryBox> <InventoryContainer name="malt" columns={maltColumns} displayLimit={5} /> <a href="/inventory/malt">View Full Table</a> </InventoryBox> <InventoryBox> <InventoryContainer name="yeast" columns={yeastColumns} displayLimit={5} /> <a href="/inventory/yeast">View Full Table</a> </InventoryBox> <InventoryBox> <InventoryContainer name="hops" columns={hopColumns} displayLimit={5} /> <a href="/inventory/hops">View Full Table</a> </InventoryBox> </InventoryDiv> ) } export default InventoryScene
import React from 'react' import InventoryContainer from '../containers/InventoryContainer' import ShadowBox from '../Components/ShadowBox' import FlexDiv from '../Components/FlexDiv' const InventoryBox = ShadowBox.extend` width:100%; margin:10px; ` const InventoryDiv = FlexDiv.extend` width:50%; margin-top: 50px; ` const InventoryScene = () => { const maltColumns = [ {name: "Malt Name", type: "text"}, {name: "Amount", type: "number"} ] const yeastColumns = [ {name: "Yeast Name", type: "text"}, {name: "Amount", type: "number"} ] const hopColumns = [ {name: "Hop Name", type: "text"}, {name: "Amount", type: "number"} ] return( <InventoryDiv> <InventoryBox> <InventoryContainer name="malt" columns={maltColumns} displayLimit={5} /> </InventoryBox> <InventoryBox> <InventoryContainer name="yeast" columns={yeastColumns} displayLimit={5} /> </InventoryBox> <InventoryBox> <InventoryContainer name="hops" columns={hopColumns} displayLimit={5} /> </InventoryBox> </InventoryDiv> ) } export default InventoryScene
Make GPIO importable, but not usable, as non-root
import cffi ffi = cffi.FFI() ffi.cdef(""" int setup(void); void setup_gpio(int gpio, int direction, int pud); int gpio_function(int gpio); void output_gpio(int gpio, int value); int input_gpio(int gpio); void set_rising_event(int gpio, int enable); void set_falling_event(int gpio, int enable); void set_high_event(int gpio, int enable); void set_low_event(int gpio, int enable); int eventdetected(int gpio); void cleanup(void); """) C = ffi.verify(sources=['c_gpio.c']) write = C.output_gpio read = C.input_gpio cleanup = C.cleanup setup = C.setup_gpio if C.setup(): def error(*args): raise RuntimeError("Error initializing GPIO") write, read, cleanup, setup = error, error, error, error INPUT = 1 OUTPUT = 0 HIGH = 1 LOW = 0 PUD_OFF = 0 PUD_DOWN = 1 PUD_UP = 2
import cffi ffi = cffi.FFI() ffi.cdef(""" int setup(void); void setup_gpio(int gpio, int direction, int pud); int gpio_function(int gpio); void output_gpio(int gpio, int value); int input_gpio(int gpio); void set_rising_event(int gpio, int enable); void set_falling_event(int gpio, int enable); void set_high_event(int gpio, int enable); void set_low_event(int gpio, int enable); int eventdetected(int gpio); void cleanup(void); """) C = ffi.verify(sources=['c_gpio.c']) write = C.output_gpio read = C.input_gpio cleanup = C.cleanup setup = C.setup_gpio if C.setup(): raise RuntimeError("Error initializing GPIO") INPUT = 1 OUTPUT = 0 HIGH = 1 LOW = 0 PUD_OFF = 0 PUD_DOWN = 1 PUD_UP = 2
Add URL to setup script
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
Fix uglify after buildRelease & buildTests
"use strict"; module.exports = function (grunt) { grunt.registerTask("make", [ "exec:version", "check", "jsdoc:public", "connectIf", "concurrent:source", "exec:buildDebug", "exec:buildRelease", "uglify:buildRelease", "concurrent:debug", "concurrent:release", "uglify:buildTests", "exec:fixUglify", "copy:publishVersionPlato", "copy:publishVersion", "copy:publishVersionDoc", "copy:publishTest" ]); };
"use strict"; module.exports = function (grunt) { grunt.registerTask("make", [ "exec:version", "check", "jsdoc:public", "connectIf", "concurrent:source", "exec:buildDebug", "exec:buildRelease", "uglify:buildRelease", "exec:fixUglify", "concurrent:debug", "concurrent:release", "uglify:buildTests", "copy:publishVersionPlato", "copy:publishVersion", "copy:publishVersionDoc", "copy:publishTest" ]); };
Use a more cross-platform touch detection method Detect more than just iDevices for touch support
const isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)); const event = isTouch ? 'touchstart' : 'click' const directive = { instances: [] } directive.onEvent = function (event) { directive.instances.forEach(({ el, fn }) => { if (event.target !== el && !el.contains(event.target)) { fn && fn(event) } }) } directive.bind = function (el) { directive.instances.push({ el, fn: null }) if (directive.instances.length === 1) { document.addEventListener(event, directive.onEvent) } } directive.update = function (el, binding) { if (typeof binding.value !== 'function') { throw new Error('Argument must be a function') } const instance = directive.instances.find(i => i.el === el) instance.fn = binding.value } directive.unbind = function (el) { const instanceIndex = directive.instances.findIndex(i => i.el === el) directive.instances.splice(instanceIndex, 1) if (directive.instances.length === 0) { document.removeEventListener(event, directive.onEvent) } } export default directive
const userAgent = navigator.userAgent.toLowerCase() const event = userAgent.match(/(iphone|ipod|ipad)/) ? 'touchstart' : 'click' const directive = { instances: [] } directive.onEvent = function (event) { directive.instances.forEach(({ el, fn }) => { if (event.target !== el && !el.contains(event.target)) { fn && fn(event) } }) } directive.bind = function (el) { directive.instances.push({ el, fn: null }) if (directive.instances.length === 1) { document.addEventListener(event, directive.onEvent) } } directive.update = function (el, binding) { if (typeof binding.value !== 'function') { throw new Error('Argument must be a function') } const instance = directive.instances.find(i => i.el === el) instance.fn = binding.value } directive.unbind = function (el) { const instanceIndex = directive.instances.findIndex(i => i.el === el) directive.instances.splice(instanceIndex, 1) if (directive.instances.length === 0) { document.removeEventListener(event, directive.onEvent) } } export default directive
linters: Add linter to catch unquoted use of $(TEST_HC) This is a common bug that creeps into Makefiles (e.g. see T12674).
#!/usr/bin/env python3 """ Linters for testsuite makefiles """ from linter import run_linters, RegexpLinter """ Warn for use of `--interactive` inside Makefiles (#11468). Encourage the use of `$(TEST_HC_OPTS_INTERACTIVE)` instead of `$(TEST_HC_OPTS) --interactive -ignore-dot-ghci -v0`. It's too easy to forget one of those flags when adding a new test. """ interactive_linter = \ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') test_hc_quotes_linter = \ RegexpLinter('\t\\$\\(TEST_HC\\)', message = "Warning: $(TEST_HC) should be quoted in Makefiles.", ).add_path_filter(lambda path: path.name == 'Makefile') linters = [ interactive_linter, test_hc_quotes_linter, ] if __name__ == '__main__': run_linters(linters, subdir='testsuite')
#!/usr/bin/env python3 """ Warn for use of `--interactive` inside Makefiles (#11468). Encourage the use of `$(TEST_HC_OPTS_INTERACTIVE)` instead of `$(TEST_HC_OPTS) --interactive -ignore-dot-ghci -v0`. It's too easy to forget one of those flags when adding a new test. """ from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'--interactive', message = "Warning: Use `$(TEST_HC_OPTS_INTERACTIVE)` instead of `--interactive -ignore-dot-ghci -v0`." ).add_path_filter(lambda path: path.name == 'Makefile') ] if __name__ == '__main__': run_linters(linters, subdir='testsuite')
Add test for asserting method arguments
<?php namespace MockaTests; use Mocka\MethodMock; class MethodMockTest extends \PHPUnit_Framework_TestCase { public function testIntegrated() { $method = new MethodMock(); $method->set(function () { return 'foo'; }); $method->at(1, function () { return 'bar'; }); $method->at([2, 5], function () { return 'zoo'; }); $this->assertSame('foo', $method->invoke()); $this->assertSame('bar', $method->invoke()); $this->assertSame('zoo', $method->invoke()); $this->assertSame('foo', $method->invoke()); $method->set(function () { return 'def'; }); $this->assertSame('def', $method->invoke()); $this->assertSame('zoo', $method->invoke()); } public function testAssertingArguments() { $method = new MethodMock(); $method->set(function($foo) { $this->assertSame('bar', $foo); }); $method->invoke(['bar']); } }
<?php namespace MockaTests; use Mocka\MethodMock; class MethodMockTest extends \PHPUnit_Framework_TestCase { public function testIntegrated() { $method = new MethodMock(); $method->set(function () { return 'foo'; }); $method->at(1, function () { return 'bar'; }); $method->at([2, 5], function () { return 'zoo'; }); $this->assertSame('foo', $method->invoke()); $this->assertSame('bar', $method->invoke()); $this->assertSame('zoo', $method->invoke()); $this->assertSame('foo', $method->invoke()); $method->set(function () { return 'def'; }); $this->assertSame('def', $method->invoke()); $this->assertSame('zoo', $method->invoke()); } }
Fix typo in error message
/*global exports: true, require: true */ /*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */ var path = require('path'), compressor = require('solder/compressor'); function Closure(type, options) { this.type = type; this.options = options; this.args = options.args; if (this.type !== 'js') { throw new Error('Closure Compiler only supports JavaScript'); } if (!options.jar) { throw new Error('Closure Compiler jar file not specified'); } path.exists(options.jar, function (exists) { if (!exists) { throw new Error('Closure Compiler jar file not found: ' + options.jar); } }); } Closure.prototype = compressor.createCompressor(); Closure.prototype.compress = function (input, callback) { var command = 'java -jar {jar} --js {input} --js_output_file {output}'; this.compressFS(command, input, callback); }; // -- Exports ---------------------------------------------------------------- exports.create = function (type, options) { return new Closure(type, options); };
/*global exports: true, require: true */ /*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */ var path = require('path'), compressor = require('solder/compressor'); function Closure(type, options) { this.type = type; this.options = options; this.args = options.args; if (this.type !== 'js') { throw new Error('Closure Compiler only supports JavaScrtipt'); } if (!options.jar) { throw new Error('Closure Compiler jar file not specified'); } path.exists(options.jar, function (exists) { if (!exists) { throw new Error('Closure Compiler jar file not found: ' + options.jar); } }); } Closure.prototype = compressor.createCompressor(); Closure.prototype.compress = function (input, callback) { var command = 'java -jar {jar} --js {input} --js_output_file {output}'; this.compressFS(command, input, callback); }; // -- Exports ---------------------------------------------------------------- exports.create = function (type, options) { return new Closure(type, options); };
Remove comment containing incorrect conversion function.
# midi-beeper-orchestra - program to create an orchestra from PC speakers # Copyright (C) 2015 The Underscores # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math def MIDItoHz(MIDIval): """ Converts a MIDI note, MIDIval, value to the equivalent hertz value """ return (2**((MIDIval-69)/12))*440 def hzToMIDI(hz): """ Converts hertz, hz, to MIDI note equivalent """ midi = 2**((hz-69)/12) * 440 return int(midi + 0.5)
# midi-beeper-orchestra - program to create an orchestra from PC speakers # Copyright (C) 2015 The Underscores # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math def MIDItoHz(MIDIval): """ Converts a MIDI note, MIDIval, value to the equivalent hertz value """ #return 69 + 12 * math.log((MIDIval/440), 2) return (2**((MIDIval-69)/12))*440 def hzToMIDI(hz): """ Converts hertz, hz, to MIDI note equivalent """ midi = 2**((hz-69)/12) * 440 return int(midi + 0.5)
Include py.typed marker in package
#!/usr/bin/env python from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
#!/usr/bin/env python from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
Fix issue with PhantomJS and Function.prototype.bind support
//= require jquery //= require jquery_ujs //= require jquery.remotipart //= require select2 //= require cocoon //= require dropzone //= require vendor/polyfills/bind //= require govuk/selection-buttons //= require moj //= require modules/moj.cookie-message.js //= require_tree . (function () { 'use strict'; delete moj.Modules.devs; $('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function (e, insertedItem) { $(insertedItem).find('.select2').select2(); }); $('.select2').select(); //Stops the form from submitting when the user presses 'Enter' key $('#claim-form, #claim-status').on('keypress', function(e) { if (e.keyCode === 13) { return false; } }); var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
//= require jquery //= require jquery_ujs //= require jquery.remotipart //= require select2 //= require cocoon //= require dropzone //= require govuk/selection-buttons //= require moj //= require modules/moj.cookie-message.js //= require_tree . (function () { 'use strict'; delete moj.Modules.devs; $('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function (e, insertedItem) { $(insertedItem).find('.select2').select2(); }); $('.select2').select(); //Stops the form from submitting when the user presses 'Enter' key $('#claim-form, #claim-status').on('keypress', function(e) { if (e.keyCode === 13) { return false; } }); var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
Update QUERY_FIELDS const to only deconstruct the query fields object
const router = require('express').Router() const { ENTITIES } = require('../../../search/constants') const { QUERY_FIELDS } = require('../../constants') const { getCollection, exportCollection } = require('../../../../modules/search/middleware/collection') const { setDefaultQuery } = require('../../../middleware') const { getRequestBody } = require('../../../../middleware/collection') const { renderList } = require('./controllers') const { setRequestBody } = require('./middleware') const { transformOrderToListItem } = require('../../transformers') const DEFAULT_QUERY = { sortby: 'created_on:desc', } router.get('/', setDefaultQuery(DEFAULT_QUERY), setRequestBody, getCollection('order', ENTITIES, transformOrderToListItem), renderList, ) router.get('/export', setDefaultQuery(DEFAULT_QUERY), getRequestBody(QUERY_FIELDS), exportCollection('order'), ) module.exports = router
const router = require('express').Router() const { ENTITIES } = require('../../../search/constants') const QUERY_FIELDS = require('../../constants') const { getCollection, exportCollection } = require('../../../../modules/search/middleware/collection') const { setDefaultQuery } = require('../../../middleware') const { getRequestBody } = require('../../../../middleware/collection') const { renderList } = require('./controllers') const { setRequestBody } = require('./middleware') const { transformOrderToListItem } = require('../../transformers') const DEFAULT_QUERY = { sortby: 'created_on:desc', } router.get('/', setDefaultQuery(DEFAULT_QUERY), setRequestBody, getCollection('order', ENTITIES, transformOrderToListItem), renderList, ) router.get('/export', setDefaultQuery(DEFAULT_QUERY), getRequestBody(QUERY_FIELDS), exportCollection('order'), ) module.exports = router
Add correct column types to test data generator.
function generateData(rows) { var data = []; for (var i = 0; i < rows; ++i) { data.push({ "id": "#" + (i + 1), "created_at": new Date().toDateString(), "status": "In progress", "title": "Test unicode €∑ĒŽŌ•ōļķņ© " + i + Math.round(Math.random() * 1000), "count": Math.round(Math.random() * 100) }); } return data; } function getColumns(data) { var firstRow = data[0]; return _.map(firstRow, function (val, key) { var type = _.isNumber(val) ? "int" : "string"; return {name: key, type: type} }); }
function generateData(rows) { var data = []; for (var i = 0; i < rows; ++i) { data.push({ "id": "#" + (i + 1), "created_at": new Date().toDateString(), "status": "In progress", "title": "Test unicode €∑ĒŽŌ•ōļķņ© " + i + Math.round(Math.random() * 1000), "count": Math.round(Math.random() * 100) }); } return data; } function getColumns(data) { var firstRow = data[0]; return _.map(firstRow, function (val, key) { return {name: key, type: "string"} }); }
Remove method for setting custom gav1 libraries PiperOrigin-RevId: 273929000
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.av1; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.util.LibraryLoader; /** Configures and queries the underlying native library. */ public final class Gav1Library { static { ExoPlayerLibraryInfo.registerModule("goog.exo.gav1"); } private static final LibraryLoader LOADER = new LibraryLoader("gav1JNI"); private Gav1Library() {} /** Returns whether the underlying library is available, loading it if necessary. */ public static boolean isAvailable() { return LOADER.isAvailable(); } }
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.av1; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.util.LibraryLoader; /** Configures and queries the underlying native library. */ public final class Gav1Library { static { ExoPlayerLibraryInfo.registerModule("goog.exo.gav1"); } private static final LibraryLoader LOADER = new LibraryLoader("gav1JNI"); private Gav1Library() {} /** * Override the names of the Gav1 native libraries. If an application wishes to call this method, * it must do so before calling any other method defined by this class, and before instantiating a * {@link Libgav1VideoRenderer} instance. * * @param libraries The names of the Gav1 native libraries. */ public static void setLibraries(String... libraries) { LOADER.setLibraries(libraries); } /** Returns whether the underlying library is available, loading it if necessary. */ public static boolean isAvailable() { return LOADER.isAvailable(); } }
Use string instead of class
from django.db import models from django.db.models import signals from django.utils.translation import ugettext_lazy as _ from core.mixins import AuditableMixin class Payment(AuditableMixin, models.Model): invoice = models.ForeignKey( 'core.Invoice', editable=False, on_delete=models.CASCADE, verbose_name=_("Invoice") ) description = models.TextField( blank=True, null=True, verbose_name=_("Description") ) total = models.DecimalField( max_digits=12, decimal_places=2, verbose_name=_("Total") ) class Meta: ordering = ['-date_creation', ] verbose_name = _("Payment") verbose_name_plural = _("Payments") def __str__(self): return "%.2f" % self.total def get_absolute_url(self): return self.parent.get_absolute_url() @property def company(self): return self.parent.company @property def parent(self): return self.invoice def post_save_payment(instance, sender, created, **kwargs): if instance.invoice.is_paid and not instance.company.is_active: instance.company.activate() signals.post_save.connect(post_save_payment, sender=Payment)
from django.db import models from django.db.models import signals from django.utils.translation import ugettext_lazy as _ from core.mixins import AuditableMixin from .invoice import Invoice class Payment(AuditableMixin, models.Model): invoice = models.ForeignKey( Invoice, editable=False, on_delete=models.CASCADE, verbose_name=_("Invoice") ) description = models.TextField( blank=True, null=True, verbose_name=_("Description") ) total = models.DecimalField( max_digits=12, decimal_places=2, verbose_name=_("Total") ) class Meta: ordering = ['-date_creation', ] verbose_name = _("Payment") verbose_name_plural = _("Payments") def __str__(self): return "%.2f" % self.total def get_absolute_url(self): return self.parent.get_absolute_url() @property def company(self): return self.parent.company @property def parent(self): return self.invoice def post_save_payment(instance, sender, created, **kwargs): if instance.invoice.is_payed and not instance.company.is_active: instance.company.activate() signals.post_save.connect(post_save_payment, sender=Payment)
Use config for skipping rule instead
<?php declare(strict_types=1); use Rector\Core\Configuration\Option; use Rector\Laravel\Set\LaravelSetList; use Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector; use Rector\Set\ValueObject\LevelSetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [ __DIR__ . '/config', __DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/views', ]); $parameters->set(Option::SKIP, [ StaticCallOnNonStaticToInstanceCallRector::class => [ __DIR__ . '/tests/ShareTest.php', ], ]); $containerConfigurator->import(LaravelSetList::LARAVEL_60); $containerConfigurator->import(LevelSetList::UP_TO_PHP_74); };
<?php declare(strict_types=1); use Rector\Core\Configuration\Option; use Rector\Laravel\Set\LaravelSetList; use Rector\Set\ValueObject\LevelSetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { // get parameters $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [ __DIR__ . '/config', __DIR__ . '/src', __DIR__ . '/tests', __DIR__ . '/views', ]); // Define what rule sets will be applied $containerConfigurator->import(LaravelSetList::LARAVEL_60); $containerConfigurator->import(LevelSetList::UP_TO_PHP_74); };
Add documentation for create invitation
//Invitations.js: Client for the Zendesk NPS API. const util = require('util'), Client = require('../client').Client; //defaultgroups = require('../helpers').defaultgroups; const Invitations = (exports.Invitations = function(options) { this.jsonAPINames = ['agent activity']; Client.call(this, options); }); // Inherit from Client base object util.inherits(Invitations, Client); // ######################################################## Invitations // ====================================== Showing Invitations Invitations.prototype.list = function({ surveyId }, cb) { this.request('GET', ['nps', 'surveys', surveyId, 'invitations'], cb); }; // ====================================== Showing Invitation by ID Invitations.prototype.show = function({ surveyId, invitationId }, cb) { this.request( 'GET', ['nps', 'surveys', surveyId, 'invitations', invitationId], cb ); }; /** * Create invitation https://developer.zendesk.com/rest_api/docs/nps-api/nps_invitations * * @param {object} params * @param {string} params.surveyId * @param {{ * invitation: { * recipients: { * name: string, * email: string, * language: string * }[] * } * }} params.data * @param {*} cb */ Invitations.prototype.create = function({ surveyId, data }, cb) { this.request('POST', ['nps', 'surveys', surveyId, 'invitations'], data, cb); };
//Invitations.js: Client for the Zendesk NPS API. const util = require('util'), Client = require('../client').Client; //defaultgroups = require('../helpers').defaultgroups; const Invitations = (exports.Invitations = function(options) { this.jsonAPINames = ['agent activity']; Client.call(this, options); }); // Inherit from Client base object util.inherits(Invitations, Client); // ######################################################## Invitations // ====================================== Showing Invitations Invitations.prototype.list = function({ surveyId }, cb) { this.request('GET', ['nps', 'surveys', surveyId, 'invitations'], cb); }; // ====================================== Showing Invitation by ID Invitations.prototype.show = function({ surveyId, invitationId }, cb) { this.request( 'GET', ['nps', 'surveys', surveyId, 'invitations', invitationId], cb ); }; // ====================================== Create Invitation Invitations.prototype.create = function({ surveyId, data }, cb) { this.request('POST', ['nps', 'surveys', surveyId, 'invitations'], data, cb); };
Remove extra createBuildOptions for now
var join = require("path").join; var console = require("./utils").console; var fs = require("fs-promise"); var zip = require("./zip"); var all = require("when").all; var tmp = require('./tmp'); var bootstrapSrc = join(__dirname, "../data/bootstrap.js"); /** * Takes a manifest object (from package.json) and build options * object and zipz up the current directory into a XPI, copying * over default `install.rdf` and `bootstrap.js` if needed * and not yet defined. Returns a promise that resolves * upon completion. * * @param {Object} manifest * @param {Object} options * @return {Promise} */ function xpi (manifest, options) { var cwd = process.cwd(); var xpiName = (manifest.name || "jetpack") + ".xpi"; var xpiPath = join(cwd, xpiName); return doFinalZip(cwd, xpiPath); } module.exports = xpi; function doFinalZip(cwd, xpiPath) { return zip(cwd, xpiPath).then(function () { return xpiPath; }); }
var join = require("path").join; var console = require("./utils").console; var fs = require("fs-promise"); var zip = require("./zip"); var all = require("when").all; var tmp = require('./tmp'); var bootstrapSrc = join(__dirname, "../data/bootstrap.js"); /** * Takes a manifest object (from package.json) and build options * object and zipz up the current directory into a XPI, copying * over default `install.rdf` and `bootstrap.js` if needed * and not yet defined. Returns a promise that resolves * upon completion. * * @param {Object} manifest * @param {Object} options * @return {Promise} */ function xpi (manifest, options) { var cwd = process.cwd(); var xpiName = (manifest.name || "jetpack") + ".xpi"; var xpiPath = join(cwd, xpiName); var buildOptions = createBuildOptions(options); return doFinalZip(cwd, xpiPath); } module.exports = xpi; function doFinalZip(cwd, xpiPath) { return zip(cwd, xpiPath).then(function () { return xpiPath; }); }
Use assertEquals() instead of assertStringEqualsFile() in order to compare XML documents with C14N
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\TextUI\XmlConfiguration; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Xml; final class MigrationTest extends TestCase { /** * @testdox Migrates PHPUnit 9.2 configuration to PHPUnit 9.3 */ public function testMigratesPhpUnit92ConfigurationToPhpUnit93(): void { $this->assertEquals( Xml::loadFile(__DIR__ . '/../../_files/XmlConfigurationMigration/output-9.3.xml'), Xml::load( (new Migrator)->migrate( __DIR__ . '/../../_files/XmlConfigurationMigration/input-9.2.xml' ) ) ); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\TextUI\XmlConfiguration; use PHPUnit\Framework\TestCase; final class MigrationTest extends TestCase { /** * @testdox Migrates PHPUnit 9.2 configuration to PHPUnit 9.3 */ public function testMigratesPhpUnit92ConfigurationToPhpUnit93(): void { $this->assertStringEqualsFile( __DIR__ . '/../../_files/XmlConfigurationMigration/output-9.3.xml', (new Migrator)->migrate( __DIR__ . '/../../_files/XmlConfigurationMigration/input-9.2.xml' ) ); } }
Fix erroneous import in ListedCFD class.
import ListedDerivative from '../ListedDerivative/listedDerivative' class ListedContractForDifference extends ListedDerivative { constructor({ assetManagerId, assetId, assetClass='ListedContractForDifference', fungible, assetIssuerId, assetStatus='Active', countryId, venueId, currency, issueDate, maturityDate, description='', clientId, comments, links, references, createdBy, updatedBy, createdTime, updatedTime, version }) { super({ assetManagerId, assetId, assetClass, fungible, assetIssuerId, assetStatus, countryId, venueId, currency, issueDate, maturityDate, description, clientId, comments, links, references, createdBy, updatedBy, createdTime, updatedTime, version }) } } export default ListedContractForDifference
import ListedDerivative from '../../ListedDerivative/listedDerivative' class ListedContractForDifference extends ListedDerivative { constructor({ assetManagerId, assetId, assetClass='ListedContractForDifference', fungible, assetIssuerId, assetStatus='Active', countryId, venueId, currency, issueDate, maturityDate, description='', clientId, comments, links, references, createdBy, updatedBy, createdTime, updatedTime, version }) { super({ assetManagerId, assetId, assetClass, fungible, assetIssuerId, assetStatus, countryId, venueId, currency, issueDate, maturityDate, description, clientId, comments, links, references, createdBy, updatedBy, createdTime, updatedTime, version }) } } export default ListedContractForDifference
Disable redirecting git output in _get_version
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() return version __version__ = _get_version()
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args, stderr=devnull) version = output.decode("utf-8").strip() return version __version__ = _get_version()
Set write deadline in client/agent connections
package remotedialer import ( "io" "sync" "time" "github.com/gorilla/websocket" ) type wsConn struct { sync.Mutex conn *websocket.Conn } func newWSConn(conn *websocket.Conn) *wsConn { w := &wsConn{ conn: conn, } w.setupDeadline() return w } func (w *wsConn) WriteMessage(messageType int, data []byte) error { w.Lock() defer w.Unlock() w.conn.SetWriteDeadline(time.Now().Add(PingWaitDuration)) return w.conn.WriteMessage(messageType, data) } func (w *wsConn) NextReader() (int, io.Reader, error) { return w.conn.NextReader() } func (w *wsConn) setupDeadline() { w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) w.conn.SetPingHandler(func(string) error { w.Lock() w.conn.WriteControl(websocket.PongMessage, []byte(""), time.Now().Add(time.Second)) w.Unlock() return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) }) w.conn.SetPongHandler(func(string) error { return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) }) }
package remotedialer import ( "io" "sync" "time" "github.com/gorilla/websocket" ) type wsConn struct { sync.Mutex conn *websocket.Conn } func newWSConn(conn *websocket.Conn) *wsConn { w := &wsConn{ conn: conn, } w.setupDeadline() return w } func (w *wsConn) WriteMessage(messageType int, data []byte) error { w.Lock() defer w.Unlock() return w.conn.WriteMessage(messageType, data) } func (w *wsConn) NextReader() (int, io.Reader, error) { return w.conn.NextReader() } func (w *wsConn) setupDeadline() { w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) w.conn.SetPingHandler(func(string) error { w.Lock() w.conn.WriteControl(websocket.PongMessage, []byte(""), time.Now().Add(time.Second)) w.Unlock() return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) }) w.conn.SetPongHandler(func(string) error { return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration)) }) }
test: Use log level of INFO for karma
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'test/components/angular/angular.js', 'test/components/angular-mocks/angular-mocks.js', 'src/scripts/*.js', 'src/scripts/**/*.js', 'test/spec/**/*.js' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress || growl reporters = ['progress']; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = true; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['Chrome']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 5000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'test/components/angular/angular.js', 'test/components/angular-mocks/angular-mocks.js', 'src/scripts/*.js', 'src/scripts/**/*.js', 'test/spec/**/*.js' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress || growl reporters = ['progress']; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_DEBUG; // enable / disable watching file and executing tests whenever any file changes autoWatch = true; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['Chrome']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 5000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
Replace /public with /posts in default tabs
const nest = require('depnest') const merge = require('lodash/merge') const fs = require('fs') const { join } = require('path') exports.gives = nest('app.sync.initialise') exports.needs = nest({ 'settings.sync.set': 'first', 'settings.sync.get': 'first' }) const defaults = { patchbay: { defaultTabs: ['/posts', '/inbox', '/notifications'], accessibility: { invert: false, saturation: 100, brightness: 100, contrast: 100 }, customStyles: defaultStyles() }, filter: { exclude: { channels: '' }, only: { peopleIFollow: false }, show: { post: true, vote: false, // a.k.a. like about: true, contact: false, channel: false, pub: false, chess: false } } } exports.create = function (api) { return nest('app.sync.initialise', initialiseSettings) function initialiseSettings () { const { get, set } = api.settings.sync const settings = merge({}, defaults, get()) settings.filter.defaults = defaults.filter set(settings) } } function defaultStyles () { // TODO add a nice little helper README / comments const path = join(__dirname, '../../styles/mcss/app-theme-vars.mcss') const styles = fs.readFileSync(path, 'utf8') return styles }
const nest = require('depnest') const merge = require('lodash/merge') const fs = require('fs') const { join } = require('path') exports.gives = nest('app.sync.initialise') exports.needs = nest({ 'settings.sync.set': 'first', 'settings.sync.get': 'first' }) const defaults = { patchbay: { defaultTabs: ['/public', '/inbox', '/notifications'], accessibility: { invert: false, saturation: 100, brightness: 100, contrast: 100 }, customStyles: defaultStyles() }, filter: { exclude: { channels: '' }, only: { peopleIFollow: false }, show: { post: true, vote: false, // a.k.a. like about: true, contact: false, channel: false, pub: false, chess: false } } } exports.create = function (api) { return nest('app.sync.initialise', initialiseSettings) function initialiseSettings () { const { get, set } = api.settings.sync const settings = merge({}, defaults, get()) settings.filter.defaults = defaults.filter set(settings) } } function defaultStyles () { // TODO add a nice little helper README / comments const path = join(__dirname, '../../styles/mcss/app-theme-vars.mcss') const styles = fs.readFileSync(path, 'utf8') return styles }
Test commint 2 - yun
package esiptestbed.mudrod.metadata.pre; import java.util.Map; import esiptestbed.mudrod.discoveryengine.DiscoveryStepAbstract; import esiptestbed.mudrod.driver.ESDriver; /** * Say sth * * * * */ public class Example extends DiscoveryStepAbstract { public Example(Map<String, String> config, ESDriver es) { super(config, es); // TODO Auto-generated constructor stub } @Override public void execute() { // TODO Auto-generated method stub System.out.println("*****************Step 1: Example******************"); startTime=System.currentTimeMillis(); es.createBulkProcesser(); /* Do something */ es.destroyBulkProcessor(); endTime=System.currentTimeMillis(); System.out.println("*****************Example ends******************Took " + (endTime-startTime)/1000+"s"); } }
package esiptestbed.mudrod.metadata.pre; import java.util.Map; import esiptestbed.mudrod.discoveryengine.DiscoveryStepAbstract; import esiptestbed.mudrod.driver.ESDriver; /** * Say sth * * * * */ public class Example extends DiscoveryStepAbstract { public Example(Map<String, String> config, ESDriver es) { super(config, es); // TODO Auto-generated constructor stub } @Override public void execute() { // TODO Auto-generated method stub System.out.println("*****************Step 1: Example******************"); startTime=System.currentTimeMillis(); es.createBulkProcesser(); /* Do something */ //test 1 es.destroyBulkProcessor(); endTime=System.currentTimeMillis(); System.out.println("*****************Example ends******************Took " + (endTime-startTime)/1000+"s"); } }
fix: Fix the shelves, which are not displaying all the books There was a problem displaying more than three books inside a shelf at the same time. It has been fixed adding a style from the Bulma library.
import React, {Component} from 'react' import { Link } from 'react-router-dom'; import PropTypes from 'prop-types' import escapeRegExp from 'escape-string-regexp' import sortBy from 'sort-by' import Book from './Book' class BooksOverview extends Component { static propTypes = { books: PropTypes.array.isRequired, shelf: PropTypes.string.isRequired, title: PropTypes.string.isRequired, subtitle: PropTypes.string.isRequired, moveTo: PropTypes.func.isRequired } render() { const { books, shelf, title, subtitle, moveTo } = this.props; return ( <section className="section"> <div className="container"> <h1 className="title"> {title} </h1> <h2 className="subtitle"> {subtitle} </h2> <div className="content"> <div className="columns is-multiline"> {books.map((book) => ( <div key={book.id} className="column is-4"> <Book book={book} moveTo={moveTo}/> </div> ))} </div> </div> </div> </section> ) } } export default BooksOverview
import React, {Component} from 'react' import { Link } from 'react-router-dom'; import PropTypes from 'prop-types' import escapeRegExp from 'escape-string-regexp' import sortBy from 'sort-by' import Book from './Book' class BooksOverview extends Component { static propTypes = { books: PropTypes.array.isRequired, shelf: PropTypes.string.isRequired, title: PropTypes.string.isRequired, subtitle: PropTypes.string.isRequired, moveTo: PropTypes.func.isRequired } render() { const { books, shelf, title, subtitle, moveTo } = this.props; return ( <section className="section"> <div className="container"> <h1 className="title"> {title} </h1> <h2 className="subtitle"> {subtitle} </h2> <div className="content"> <div className="columns"> {books.map((book) => ( <div key={book.id} className="column is-4"> <Book book={book} moveTo={moveTo}/> </div> ))} </div> </div> </div> </section> ) } } export default BooksOverview
Add typehints for ServiceRegistryInterface::get() calls
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Taxation\Calculator; use Sylius\Component\Registry\ServiceRegistry; use Sylius\Component\Taxation\Model\TaxRateInterface; /** * Delegating calculator. * It uses proper calculator to calculate the amount of tax. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ class DelegatingCalculator implements CalculatorInterface { /** * @var ServiceRegistry */ private $calculatorsRegistry; public function __construct(ServiceRegistry $serviceRegistry) { $this->calculatorsRegistry = $serviceRegistry; } /** * {@inheritdoc} */ public function calculate($base, TaxRateInterface $rate) { /** @var CalculatorInterface $calculator */ $calculator = $this->calculatorsRegistry->get($rate->getCalculator()); return $calculator->calculate($base, $rate); } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Taxation\Calculator; use Sylius\Component\Registry\ServiceRegistry; use Sylius\Component\Taxation\Model\TaxRateInterface; /** * Delegating calculator. * It uses proper calculator to calculate the amount of tax. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ class DelegatingCalculator implements CalculatorInterface { /** * @var ServiceRegistry */ private $calculatorsRegistry; public function __construct(ServiceRegistry $serviceRegistry) { $this->calculatorsRegistry = $serviceRegistry; } /** * {@inheritdoc} */ public function calculate($base, TaxRateInterface $rate) { $calculator = $this->calculatorsRegistry->get($rate->getCalculator()); return $calculator->calculate($base, $rate); } }
Fix turnserver auth timestamp generation
package server import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "time" ) type ICEAuthServer struct { URLs []string `json:"urls"` Username string `json:"username,omitempty"` Credential string `json:"credential,omitempty"` } func GetICEAuthServers(servers []ICEServer) (result []ICEAuthServer) { for _, server := range servers { result = append(result, newICEServer(server)) } return } func newICEServer(server ICEServer) ICEAuthServer { switch server.AuthType { case AuthTypeSecret: return getICEStaticAuthSecretCredentials(server) default: return ICEAuthServer{URLs: server.URLs} } } func getICEStaticAuthSecretCredentials(server ICEServer) ICEAuthServer { timestamp := time.Now().Unix() + 24*3600 username := fmt.Sprintf("%d:%s", timestamp, server.AuthSecret.Username) h := hmac.New(sha1.New, []byte(server.AuthSecret.Secret)) h.Write([]byte(username)) credential := base64.StdEncoding.EncodeToString(h.Sum(nil)) return ICEAuthServer{ URLs: server.URLs, Username: username, Credential: credential, } }
package server import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "time" ) type ICEAuthServer struct { URLs []string `json:"urls"` Username string `json:"username,omitempty"` Credential string `json:"credential,omitempty"` } func GetICEAuthServers(servers []ICEServer) (result []ICEAuthServer) { for _, server := range servers { result = append(result, newICEServer(server)) } return } func newICEServer(server ICEServer) ICEAuthServer { switch server.AuthType { case AuthTypeSecret: return getICEStaticAuthSecretCredentials(server) default: return ICEAuthServer{URLs: server.URLs} } } func getICEStaticAuthSecretCredentials(server ICEServer) ICEAuthServer { timestamp := time.Now().UnixNano() / 1_000_000 username := fmt.Sprintf("%d:%s", timestamp, server.AuthSecret.Username) h := hmac.New(sha1.New, []byte(server.AuthSecret.Secret)) h.Write([]byte(username)) credential := base64.StdEncoding.EncodeToString(h.Sum(nil)) return ICEAuthServer{ URLs: server.URLs, Username: username, Credential: credential, } }
Add missing field in 'action' for 'Message' object
package com.vk.api.sdk.objects.messages; import com.google.gson.annotations.SerializedName; /** * Message action type */ public enum Action { @SerializedName("chat_photo_update") CHAT_PHOTO_UPDATE("chat_photo_update"), @SerializedName("chat_photo_remove") CHAT_PHOTO_REMOVE("chat_photo_remove"), @SerializedName("chat_create") CHAT_CREATE("chat_create"), @SerializedName("chat_title_update") CHAT_TITLE_UPDATE("chat_title_update"), @SerializedName("chat_invite_user") CHAT_INVITE_USER("chat_invite_user"), @SerializedName("chat_kick_user") CHAT_KICK_USER("chat_kick_user"), @SerializedName("chat_pin_message") CHAT_PIN_MESSAGE("chat_pin_message"), @SerializedName("chat_unpin_message") CHAT_UNPIN_MESSAGE("chat_unpin_message"), @SerializedName("chat_invite_user_by_link") CHAT_INVITE_USER_BY_LINK("chat_invite_user_by_link"); private final String value; Action(String value) { this.value = value; } public String getValue() { return value; } }
package com.vk.api.sdk.objects.messages; import com.google.gson.annotations.SerializedName; /** * Message action type */ public enum Action { @SerializedName("chat_photo_update") CHAT_PHOTO_UPDATE("chat_photo_update"), @SerializedName("chat_photo_remove") CHAT_PHOTO_REMOVE("chat_photo_remove"), @SerializedName("chat_create") CHAT_CREATE("chat_create"), @SerializedName("chat_title_update") CHAT_TITLE_UPDATE("chat_title_update"), @SerializedName("chat_invite_user") CHAT_INVITE_USER("chat_invite_user"), @SerializedName("chat_kick_user") CHAT_KICK_USER("chat_kick_user"); private final String value; Action(String value) { this.value = value; } public String getValue() { return value; } }
Add full path for public directory
var express = require('express'), app = express(), bodyParser = require('body-parser'), serveStatic = require('serve-static'), radiodan = require('radiodan-client').create(), player = radiodan.player.get('main'), statusLED = radiodan.RGBLED.get('power'), apiRoutes = require('./lib/routes'), port = process.env.PORT || 5000; app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({extended: true})); app.use(serveStatic(__dirname + '/public')); app.use('/api', apiRoutes(express.Router(), player, statusLED)); app.listen(port); console.log('Listening on http://127.0.0.1:'+port);
var express = require('express'), app = express(), bodyParser = require('body-parser'), serveStatic = require('serve-static'), radiodan = require('radiodan-client').create(), player = radiodan.player.get('main'), statusLED = radiodan.RGBLED.get('power'), apiRoutes = require('./lib/routes'), port = process.env.PORT || 5000; app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({extended: true})); app.use(serveStatic('./public')); app.use('/api', apiRoutes(express.Router(), player, statusLED)); app.listen(port); console.log('Listening on http://127.0.0.1:'+port);
Enable copy on cell output
'use babel'; import React from 'react'; import {Transformime} from 'transformime'; import { StreamTransformer, TracebackTransformer, MarkdownTransformer, } from 'transformime-jupyter-transformers'; export default class DisplayArea extends React.Component { constructor(props) { super(props); this.transformer = new Transformime(); this.transformer.transformers.push(new StreamTransformer()); this.transformer.transformers.push(new TracebackTransformer()); this.transformer.transformers.push(new MarkdownTransformer()); } componentDidMount() { this.setupDOM(); } // transformime-generated HTML is in outputs // after every render, fill our element with that HTML componentDidUpdate() { let outputs = this.props.data.get('outputs'); let outputHTML = outputs.join(''); this.el.innerHTML = outputHTML; } render() { return ( <div className="cell-display-area native-key-bindings" tabIndex="-1"> </div> ); } setupDOM() { let container = React.findDOMNode(this); let outputNode = document.createElement('div'); outputNode.style.backgroundColor = 'white'; this.shadow = container.createShadowRoot(); this.shadow.appendChild(outputNode); this.document = this.shadow.ownerDocument; this.el = outputNode; } }
'use babel'; import React from 'react'; import {Transformime} from 'transformime'; import { StreamTransformer, TracebackTransformer, MarkdownTransformer, } from 'transformime-jupyter-transformers'; export default class DisplayArea extends React.Component { constructor(props) { super(props); this.transformer = new Transformime(); this.transformer.transformers.push(new StreamTransformer()); this.transformer.transformers.push(new TracebackTransformer()); this.transformer.transformers.push(new MarkdownTransformer()); } componentDidMount() { this.setupDOM(); } // transformime-generated HTML is in outputs // after every render, fill our element with that HTML componentDidUpdate() { let outputs = this.props.data.get('outputs'); let outputHTML = outputs.join(''); this.el.innerHTML = outputHTML; } render() { return ( <div className="cell-display-area"> </div> ); } setupDOM() { let container = React.findDOMNode(this); let outputNode = document.createElement('div'); outputNode.style.backgroundColor = 'white'; this.shadow = container.createShadowRoot(); this.shadow.appendChild(outputNode); this.document = this.shadow.ownerDocument; this.el = outputNode; } }
Add bindingKey to detached counters conditions
<?php namespace Muffin\Hits\Model\Behavior\Strategy; use Cake\Database\Expression\QueryExpression; use Cake\ORM\Table; use Cake\ORM\TableRegistry; class DefaultStrategy extends AbstractStrategy { protected $_conditions; protected $_offset; public function __construct(array $conditions = [], $offset = 1) { $this->_conditions = $conditions; $this->$_offset = 1; } public function increment(Table $table, $counter, $identifier) { list($alias, $field) = $this->_counterSplit($counter); $key = $table->primaryKey(); if ($table->alias() !== $alias) { $key = $table->$alias->bindingKey(); $table = TableRegistry::get($alias); } $expression = new QueryExpression("$field = $field + " . $this->_offset); $conditions = [$key => $identifier] + $this->_conditions; return $table->updateAll($expression, $conditions); } }
<?php namespace Muffin\Hits\Model\Behavior\Strategy; use Cake\Database\Expression\QueryExpression; use Cake\ORM\Table; use Cake\ORM\TableRegistry; class DefaultStrategy extends AbstractStrategy { protected $_conditions; protected $_offset; public function __construct(array $conditions = [], $offset = 1) { $this->_conditions = $conditions; $this->$_offset = 1; } public function increment(Table $table, $counter, $identifier) { list($alias, $field) = $this->_counterSplit($counter); $conditions = [$table->aliasField($table->primaryKey()) => $identifier]; if ($table->alias() !== $alias) { $conditions = []; $table = TableRegistry::get($alias); } $expression = new QueryExpression("$field = $field + " . $this->_offset); return $table->updateAll($expression, $conditions + $this->_conditions); } }
Set escalation threshold to null by default
GLClient.controller('AdminContextsCtrl', ['$scope', '$rootScope', 'localization', 'AdminContexts', function($scope, $rootScope, localization, AdminContexts) { $scope.new_context = function() { var context = new AdminContexts; //context.name[localization.selected_language] = $scope.new_context_name; context.name = $scope.new_context_name; context.description = ''; context.fields = []; context.languages = []; context.receivers = []; context.escalation_threshold = null; context.file_max_download = 42; context.tip_max_access = 42; context.selectable_receiver = true; context.tip_timetolive = 42; context.$save(function(created_context){ $scope.adminContexts.push(created_context); }); }; // XXX this is *very* hackish. $scope.editFields = function(fields) { $rootScope.fieldEditor = true; $rootScope.fieldsToEdit = fields; }; $rootScope.closeEditor = function() { $rootScope.fieldEditor = false; }; $scope.delete_context = function(context) { var idx = _.indexOf($scope.adminContexts, context); context.$delete(function(){ $scope.adminContexts.splice(idx, 1); }); } }]);
GLClient.controller('AdminContextsCtrl', ['$scope', '$rootScope', 'localization', 'AdminContexts', function($scope, $rootScope, localization, AdminContexts) { $scope.new_context = function() { var context = new AdminContexts; //context.name[localization.selected_language] = $scope.new_context_name; context.name = $scope.new_context_name; context.description = ''; context.fields = []; context.languages = []; context.receivers = []; context.escalation_threshold = 42; context.file_max_download = 42; context.tip_max_access = 42; context.selectable_receiver = true; context.tip_timetolive = 42; context.$save(function(created_context){ $scope.adminContexts.push(created_context); }); }; // XXX this is *very* hackish. $scope.editFields = function(fields) { $rootScope.fieldEditor = true; $rootScope.fieldsToEdit = fields; }; $rootScope.closeEditor = function() { $rootScope.fieldEditor = false; }; $scope.delete_context = function(context) { var idx = _.indexOf($scope.adminContexts, context); context.$delete(function(){ $scope.adminContexts.splice(idx, 1); }); } }]);
Add utility for address change functionality testing
#!/usr/bin/python """Looks for sensor with ADDRESS1 and changes it's address to ADDRESS2 then changes it back to ADDRESS1""" import minimalmodbus import serial from time import sleep ADDRESS1 = 1 ADDRESS2 = 2 minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True minimalmodbus.PARITY=serial.PARITY_NONE minimalmodbus.STOPBITS = 2 minimalmodbus.BAUDRATE=19200 minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1) sensor.debug=True print(("reading address: ") + str(sensor.read_register(0, functioncode=3))) print("writing new address: " + str(ADDRESS2)) sensor.write_register(0, value=ADDRESS2, functioncode=6) sleep(0.2) sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS2) print("reading address from holding register: ") print(sensor.read_register(0, functioncode=3)) print("writing new address: " + str(ADDRESS1)) sensor.write_register(0, value=ADDRESS1, functioncode=6) sleep(0.2) sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1) print("reading address from holding register: ") print(sensor.read_register(0, functioncode=3))
#!/usr/bin/python import minimalmodbus from time import sleep ADDRESS1 = 1 ADDRESS2 = 2 minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1) print("writing new address: " + str(ADDRESS2)) sensor.write_register(0, value=ADDRESS2, functioncode=6) sleep(0.2) sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS2) print("reading address from holding register: ") print(sensor.read_register(0, functioncode=3)) print("writing new address: " + str(ADDRESS1)) sensor.write_register(0, value=ADDRESS1, functioncode=6) sleep(0.2) sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1) print("reading address from holding register: ") print(sensor.read_register(0, functioncode=3))
Fix sitemap include (to work on case sensitive linux)
var SiteMap = require('SiteMap.js').SiteMap; var Doc = require('ngdoc.js').Doc; describe('sitemap', function(){ it('should render empty sitemap', function(){ var map = new SiteMap([]); expect(map.render()).toEqual([ '<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', '</urlset>', ''].join('\n')); }); it('should render ngdoc url', function(){ var map = new SiteMap([new Doc({name: 'a.b.c<>\'"&'})]); expect(map.render()).toContain([ ' <url>', '<loc>http://docs.angularjs.org/#!a.b.c&lt;&gt;&apos;&quot;&amp;</loc>', '<changefreq>weekly</changefreq>', '</url>'].join('')); }); });
var SiteMap = require('sitemap.js').SiteMap; var Doc = require('ngdoc.js').Doc; describe('sitemap', function(){ it('should render empty sitemap', function(){ var map = new SiteMap([]); expect(map.render()).toEqual([ '<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', '</urlset>', ''].join('\n')); }); it('should render ngdoc url', function(){ var map = new SiteMap([new Doc({name: 'a.b.c<>\'"&'})]); expect(map.render()).toContain([ ' <url>', '<loc>http://docs.angularjs.org/#!a.b.c&lt;&gt;&apos;&quot;&amp;</loc>', '<changefreq>weekly</changefreq>', '</url>'].join('')); }); });
Fix remove echoPermission option in PopoverModel
// ---------------------------------------------------------------- // Popover Class class PopoverModel extends CommonModel { constructor({ name = 'Popover', selector = null, help = 'popover', trigger = 'hover' } = {}) { super({ name: name }); this.NAME = name; this.SELECTOR = selector; this.HELP = help; this.TRIGGER = trigger; } } class PopoverView extends CommonView { constructor(_model = new PopoverModel()) { super(_model); this.setPopover(); } setPopover() { if (this.model.SELECTOR != null) { $(this.model.SELECTOR).attr('data-toggle', 'popover'); $(this.model.SELECTOR).attr('data-content', this.model.HELP); $(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER); $(this.model.SELECTOR).popover(); } } } // ---------------------------------------------------------------- // Controllers class PopoverController extends CommonController { constructor(_obj) { super({ name: 'Popover Controller' }); this.model = new PopoverModel(_obj); this.view = new PopoverView(this.model); } }
// ---------------------------------------------------------------- // Popover Class class PopoverModel extends CommonModel { constructor({ name = 'Popover', selector = null, help = 'popover', trigger = 'hover' } = {}) { super({ name: name, echoPermission: false }); this.NAME = name; this.SELECTOR = selector; this.HELP = help; this.TRIGGER = trigger; } } class PopoverView extends CommonView { constructor(_model = new PopoverModel()) { super(_model); this.setPopover(); } setPopover() { if (this.model.SELECTOR != null) { $(this.model.SELECTOR).attr('data-toggle', 'popover'); $(this.model.SELECTOR).attr('data-content', this.model.HELP); $(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER); $(this.model.SELECTOR).popover(); } } } // ---------------------------------------------------------------- // Controllers class PopoverController extends CommonController { constructor(_obj) { super({ name: 'Popover Controller' }); this.model = new PopoverModel(_obj); this.view = new PopoverView(this.model); } }
Accumulate ancestor nodes during walk
'use strict'; // MODULES // var walk = require( 'acorn/dist/walk.js' ).fullAncestor; var contains = require( '@stdlib/assert/contains' ); var types = require( './node_types.js' ); // MAIN // /** * Flattens an AST. * * @private * @param {Node} ast - AST node * @returns {Array} flattened AST */ function flatten( ast ) { var out = []; walk( ast, visit ); return out; /** * Callback invoked upon visiting an AST node. * * @private * @param {Node} node - AST node * @param {*} state - state * @param {Array<Node>} ancestors - ancestor nodes */ function visit( node ) { if ( node !== ast && contains( types, node.type ) ) { out.push( node ); } } // end FUNCTION visit() } // end FUNCTION flatten() // EXPORTS // module.exports = flatten;
'use strict'; // MODULES // var walk = require( 'acorn/dist/walk.js' ).full; var contains = require( '@stdlib/assert/contains' ); var types = require( './node_types.js' ); // MAIN // /** * Flattens an AST. * * @private * @param {Node} ast - AST node * @returns {Array} flattened AST */ function flatten( ast ) { var out = []; walk( ast, visit ); return out; /** * Callback invoked upon visiting an AST node. * * @private * @param {Node} node - AST node * @param {*} state - state * @param {string} type - node type */ function visit( node, state, type ) { if ( node !== ast && contains( types, type ) ) { out.push( node ); } } // end FUNCTION visit() } // end FUNCTION flatten() // EXPORTS // module.exports = flatten;
Set some fields as tranlate
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmJobPosition(models.Model): _name = 'crm.job_position' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Job position" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.job_position') children = fields.One2many(comodel_name='crm.job_position', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmJobPosition(models.Model): _name = 'crm.job_position' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Job position" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.job_position') children = fields.One2many(comodel_name='crm.job_position', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Remove copyright notice during preprocessing
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) # Ignore notice, since we don't use it for analysing the data text = text[81:] token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
import os import pickle def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables): """ Preprocess Text Data """ text = load_data(dataset_path) token_dict = token_lookup() for key, token in token_dict.items(): text = text.replace(key, ' {} '.format(token)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables(text) int_text = [vocab_to_int[word] for word in text] pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb')) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open('preprocess.p', mode='rb')) def save_params(params): """ Save parameters to file """ pickle.dump(params, open('params.p', 'wb')) def load_params(): """ Load parameters from file """ return pickle.load(open('params.p', mode='rb'))
Change directory call for simulator
'use strict'; const fs = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const { BrowserWindow } = require('electron'); const EXPORT_FILES = 'export_files'; const exportedDir = path.join(__dirname, '../', EXPORT_FILES); const simulator = root => { const WIDTH = 800; const HEIGHT = 600; let child = spawn( 'npm', ['start'], { cwd: exportedDir, stdio: 'inherit', env: process.env } ) setTimeout(()=>{ let child = new BrowserWindow({ width: WIDTH, height: HEIGHT }); child.loadURL('http://localhost:8080/'); child.toggleDevTools(); }, 5000) }; module.exports = simulator;
'use strict'; const fs = require('fs'); const path = require('path'); const { spawn } = require('child_process'); const { BrowserWindow } = require('electron'); const simulator = root => { const WIDTH = 800; const HEIGHT = 600; //Deserialize project info from projInfo file, contains path to index.html and presence of webpack among other things // const projInfo = JSON.parse(fs.readFileSync(path.join(__dirname, '../lib/projInfo.js'))); let child = spawn( 'npm', ['start'], { cwd: '/Users/jyamamoto/_personal/Fermionjs/app/export_files', stdio: 'inherit', env: process.env } ) setTimeout(()=>{ let child = new BrowserWindow({ width: WIDTH, height: HEIGHT }); child.loadURL('http://localhost:8080/'); child.toggleDevTools(); }, 5000) }; module.exports = simulator;
Update "Basic Instructions" after feed change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" language = "en" url = "http://www.basicinstructions.net/" start_date = "2006-07-01" rights = "Scott Meyer" class Crawler(CrawlerBase): history_capable_days = 100 schedule = "Tu,Th,Su" time_zone = "US/Eastern" def crawl(self, pub_date): feed = self.parse_feed( "http://basicinstructions.net/basic-instructions/rss.xml" ) for entry in feed.for_date(pub_date): url = entry.summary.src("img") title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" language = "en" url = "http://www.basicinstructions.net/" start_date = "2006-07-01" rights = "Scott Meyer" class Crawler(CrawlerBase): history_capable_days = 100 schedule = "Tu,Th,Su" time_zone = "US/Eastern" def crawl(self, pub_date): feed = self.parse_feed( "http://basicinstructions.net/basic-instructions/rss.xml" ) for entry in feed.for_date(pub_date): url = entry.summary.src('img[src*="/storage/"][src*=".gif"]') title = entry.title return CrawlerImage(url, title)
Fix json loading, fix capital checker
"""Handle incoming spam messages.""" from ..handler import Handler import logging class SpamHandler(Handler): """Spam handler.""" MAX_SCORE = 16 MAX_EMOTES = 6 ALLOW_LINKS = False def __init__(self): self.logger = logging.getLogger(__name__) def on_message(self, packet): """Handle message events.""" built_message = "" for chunk in packet: if chunk["type"] == "text": built_message += chunk["text"] exceeds_caps = self.check_caps(built_message) contains_emotes = self.check_emotes(packet) has_links = self.check_links(packet) if exceeds_caps or contains_emotes or has_links: return True else: return False def check_links(self, packet): return not self.ALLOW_LINKS and any(chunk["type"] == "link" for chunk in packet) def check_emotes(self, packet): return sum(chunk["type"] == "emote" for chunk in packet) > self.MAX_EMOTES def check_caps(self, message): return sum(char.isupper() - char.islower() for char in message) > self.MAX_SCORE
"""Handle incoming spam messages.""" from ..handler import Handler import logging import json class SpamHandler(Handler): """Spam handler.""" MAX_SCORE = 16 MAX_EMOTES = 6 ALLOW_LINKS = False def __init__(self): self.logger = logging.getLogger(__name__) def on_message(self, packet): """Handle message events.""" packet = json.loads(packet) # exceeds_caps = self.check_caps(''.join(chunk for chunk in packet if chunk["type"] == "text")) contains_emotes = self.check_emotes(packet) has_links = self.check_links(packet) if contains_emotes or has_links: return True else: return False def check_links(self, packet): return not self.ALLOW_LINKS and any(chunk["type"] == "link" for chunk in packet) def check_emotes(self, packet): return sum(chunk["type"] == "emote" for chunk in packet) > self.MAX_EMOTES def check_caps(self, message): return sum(char.isupper() - char.islower() for char in message["text"]) > self.MAX_SCORE
Use the old django test runner We aren't ready to switch to the new unittest discovery in django.
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '', }, } SECRET_KEY = "widgy_tests_secret_key" # To speed up tests under SQLite we use the MD5 hasher as the default one. # This should not be needed under other databases, as the relative speedup # is only marginal there. PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', ) SOUTH_TESTS_MIGRATE = False URLCONF_INCLUDE_CHOICES = tuple() TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '', }, } SECRET_KEY = "widgy_tests_secret_key" # To speed up tests under SQLite we use the MD5 hasher as the default one. # This should not be needed under other databases, as the relative speedup # is only marginal there. PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', ) SOUTH_TESTS_MIGRATE = False URLCONF_INCLUDE_CHOICES = tuple()
Add ability to specify email_check_hash for createUser
import { omit } from 'lodash'; import uuid from 'uuid'; import bcrypt from 'bcrypt'; import { Factory } from 'rosie'; import faker from 'faker'; import { bookshelf } from '../db'; const User = bookshelf.model('User'); const UserFactory = new Factory() .attr('id', () => uuid.v4()) .attr('created_at', () => faker.date.recent()) .attr('updated_at', () => faker.date.recent()) .attr('username', () => faker.internet.userName().toLowerCase()) .attr('email', () => faker.internet.email()) .attr('password', () => faker.internet.password()) .attr('hashed_password', ['password'], password => bcrypt.hashSync(password, 10)) .attr('email_check_hash', () => Math.random().toString()) .attr('more', { firstName: faker.name.firstName(), lastName: faker.name.lastName(), first_login: false }); export default UserFactory; export async function createUser(attrs = {}) { const userAttrs = UserFactory.build(attrs); const user = await new User(omit(userAttrs, 'password')).save(null, { method: 'insert' }); await user.save({ email_check_hash: attrs.email_check_hash || null }, { method: 'update' }); user.attributes.password = userAttrs.password; return user; }
import uuid from 'uuid'; import bcrypt from 'bcrypt'; import { Factory } from 'rosie'; import faker from 'faker'; import { bookshelf } from '../db'; const User = bookshelf.model('User'); const UserFactory = new Factory() .attr('id', () => uuid.v4()) .attr('created_at', () => faker.date.recent()) .attr('updated_at', () => faker.date.recent()) .attr('username', () => faker.internet.userName().toLowerCase()) .attr('email', () => faker.internet.email()) .attr('password', () => faker.internet.password()) .attr('hashed_password', ['password'], password => bcrypt.hashSync(password, 10)) .attr('email_check_hash', '') .attr('more', { firstName: faker.name.firstName(), lastName: faker.name.lastName(), first_login: false }); export default UserFactory; export async function createUser(attrs = {}) { const userAttrs = UserFactory.build(attrs); const user = await User.create(userAttrs); await user.save({ email_check_hash: null }, { method: 'update' }); user.attributes.password = userAttrs.password; return user; }
Change @include to match manifest
// ==UserScript== // @name TwitchEmote4Facebook // @description adds the Twitch emotes to the facebook chat // @homepage https://github.com/Kiniamaro/TwitchEmote4Facebook // @version 0.1.0 // @include https://www.facebook.com/* // @grant none // ==/UserScript== var emotes = []; // Todo function kappafy() { var messages = document.getElementsByClassName("null"); for (var i = 0; i < messages.length; i++) { if (messages[i].innerHTML.match(/Kappa/g)) { var modified = messages[i].innerHTML.replace( /Kappa/g, '<img src="http://static-cdn.jtvnw.net/jtv_user_pictures/' + 'chansub-global-emoticon-ddc6e3a8732cb50f-25x28.png">' ); messages[i].innerHTML = modified; } } } window.setInterval(kappafy, 1000);
// ==UserScript== // @name TwitchEmote4Facebook // @description adds the Twitch emotes to the facebook chat // @homepage https://github.com/Kiniamaro/TwitchEmote4Facebook // @version 0.1.0 // @include *.facebook.com/* // @grant none // ==/UserScript== var emotes = []; // Todo function kappafy() { var messages = document.getElementsByClassName("null"); for (var i = 0; i < messages.length; i++) { if (messages[i].innerHTML.match(/Kappa/g)) { var modified = messages[i].innerHTML.replace( /Kappa/g, '<img src="http://static-cdn.jtvnw.net/jtv_user_pictures/' + 'chansub-global-emoticon-ddc6e3a8732cb50f-25x28.png">' ); messages[i].innerHTML = modified; } } } window.setInterval(kappafy, 1000);
Test actual parsed JSON instead of strings
'use strict'; var grunt = require('grunt'); function readFile(file) { return grunt.file.readJSON(file); } function assertFileEquality(test, pathToActual, pathToExpected, message) { var actual, expected; expected = readFile(pathToExpected); try { actual = readFile(pathToActual); } catch (e) { console.log("\n" + e.message); } test.deepEqual(expected, actual, message); } exports.noflo_manifest = { update: function(test) { test.expect(2); assertFileEquality(test, 'tmp/package.json', 'test/expected/package.json', 'Should add the expected graphs and components to the package.json file' ); assertFileEquality(test, 'tmp/component.json', 'test/expected/component.json', 'Should add the expected graphs and components to the component.json file' ); test.done(); } };
'use strict'; var grunt = require('grunt'); function readFile(file) { var contents = grunt.file.read(file); if (process.platform === 'win32') { contents = contents.replace(/\r\n/g, '\n'); } return contents; } function assertFileEquality(test, pathToActual, pathToExpected, message) { var actual, expected; expected = readFile(pathToExpected); try { actual = readFile(pathToActual); } catch (e) { console.log("\n" + e.message); actual = ''; } test.equal(expected.trim(), actual.trim(), message); } exports.noflo_manifest = { update: function(test) { test.expect(2); assertFileEquality(test, 'tmp/package.json', 'test/expected/package.json', 'Should add the expected graphs and components to the package.json file' ); assertFileEquality(test, 'tmp/component.json', 'test/expected/component.json', 'Should add the expected graphs and components to the component.json file' ); test.done(); } };
Use Surge's 200 file for clean routing.
// see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { build: { env: require('./env.prod'), index: path.resolve(__dirname, '../build/200.html'), assetsRoot: path.resolve(__dirname, '../build'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./env.dev'), port: 8080, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
// see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { build: { env: require('./env.prod'), index: path.resolve(__dirname, '../build/index.html'), assetsRoot: path.resolve(__dirname, '../build'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./env.dev'), port: 8080, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
Swap inputTooLong and inputTooShort error messages "Engada" in galician is "to add" and therefore should be the base text used for the inputTooShort method, asking the use to add more chars. It seems to be mistakenly defined exactly the opposite it should be (as inputTooLong was containing the right text).
define(function () { // Galician return { inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Elimine '; if (overChars === 1) { message += 'un carácter'; } else { message += overChars + ' caracteres'; } return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Engada '; if (remainingChars === 1) { message += 'un carácter'; } else { message += remainingChars + ' caracteres'; } return message; }, loadingMore: function () { return 'Cargando máis resultados…'; }, maximumSelected: function (args) { var message = 'Só pode '; if (args.maximum === 1) { message += 'un elemento'; } else { message += args.maximum + ' elementos'; } return message; }, noResults: function () { return 'Non se atoparon resultados'; }, searching: function () { return 'Buscando…'; } }; });
define(function () { // Galician return { inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Engada '; if (overChars === 1) { message += 'un carácter'; } else { message += overChars + ' caracteres'; } return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Elimine '; if (remainingChars === 1) { message += 'un carácter'; } else { message += remainingChars + ' caracteres'; } return message; }, loadingMore: function () { return 'Cargando máis resultados…'; }, maximumSelected: function (args) { var message = 'Só pode '; if (args.maximum === 1) { message += 'un elemento'; } else { message += args.maximum + ' elementos'; } return message; }, noResults: function () { return 'Non se atoparon resultados'; }, searching: function () { return 'Buscando…'; } }; });
Trim quotes around the CLI argument.
const jsonic = require('jsonic'); const qs = require('qs'); const trim = require('lodash/trim'); /** * Start a timer. * * @return {Array} */ exports.startTimer = function() { return process.hrtime(); }; /** * Stop the given timer and return elapsed time in milliseconds. * * @return {Number} */ exports.endTimer = function(start) { const end = process.hrtime(start); return end[0] * 1000 + end[1] / 1000000; } /** * Parse CLI input into the appropriate request payload. */ exports.parseData = function(data) { let parsedData, headers; data = trim(data, `'"`); if (data && typeof data === 'string') { if (data.includes(':')) { parsedData = jsonic(data); } else if (data.includes('=')) { headers = {'Content-Type': 'application/x-www-form-urlencoded'}; parsedData = qs.stringify(qs.parse(data)); } else { headers = {'Content-Type': 'text/plain'}; parsedData = data; } } return { parsedData, headers }; } /** * Track verbosity CLI argument. */ exports.increaseVerbosity = function(v, total) { return total + 1; }
const jsonic = require('jsonic'); const qs = require('qs'); /** * Start a timer. * * @return {Array} */ exports.startTimer = function() { return process.hrtime(); }; /** * Stop the given timer and return elapsed time in milliseconds. * * @return {Number} */ exports.endTimer = function(start) { const end = process.hrtime(start); return end[0] * 1000 + end[1] / 1000000; } /** * Parse CLI input into the appropriate request payload. */ exports.parseData = function(data) { let parsedData, headers; if (data && typeof data === 'string') { if (data.includes(':')) { parsedData = jsonic(data); } else if (data.includes('=')) { headers = {'Content-Type': 'application/x-www-form-urlencoded'}; parsedData = qs.stringify(qs.parse(data)); } else { headers = {'Content-Type': 'text/plain'}; parsedData = data; } } return { parsedData, headers }; } /** * Track verbosity CLI argument. */ exports.increaseVerbosity = function(v, total) { return total + 1; }
Set implicit loop for Python <3.6
import asyncio import threading class Tasks: loop = asyncio.new_event_loop() @classmethod def _run(cls): asyncio.set_event_loop(cls.loop) try: cls.loop.run_forever() finally: cls.loop.close() @classmethod def do(cls, func, *args, **kwargs): cls.loop.call_soon(lambda: func(*args, **kwargs)) cls.loop._write_to_self() @classmethod def later(cls, func, *args, after=None, **kwargs): cls.loop.call_later(after, lambda: func(*args, **kwargs)) cls.loop._write_to_self() @classmethod def periodic(cls, func, *args, interval=None, **kwargs): @asyncio.coroutine def f(): while True: yield from asyncio.sleep(interval) func(*args, **kwargs) cls.loop.create_task(f()) cls.loop._write_to_self() threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
import asyncio import threading class Tasks: loop = asyncio.new_event_loop() @classmethod def _run(cls): try: cls.loop.run_forever() finally: cls.loop.close() @classmethod def do(cls, func, *args, **kwargs): cls.loop.call_soon(lambda: func(*args, **kwargs)) cls.loop._write_to_self() @classmethod def later(cls, func, *args, after=None, **kwargs): cls.loop.call_later(after, lambda: func(*args, **kwargs)) cls.loop._write_to_self() @classmethod def periodic(cls, func, *args, interval=None, **kwargs): @asyncio.coroutine def f(): while True: yield from asyncio.sleep(interval) func(*args, **kwargs) cls.loop.create_task(f()) cls.loop._write_to_self() threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()
Fix to TAP output when grep is used to filter out tests: these tests should not contribute to the overall total in the TAP plan.
/** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 1; runner.on('start', function(){ var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ console.log('not ok %d %s', n, title(test)); console.log(err.stack.replace(/^/gm, ' ')); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); }
/** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , n = 1; runner.on('start', function(){ console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ console.log('not ok %d %s', n, title(test)); console.log(err.stack.replace(/^/gm, ' ')); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); }
Add ability to programatically play sound after button press
from flask import Flask, request, redirect import twilio.twiml app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello_monkey(): """Respond to incoming requests""" resp = twilio.twiml.Response() with resp.gather(numDigits=1, action="/handle-key", method="POST") as g: g.say("press 1 or something") return str(resp) @app.route("/handle-key", methods=['GET', 'POST']) def handle_key(): digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = twilio.twiml.Response() resp.play("http://demo.twilio.com/hellomonkey/monkey.mp3") return str(resp) else: return redirect("/") if __name__ == "__main__": app.run(debug=True)
from flask import Flask, request, redirect import twilio.twiml app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello_monkey(): """Respond to incoming requests""" resp = twilio.twiml.Response() with resp.gather(numDigits=1, action="/handle-key", method="POST") as g: g.say("press 1 or something") return str(resp) @app.route("/handle-key", methods=['GET', 'POST']) def handle_key(): digit_pressed = request.values.get('Digits', None) if digit_pressed == "1": resp = twilio.twiml.Response() resp.redirect("http://b9ff5a36.ngrok.io/twl/modified.xml") return str(resp) else: return redirect("/") if __name__ == "__main__": app.run(debug=True)
Fix admin URLs; turn deprecation warnings into errors
import warnings from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() # Turns deprecation warnings into errors warnings.simplefilter('error', DeprecationWarning) urlpatterns = [ # Examples: # url(r'^$', 'SigmaPi.views.home', name='home'), # url(r'^SigmaPi/', include('SigmaPi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', admin.site.urls), url(r'^users/', include('UserInfo.urls')), url(r'^secure/', include('Secure.urls')), url(r'^', include('PubSite.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'SigmaPi.views.home', name='home'), # url(r'^SigmaPi/', include('SigmaPi.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('UserInfo.urls')), url(r'^secure/', include('Secure.urls')), url(r'^', include('PubSite.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Add extra validation for vote creation.
<?php $question = trim($_REQUEST['question']); if($_REQUEST['action'] == 'Preview Vote') { $container = create_container('skeleton.php','vote_create.php'); $container['PreviewVote'] = $question; $container['Days'] = $_REQUEST['days']; forward($container); } $option = trim($_REQUEST['option']); if($_REQUEST['action'] == 'Preview Option') { $container = create_container('skeleton.php','vote_create.php'); $container['PreviewOption'] = $option; $container['VoteID'] = $_REQUEST['vote']; forward($container); } if($_REQUEST['action'] == 'Create Vote') { if(empty($question)) create_error('You have to specify a vote message.'); if(empty($_REQUEST['days'])) create_error('You have to specify the amount of time to run the vote for.'); $end = TIME+86400*$_REQUEST['days']; // put the msg into the database $db->query('INSERT INTO voting (question, end) VALUES('.$db->escapeString($question).','.$db->escapeNumber($end).')'); } else if($_REQUEST['action'] == 'Add Option') { if(empty($option)) create_error('You have to specify an option message.'); if(empty($_REQUEST['vote'])) create_error('You have to select a vote to add the option to.'); // put the msg into the database $db->query('INSERT INTO voting_options (vote_id, text) VALUES('.$db->escapeNumber($_REQUEST['vote']).','.$db->escapeString($option).')'); } forward(create_container('skeleton.php', 'vote_create.php')) ?>
<?php $question = trim($_REQUEST['question']); if($_REQUEST['action'] == 'Preview Vote') { $container = create_container('skeleton.php','vote_create.php'); $container['PreviewVote'] = $question; $container['Days'] = $_REQUEST['days']; forward($container); } $option = trim($_REQUEST['option']); if($_REQUEST['action'] == 'Preview Option') { $container = create_container('skeleton.php','vote_create.php'); $container['PreviewOption'] = $option; $container['VoteID'] = $_REQUEST['vote']; forward($container); } if($_REQUEST['action'] == 'Create Vote') { $end = TIME+86400*$_REQUEST['days']; // put the msg into the database $db->query('INSERT INTO voting (question, end) VALUES('.$db->escapeString($question).','.$db->escapeNumber($end).')'); } else if($_REQUEST['action'] == 'Add Option') { $voteID = $_REQUEST['vote']; // put the msg into the database $db->query('INSERT INTO voting_options (vote_id, text) VALUES('.$db->escapeNumber($voteID).','.$db->escapeString($option).')'); } forward(create_container('skeleton.php', 'vote_create.php')) ?>
Check for undefined arrays in modules
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, intlShape } from 'react-intl'; import ModulesContext, { originalModules } from '../../ModulesContext'; class ModuleTranslator extends React.Component { static propTypes = { children: PropTypes.node, intl: intlShape, } constructor(props) { super(props); this.state = { modules: this.translateModules(), }; } translateModules = () => { return { app: (originalModules.app || []).map(this.translateModule), plugin: (originalModules.plugin || []).map(this.translateModule), settings: (originalModules.settings || []).map(this.translateModule), }; } translateModule = (module) => { const { formatMessage } = this.props.intl; return { ...module, displayName: module.displayName ? formatMessage({ id: module.displayName }) : undefined, }; } render() { return ( <ModulesContext.Provider value={this.state.modules}> { this.props.children } </ModulesContext.Provider> ); } } export default injectIntl(ModuleTranslator);
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, intlShape } from 'react-intl'; import ModulesContext, { originalModules } from '../../ModulesContext'; class ModuleTranslator extends React.Component { static propTypes = { children: PropTypes.node, intl: intlShape, } constructor(props) { super(props); this.state = { modules: this.translateModules(), }; } translateModules = () => { return { app: originalModules.app.map(this.translateModule), plugin: originalModules.plugin.map(this.translateModule), settings: originalModules.settings.map(this.translateModule), }; } translateModule = (module) => { const { formatMessage } = this.props.intl; return { ...module, displayName: module.displayName ? formatMessage({ id: module.displayName }) : undefined, }; } render() { return ( <ModulesContext.Provider value={this.state.modules}> { this.props.children } </ModulesContext.Provider> ); } } export default injectIntl(ModuleTranslator);
Fix issue in retrieval of transactions
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) }, Item: { rsbuddy: ({ id }, args, { models }) => models.items .findOne({ id }, { _id: false, rsbuddy: true }) .then(tx => tx.rsbuddy) } } })
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) }, Item: { rsbuddy: (root, args, { models }) => models.items.findOne({ id: root.id }, { _id: false, rsbuddy: true }) } } })
Use standard plugin naming convention As usual, stealing things from the less and coffeescript packages. I’m not sure why this would possibly matter, but at least it’s consistent.
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.0-0.0.42" }); Package._transitional_registerBuildPlugin({ name: "compileHarmony", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: {"traceur": "0.0.42"} }); Package.on_use(function(api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); }); // Issue #7 reminder // Package.on_test(function (api) { // api.use(["harmony", "tinytest"]); // api.add_files("tests/test.js", ["client"]); // api.add_files([ // ], ["client", "server"]); // });
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.0-0.0.42" }); Package._transitional_registerBuildPlugin({ name: "harmony-compiler", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: {"traceur": "0.0.42"} }); Package.on_use(function(api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); }); // Issue #7 reminder // Package.on_test(function (api) { // api.use(["harmony", "tinytest"]); // api.add_files("tests/test.js", ["client"]); // api.add_files([ // ], ["client", "server"]); // });
Reduce amount of Always/Never instances. (The are stateless.)
from __future__ import unicode_literals from .base import Always, Never from .types import SimpleFilter, CLIFilter __all__ = ( 'to_cli_filter', 'to_simple_filter', ) _always = Always() _never = Never() def to_simple_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a SimpleFilter. """ assert isinstance(bool_or_filter, (bool, SimpleFilter)), \ TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter) return { True: _always, False: _never, }.get(bool_or_filter, bool_or_filter) def to_cli_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a CLIFilter. """ assert isinstance(bool_or_filter, (bool, CLIFilter)), \ TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter) return { True: _always, False: _never, }.get(bool_or_filter, bool_or_filter)
from __future__ import unicode_literals from .base import Always, Never from .types import SimpleFilter, CLIFilter __all__ = ( 'to_cli_filter', 'to_simple_filter', ) def to_simple_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a SimpleFilter. """ assert isinstance(bool_or_filter, (bool, SimpleFilter)), \ TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter) return { True: Always(), False: Never() }.get(bool_or_filter, bool_or_filter) def to_cli_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a CLIFilter. """ assert isinstance(bool_or_filter, (bool, CLIFilter)), \ TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter) return { True: Always(), False: Never() }.get(bool_or_filter, bool_or_filter)
Remove no longer used argument from buildUrl() call
<?php namespace Keyteq\Keymedia\API; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Util\RequestBuilder; class RestConnector { protected $config; protected $requestBuilder; public function __construct(Configuration $config, RequestBuilder $requestBuilder) { $this->config = $config; $this->requestBuilder = $requestBuilder; } public function getResource($resourceName, $resourceId, array $parameters = array()) { $path = "{$resourceName}/{$resourceId}.json"; $url = $this->buildUrl($path, $parameters); $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters); return $request->perform(); } public function getCollection($resourceName, array $parameters = array()) { $path = "{$resourceName}.json"; $url = $this->buildUrl($path); $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters); return $request->perform(); } protected function buildUrl($path = '') { $rootUrl = $this->config->getApiUrl(); $url = "{$rootUrl}/{$path}"; return $url; } }
<?php namespace Keyteq\Keymedia\API; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Util\RequestBuilder; class RestConnector { protected $config; protected $requestBuilder; public function __construct(Configuration $config, RequestBuilder $requestBuilder) { $this->config = $config; $this->requestBuilder = $requestBuilder; } public function getResource($resourceName, $resourceId, array $parameters = array()) { $path = "{$resourceName}/{$resourceId}.json"; $url = $this->buildUrl($path, $parameters); $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters); return $request->perform(); } public function getCollection($resourceName, array $parameters = array()) { $path = "{$resourceName}.json"; $url = $this->buildUrl($path, $parameters); $request = $this->requestBuilder->buildRequest($url, 'GET', $parameters); return $request->perform(); } protected function buildUrl($path = '') { $rootUrl = $this->config->getApiUrl(); $url = "{$rootUrl}/{$path}"; return $url; } }
api: Remove resourceType, use only entityType Signed-off-by: Rohit Yadav <0fa72ca37c4b5fa62675187ce32ea6c9f842fd52@apache.org>
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.cloudstack.api.BaseCmd.CommandType; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) public @interface Parameter { String name() default ""; String description() default ""; boolean required() default false; CommandType type() default CommandType.OBJECT; CommandType collectionType() default CommandType.OBJECT; Class<?>[] entityType() default Object.class; boolean expose() default true; boolean includeInApiDoc() default true; int length() default 255; String since() default ""; String retrieveMethod() default "getById"; }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.cloudstack.api.BaseCmd.CommandType; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) public @interface Parameter { String name() default ""; String description() default ""; boolean required() default false; CommandType type() default CommandType.OBJECT; CommandType collectionType() default CommandType.OBJECT; Class<?>[] entityType() default Object.class; boolean expose() default true; boolean includeInApiDoc() default true; int length() default 255; String since() default ""; Class<?>[] resourceType() default Object.class; String retrieveMethod() default "getById"; }
Rename service name in default test
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB package is installed def test_mongodb_is_installed(host): package = host.package('mongodb-org') assert package.is_installed assert package.version.startswith('3.4.7') # check if MongoDB is enabled and running def test_mongod_is_running(host): mongod = host.service('mongod') assert mongod.is_running assert mongod.is_enabled # check if configuration file contains the required line def test_mongod_config_file(File): config_file = File('/etc/mongod.conf') assert config_file.contains('port: 27017') assert config_file.contains('bindIp: 127.0.0.1') assert config_file.is_file # check if mongod process is listening on localhost def test_mongod_is_listening(host): port = host.socket('tcp://127.0.0.1:27017') assert port.is_listening
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') # check if MongoDB package is installed def test_mongodb_is_installed(host): package = host.package('mongodb-org') assert package.is_installed assert package.version.startswith('3.4.7') # check if MongoDB is enabled and running def test_mongod_is_running(host): mongo = host.service('mongod') assert mongo.is_running assert mongo.is_enabled # check if configuration file contains the required line def test_mongod_config_file(File): config_file = File('/etc/mongod.conf') assert config_file.contains('port: 27017') assert config_file.contains('bindIp: 127.0.0.1') assert config_file.is_file # check if mongod process is listening on localhost def test_mongod_is_listening(host): port = host.socket('tcp://127.0.0.1:27017') assert port.is_listening
Set root log level to INFO
import logging.config _logging_config = dict( version=1, disable_existing_loggers=False, formatters={ 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(message)s' }, }, handlers={ 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'null': { 'class': 'logging.NullHandler', } }, loggers={ '': { 'handlers': ['console'], 'level': logging.INFO, }, 'influxdb': { 'level': logging.INFO, }, 'phue': { 'level': logging.INFO, }, }, ) logging.config.dictConfig(_logging_config)
import logging.config _logging_config = dict( version=1, disable_existing_loggers=False, formatters={ 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(message)s' }, }, handlers={ 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'null': { 'class': 'logging.NullHandler', } }, loggers={ '': { 'handlers': ['console'], 'level': logging.DEBUG, }, 'influxdb': { 'level': logging.INFO, }, 'phue': { 'level': logging.INFO, }, }, ) logging.config.dictConfig(_logging_config)
Add OPTIONS to CORS allowed methods
/** * Adds CORS headers to the response * * ####Example: * * app.all('/api*', keystone.middleware.cors); * * @param {app.request} req * @param {app.response} res * @param {function} next * @api public */ // The exported function returns a closure that retains // a reference to the keystone instance, so it can be // passed as middeware to the express app. module.exports = function (keystone) { return function cors (req, res, next) { var origin = keystone.get('cors allow origin'); if (origin) { res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin); } if (keystone.get('cors allow methods') !== false) { res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE,OPTIONS'); } if (keystone.get('cors allow headers') !== false) { res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization'); } next(); }; };
/** * Adds CORS headers to the response * * ####Example: * * app.all('/api*', keystone.middleware.cors); * * @param {app.request} req * @param {app.response} res * @param {function} next * @api public */ // The exported function returns a closure that retains // a reference to the keystone instance, so it can be // passed as middeware to the express app. module.exports = function (keystone) { return function cors (req, res, next) { var origin = keystone.get('cors allow origin'); if (origin) { res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin); } if (keystone.get('cors allow methods') !== false) { res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE'); } if (keystone.get('cors allow headers') !== false) { res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization'); } next(); }; };
[NO-JIRA]: Fix errors overview actions naming
import { fetchErrorCatalog } from '../../../services/errors.service.js' // ------------------------------------ // Constants // ------------------------------------ const GET_ERRORS_OVERVIEW_SUCCESS = 'GET_ERRORS_OVERVIEW_SUCCESS' // ------------------------------------ // Actions // ------------------------------------ export const getErrorsOverviewSuccess = (payload) => ({ type: GET_ERRORS_OVERVIEW_SUCCESS, payload }) export const getErrorsOverview = () => (dispatch) => { return fetchErrorCatalog() .then((data) => { dispatch(getErrorsOverviewSuccess(data)) }) } export const actions = { getErrorsOverview } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [GET_ERRORS_OVERVIEW_SUCCESS]: (state, { payload }) => ({ ...state, errorsData: payload }) } // ------------------------------------ // Reducer // ------------------------------------ export const initialState = { errorsData: null } export default function (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
import { fetchErrorCatalog } from '../../../services/errors.service.js' // ------------------------------------ // Constants // ------------------------------------ const GET_ENVIRONMENT_SUCCESS = 'GET_ENVIRONMENT_SUCCESS' // ------------------------------------ // Actions // ------------------------------------ export const getErrorsOverviewSuccess = (payload) => ({ type: GET_ENVIRONMENT_SUCCESS, payload }) export const getErrorsOverview = () => (dispatch) => { return fetchErrorCatalog() .then((data) => { dispatch(getErrorsOverviewSuccess(data)) }) } export const actions = { getErrorsOverview } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [GET_ENVIRONMENT_SUCCESS]: (state, { payload }) => ({ ...state, errorsData: payload }) } // ------------------------------------ // Reducer // ------------------------------------ export const initialState = { errorsData: null } export default function (state = initialState, action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
Add JS to toggle active class on buttons.
/* PSEUDO CODE FOR LOGIN MENU 1. COLLECT DATA ENTERED INTO THE <INPUT> 2. WHEN .LOGIN-SUBMIT IS 'CLICKED' `GET/users/id` TO DATABASE TO BE VERIFIED? */ ;(function(){ angular.module('Front-Rails', [ ]) .run(function($http, $rootScope) { $http.get('https://stackundertow.herokuapp.com/questions') .then(function(response){ // $rootScope.query = "hello"; $rootScope.query = response.data[0].query; // $rootScope.questions = response.data; }) }) })(); $('.search a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); }); $('.redirect a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .toggleClass('active') .siblings().removeClass('active'); });
/* PSEUDO CODE FOR LOGIN MENU 1. COLLECT DATA ENTERED INTO THE <INPUT> 2. WHEN .LOGIN-SUBMIT IS 'CLICKED' `GET/users/id` TO DATABASE TO BE VERIFIED? */ ;(function(){ angular.module('Front-Rails', [ ]) .run(function($http, $rootScope) { $http.get('https://stackundertow.herokuapp.com/questions') .then(function(response){ // $rootScope.query = "hello"; $rootScope.query = response.data[0].query; // $rootScope.questions = response.data; }) }) })(); $('.search a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .addClass('active') .siblings().removeClass('active'); }); $('.redirect a[href]').on('click', function(event){ event.preventDefault(); $(this).add(this.hash) .addClass('active') .siblings().removeClass('active'); });
Update helper and change var to const
Template.editQuestionsGroup.helpers({ ekloreQuestionsLinked() { return EkloreQuestions.find({ questionGroupId: this._id }); } }); Template.editQuestionsGroup.events({ 'click #save': function(event) { event.preventDefault(); const questionsGroupData = { questionsGroupId: Router.current().params._id, title: $('#questionsGroupTitle').val(), label: $('#questionsGroupLabel').val(), level: Number($('#questionsGroupLevel').val()) }; if ($('input[name="deprecated"]:checked').val() === 'notDeprecated') { questionsGroupData.deprecated = false; } else if ($('input[name="deprecated"]:checked').val() === 'deprecated') { questionsGroupData.deprecated = true; } if (!questionsGroupData.title) { return throwError('Name must be filled'); } if (!questionsGroupData.label) { return throwError('Label must be filled'); } if (!questionsGroupData.level) { return throwError('Level must be filled'); } if (questionsGroupData.level < 2) { return throwError('The level must be superior to 1'); } Meteor.call('updateAQuestionsGroup', questionsGroupData, (error, result) => { if (error) { return throwError(error.message); } else { return throwError('Update succesful !'); } }); } });
Template.editQuestionsGroup.helpers({ ekloreQuestionsLinked() { return EkloreQuestions .find({ 'questionGroupId': this._id }); } }); Template.editQuestionsGroup.events({ 'click #save': function(event) { event.preventDefault(); var questionsGroupData = { questionsGroupId: Router.current().params._id, title: $('#questionsGroupTitle').val(), label: $('#questionsGroupLabel').val(), level: Number($('#questionsGroupLevel').val()) }; if ($('input[name="deprecated"]:checked').val() === 'notDeprecated') { questionsGroupData.deprecated = false; } else if ($('input[name="deprecated"]:checked').val() === 'deprecated') { questionsGroupData.deprecated = true; } if (!questionsGroupData.title) { return throwError('Name must be filled'); } if (!questionsGroupData.label) { return throwError('Label must be filled'); } if (!questionsGroupData.level) { return throwError('Level must be filled'); } if (questionsGroupData.level < 2) { return throwError('The level must be superior to 1'); } Meteor.call('updateAQuestionsGroup', questionsGroupData, (error, result) => { if (error) { return throwError(error.message); } else { return throwError('Update succesful !'); } }); } });
Introduce `equalOps` test helper for comparing operations. Provides comparisons of Operation instances based on their serialized form.
var verifyLocalStorageContainsRecord = function(namespace, type, id, record, ignoreFields) { var expected = {}; expected[id] = record; var actual = JSON.parse(window.localStorage.getItem(namespace)); if (type) actual = actual[type]; if (ignoreFields) { for (var i = 0, l = ignoreFields.length, field; i < l; i++) { field = ignoreFields[i]; actual[id][field] = record[field]; } } deepEqual(actual, expected, 'data in local storage matches expectations'); }; var verifyLocalStorageIsEmpty = function(namespace) { var contents = JSON.parse(window.localStorage.getItem(namespace)); if (contents === null) { equal(contents, null, 'local storage should still be empty'); } else { deepEqual(contents, {}, 'local storage should still be empty'); } }; var equalOps = function(result, expected, msg) { deepEqual(result && result.serialize ? result.serialize() : result, expected && expected.serialize ? expected.serialize() : expected, msg); }; export { verifyLocalStorageContainsRecord, verifyLocalStorageIsEmpty, equalOps };
var verifyLocalStorageContainsRecord = function(namespace, type, id, record, ignoreFields) { var expected = {}; expected[id] = record; var actual = JSON.parse(window.localStorage.getItem(namespace)); if (type) actual = actual[type]; if (ignoreFields) { for (var i = 0, l = ignoreFields.length, field; i < l; i++) { field = ignoreFields[i]; actual[id][field] = record[field]; } } deepEqual(actual, expected, 'data in local storage matches expectations'); }; var verifyLocalStorageIsEmpty = function(namespace) { var contents = JSON.parse(window.localStorage.getItem(namespace)); if (contents === null) { equal(contents, null, 'local storage should still be empty'); } else { deepEqual(contents, {}, 'local storage should still be empty'); } }; export { verifyLocalStorageContainsRecord, verifyLocalStorageIsEmpty };
Initialize strict mode before anything else
package de.markusfisch.android.shadereditor.app; import de.markusfisch.android.shadereditor.database.DataSource; import de.markusfisch.android.shadereditor.preference.Preferences; import de.markusfisch.android.shadereditor.BuildConfig; import android.app.Application; import android.os.StrictMode; public class ShaderEditorApplication extends Application { public static final Preferences preferences = new Preferences(); public static final DataSource dataSource = new DataSource(); @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy( new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build()); } preferences.init(this); dataSource.openAsync(this); } }
package de.markusfisch.android.shadereditor.app; import de.markusfisch.android.shadereditor.database.DataSource; import de.markusfisch.android.shadereditor.preference.Preferences; import de.markusfisch.android.shadereditor.BuildConfig; import android.app.Application; import android.os.StrictMode; public class ShaderEditorApplication extends Application { public static final Preferences preferences = new Preferences(); public static final DataSource dataSource = new DataSource(); @Override public void onCreate() { super.onCreate(); preferences.init(this); dataSource.openAsync(this); if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy( new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build()); } } }
Clean up BlinkyPlayer a little
import time class BlinkyPlayer(object): FOREVER = -1 def __init__(self, blinkytape): self._blinkytape = blinkytape def play(self, animation, num_cycles = FOREVER): finished = self._finished_predicate(animation, num_cycles) animation.begin() while not finished(): pixels = animation.next_frame() self._blinkytape.update(pixels) time.sleep(animation.frame_period_sec) animation.end() def _finished_predicate(self, animation, num_cycles): if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError if num_cycles == self.FOREVER: predicate = self._forever_predicate() else: self._num_frames = animation.frame_count * num_cycles predicate = self._frame_count_predicate() return predicate def _forever_predicate(self): return lambda: False def _frame_count_predicate(self): def predicate(): finished = self._num_frames <= 0 self._num_frames = self._num_frames - 1 return finished return predicate
import time class BlinkyPlayer(object): FOREVER = -1 def __init__(self, blinkytape): self._blinkytape = blinkytape def play(self, animation, num_cycles = FOREVER): finished = self._make_finished_predicate(animation, num_cycles) animation.begin() while not finished(): pixels = animation.next_frame() self._blinkytape.update(pixels) time.sleep(animation.frame_period_sec) animation.end() def _make_finished_predicate(self, animation, num_cycles): if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError if num_cycles == self.FOREVER: predicate = lambda: False else: self._num_frames = animation.frame_count * num_cycles def predicate(): finished = self._num_frames <= 0 self._num_frames = self._num_frames - 1 return finished return predicate
Add rescue field to store client's messages
var mongoose, RatSchema, Schema; mongoose = require( 'mongoose' ); Schema = mongoose.Schema; RatSchema = new Schema({ 'archive': { default: false, type: Boolean }, 'CMDRname': { type: String }, 'createdAt': { type: Date }, 'drilled': { default: false, type: Boolean }, 'gamertag': { type: String }, 'lastModified': { type: Date }, 'joined': { default: Date.now(), type: Date }, 'netlog': { type: { 'commanderId': { type: String }, 'data': { type: Schema.Types.Mixed }, 'userId': { type: String } } }, 'nickname': { type: [String] } }); RatSchema.index({ 'CMDRname': 'text', 'gamertag': 'text', 'nickname': 'text' }); RatSchema.pre( 'save', function ( next ) { var timestamp; timestamp = Date.now(); this.createdAt = this.createdAt || timestamp; this.lastModified = timestamp; next(); }); RatSchema.set( 'toJSON', { virtuals: true, transform: function ( document, ret, options ) { ret.id = ret._id; delete ret._id; } }); module.exports = mongoose.model( 'Rat', RatSchema );
var mongoose, RatSchema, Schema; mongoose = require( 'mongoose' ); Schema = mongoose.Schema; RatSchema = new Schema({ 'archive': { default: false, type: Boolean }, 'CMDRname': { type: String }, 'createdAt': { type: Date }, 'drilled': { default: false, type: Boolean }, 'gamertag': { type: String }, 'lastModified': { type: Date }, 'joined': { default: Date.now(), type: Date }, 'netlog': { type: { 'commanderId': { type: String }, 'data': { type: Schema.Types.Mixed }, 'userId': { type: String } } }, 'nickname': { type: String } }); RatSchema.index({ 'CMDRname': 'text', 'gamertag': 'text', 'nickname': 'text' }); RatSchema.pre( 'save', function ( next ) { var timestamp; timestamp = Date.now(); this.createdAt = this.createdAt || timestamp; this.lastModified = timestamp; next(); }); RatSchema.set( 'toJSON', { virtuals: true, transform: function ( document, ret, options ) { ret.id = ret._id; delete ret._id; } }); module.exports = mongoose.model( 'Rat', RatSchema );
Support routing termination on client side
// Fluxex extra action // you should attach a `routing()` action creator on your fluxexapp // For most case you will not require this file directly // See routing.js for more info // // To support IE8, // You will need to npm install html5-history-api, // then add require('fluxex/extra/history'); in your fluxexapp.js module.exports = function (url) { // Try to route this.dispatch('UPDATE_URL', url).then(function () { // Run action to update page stores return this.executeAction(this.routing); }.bind(this)).then(function () { // Success, trigger page refresh this.getStore('page').emitChange(); // update url to history /*global window*/ window.history.pushState(JSON.stringify(this._context), undefined, url); // scroll window to top to simulate non-pjax click window.scrollTo( 0, 0); }.bind(this))['catch'](function (E) { if (!E.hasHandled) { if (console && console.log) { console.log('Pjax failed! Failback to page loading....'); console.log(E.stack || E); } // pjax failed, go to url... window.location.href = url; } }); };
// Fluxex extra action // you should attach a `routing()` action creator on your fluxexapp // For most case you will not require this file directly // See routing.js for more info // // To support IE8, // You will need to npm install html5-history-api, // then add require('fluxex/extra/history'); in your fluxexapp.js module.exports = function (url) { // Try to route this.dispatch('UPDATE_URL', url).then(function () { // Run action to update page stores return this.executeAction(this.routing); }.bind(this)).then(function () { // Success, trigger page refresh this.getStore('page').emitChange(); // update url to history /*global window*/ window.history.pushState(JSON.stringify(this._context), undefined, url); // scroll window to top to simulate non-pjax click window.scrollTo( 0, 0); }.bind(this))['catch'](function (E) { if (console && console.log) { console.log('Pjax failed! Failback to page loading....'); console.log(E.stack || E); } // pjax failed, go to url... window.location.href = url; }); };
Update unit tests for packager.rpm.build.py
#! /usr/bin/python from packager.rpm.build import BuildRPM from nose.tools import * @raises(TypeError) def test_fail_with_no_parameters(): BuildRPM(None) @raises(TypeError) def test_fail_with_one_parameter(): BuildRPM("hydrotrend") def test_hydrotrend_version_none(): BuildRPM("hydrotrend", None) def test_hydrotrend_version_head(): BuildRPM("hydrotrend", "head") #def test_hydrotrend_tagged_version(): # BuildRPM("hydrotrend", "3.0.2") def test_cem_version_head(): BuildRPM("cem", "head") #def test_cem_tagged_version(): # BuildRPM("cem", "0.2") def test_child_version_head(): BuildRPM("child", "head") def test_child_version_head(): BuildRPM("sedflux", "head")
#! /usr/bin/python from build_rpm import BuildModelRPM from nose.tools import * @raises(TypeError) def test_fail_with_no_parameters(): BuildModelRPM(None) @raises(TypeError) def test_fail_with_one_parameter(): BuildModelRPM("hydrotrend") def test_hydrotrend_version_none(): BuildModelRPM("hydrotrend", None) def test_hydrotrend_version_head(): BuildModelRPM("hydrotrend", "head") #def test_hydrotrend_tagged_version(): # BuildModelRPM("hydrotrend", "3.0.2") def test_cem_version_head(): BuildModelRPM("cem", "head") #def test_cem_tagged_version(): # BuildModelRPM("cem", "0.2") def test_child_version_head(): BuildModelRPM("child", "head") def test_child_version_head(): BuildModelRPM("sedflux", "head")
Fix issue with version setter
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): import odintools b = os.getenv('TRAVIS_BUILD_NUMBER') if os.getenv('TRAVIS') else os.environ.get('BUILD_NUMBER') return odintools.version(PACKAGE_VERSION, b) setup( name='osaapi', version_getter=version, author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), setup_requires=['odintools'], odintools=True, )
import os from setuptools import setup PACKAGE_VERSION = '0.3' def version(): if os.getenv('TRAVIS'): return os.getenv('TRAVIS_BUILD_NUMBER') else: import odintools return odintools.version(PACKAGE_VERSION, os.environ.get('BUILD_NUMBER')) setup( name='osaapi', version_getter=version, author='apsliteteam, oznu', author_email='aps@odin.com', packages=['osaapi'], url='https://aps.odin.com', license='Apache License', description='A python client for the Odin Service Automation (OSA) and billing APIs.', long_description=open('README.md').read(), setup_requires=['odintools'], odintools=True, )
Test to validate the SourceDirSubdir works as expected with globs
package getter import ( "testing" ) func TestSourceDirSubdir(t *testing.T) { cases := []struct { Input string Dir, Sub string }{ { "hashicorp.com", "hashicorp.com", "", }, { "hashicorp.com//foo", "hashicorp.com", "foo", }, { "hashicorp.com//foo?bar=baz", "hashicorp.com?bar=baz", "foo", }, { "https://hashicorp.com/path//*?archive=foo", "https://hashicorp.com/path?archive=foo", "*", }, { "file://foo//bar", "file://foo", "bar", }, } for i, tc := range cases { adir, asub := SourceDirSubdir(tc.Input) if adir != tc.Dir { t.Fatalf("%d: bad dir: %#v", i, adir) } if asub != tc.Sub { t.Fatalf("%d: bad sub: %#v", i, asub) } } }
package getter import ( "testing" ) func TestSourceDirSubdir(t *testing.T) { cases := []struct { Input string Dir, Sub string }{ { "hashicorp.com", "hashicorp.com", "", }, { "hashicorp.com//foo", "hashicorp.com", "foo", }, { "hashicorp.com//foo?bar=baz", "hashicorp.com?bar=baz", "foo", }, { "file://foo//bar", "file://foo", "bar", }, } for i, tc := range cases { adir, asub := SourceDirSubdir(tc.Input) if adir != tc.Dir { t.Fatalf("%d: bad dir: %#v", i, adir) } if asub != tc.Sub { t.Fatalf("%d: bad sub: %#v", i, asub) } } }
Add code to subscribe to sources on click
const MAX_SHOWED_ALERTS = 15; var eventSources = {}; $(function() { $('nav li a').click(function(event) { event.preventDefault(); var li = $(this).closest('li'); var sourceUri = $(this).attr('href'); li.toggleClass('selected'); if (li.hasClass('selected')) { createEventSource({ uri: sourceUri, options: {}, onMessageCallback: notifyAlert }); } else { removeEventSource(sourceUri); } }); }); function createEventSource(conf) { var eventSource = new EventSource(conf.uri, conf.options); eventSource.onmessage = function(e) { conf.onMessageCallback(e); }; eventSources[conf.uri] = eventSource; return eventSource; } function notifyAlert(e) { var alert = JSON.parse(e.data); var date = new Date(alert.timestamp); var alert = '<li class="alert ' + alert.alertLevel + '"><span class="source">' + alert.source + '</span><span class="date">' + date.toString() + '</span><p>' + alert.message + '</p></li>'; $('#alerts ul').prepend(alert); $('#alerts li:gt(' + (MAX_SHOWED_ALERTS - 1) + ')').remove(); } function removeEventSource(sourceUri) { if (eventSources.hasOwnProperty(sourceUri)) { eventSources[sourceUri].close(); delete eventSources[sourceUri]; } }
var eventSources = []; $(function() { createEventSource({ source: 'Police', uri: 'http://156.35.95.69/server-sent-events/server/server.php', options: {}, onMessageCallback: notifyAlert }); createEventSource({ source: 'Firefighters', uri: 'http://156.35.95.69/server-sent-events/server/server.php', options: {}, onMessageCallback: notifyAlert }); createEventSource({ source: 'Weather alerts', uri: 'http://156.35.95.69/server-sent-events/server/server.php', options: {}, onMessageCallback: notifyAlert }); }); function createEventSource(conf) { var eventSource = new EventSource(conf.uri, conf.options); eventSource.onmessage = function(e) { conf.onMessageCallback(e, conf.source); }; eventSources.push(eventSource); return eventSource; } function notifyAlert(e, source) { var alert = JSON.parse(e.data); var date = new Date(alert.timestamp); var alert = '<li class="alert ' + alert.alertLevel + '"><p><span class="source">' + source + ':</span> ' + alert.message + '</p><span class="date">' + date.toString() + '</span></li>'; $('section#alerts ul').prepend(alert); }
Add texte to description to producr
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Nos Bonbons</title> <link rel="stylesheet" href="css/main.css"> </head> <body> <?php include "Reference.php"; ?> <?php include("header.php"); ?> <div id="produit"> <figure class="imageBonbon"> <img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap"> </figure> <h2><?php echo $Reference[1]['Titre']; ?></h2> <!-- <div class="card-block"> <h4 class="card-title"><?php echo $value['Titre']?></h4> <p class="card-text"><?php echo $value['Description']?></p> </div> --> <p><?php echo $Reference[1]['Description'];?></p> </div> <h2><?php echo $Reference[1]['Texte']; ?></h2> <?php //include("footer.php"); ?> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Nos Bonbons</title> <link rel="stylesheet" href="css/main.css"> </head> <body> <?php include "Reference.php"; ?> <?php include("header.php"); ?> <div id="produit"> <figure class="imageBonbon"> <img class="card-img-top" src="<?php echo $Reference[1]['Image']; ?>" alt="Card image cap"> </figure> <h2><?php echo $Reference[1]['Titre']; ?></h2> <!-- <div class="card-block"> <h4 class="card-title"><?php echo $value['Titre']?></h4> <p class="card-text"><?php echo $value['Description']?></p> </div> --> </div> <p><?php echo $Reference[1]['Description'];?></p> <?php //include("footer.php"); ?> </body> </html>
static: Make debug_mode for default_page_params follow the setting. For pages that don't have page_params, the default_page_params now ensures that debug_mode will correctly follow settings.DEBUG. This allows blueslip exception popups to work on portico pages for development environment. Fixes: #17540.
from typing import Any from django.conf import settings from django.contrib.staticfiles.storage import staticfiles_storage from django.template.defaultfilters import pluralize, slugify from django.urls import reverse from django.utils import translation from django.utils.timesince import timesince from jinja2 import Environment from two_factor.templatetags.two_factor import device_action from zerver.templatetags.app_filters import display_list, render_markdown_path def environment(**options: Any) -> Environment: env = Environment(**options) env.globals.update( default_page_params={ "debug_mode": settings.DEBUG, "webpack_public_path": staticfiles_storage.url( settings.WEBPACK_LOADER["DEFAULT"]["BUNDLE_DIR_NAME"], ), }, static=staticfiles_storage.url, url=reverse, render_markdown_path=render_markdown_path, ) env.install_gettext_translations(translation, True) env.filters["slugify"] = slugify env.filters["pluralize"] = pluralize env.filters["display_list"] = display_list env.filters["device_action"] = device_action env.filters["timesince"] = timesince return env
from typing import Any from django.conf import settings from django.contrib.staticfiles.storage import staticfiles_storage from django.template.defaultfilters import pluralize, slugify from django.urls import reverse from django.utils import translation from django.utils.timesince import timesince from jinja2 import Environment from two_factor.templatetags.two_factor import device_action from zerver.templatetags.app_filters import display_list, render_markdown_path def environment(**options: Any) -> Environment: env = Environment(**options) env.globals.update( default_page_params={ "debug_mode": False, "webpack_public_path": staticfiles_storage.url( settings.WEBPACK_LOADER["DEFAULT"]["BUNDLE_DIR_NAME"], ), }, static=staticfiles_storage.url, url=reverse, render_markdown_path=render_markdown_path, ) env.install_gettext_translations(translation, True) env.filters["slugify"] = slugify env.filters["pluralize"] = pluralize env.filters["display_list"] = display_list env.filters["device_action"] = device_action env.filters["timesince"] = timesince return env
Allow push to origin again.
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ dest: '2013/', exclusions: ['build','node_modules','2013','2014'], copy: { main: { src: '**/*', dest: 'build/<%= dest %>', filter: function(filepath) { var filepathParts = filepath.split(require('path').sep); var shouldExclude = (filepathParts.length === 1 && grunt.file.isFile(filepath)) || (grunt.config('exclusions').indexOf(filepathParts[0]) !== -1); if (shouldExclude) { console.log("Skipping " + filepath + " " + grunt.config('exclusions') + " " + filepath.split(require('path').sep)[0]); } return !shouldExclude; } } }, 'gh-pages': { options: { base: 'build'/*, push: false*/ }, src: '**/*' } }); // Load the plugin that provides the "copy" task. grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-gh-pages'); // Default task(s). grunt.registerTask('default', ['copy', 'gh-pages']); };
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ dest: '2013/', exclusions: ['build','node_modules','2013','2014'], copy: { main: { src: '**/*', dest: 'build/<%= dest %>', filter: function(filepath) { var filepathParts = filepath.split(require('path').sep); var shouldExclude = (filepathParts.length === 1 && grunt.file.isFile(filepath)) || (grunt.config('exclusions').indexOf(filepathParts[0]) !== -1); if (shouldExclude) { console.log("Skipping " + filepath + " " + grunt.config('exclusions') + " " + filepath.split(require('path').sep)[0]); } return !shouldExclude; } } }, 'gh-pages': { options: { base: 'build', push: false }, src: '**/*' } }); // Load the plugin that provides the "copy" task. grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-gh-pages'); // Default task(s). grunt.registerTask('default', ['copy', 'gh-pages']); };
Remove unnecessary codec reader, fixes type issue
""" byceps.services.country.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from dataclasses import dataclass import json from flask import current_app @dataclass(frozen=True) class Country: name: str alpha2: str alpha3: str def get_countries() -> list[Country]: """Load countries from JSON file.""" path = 'services/country/resources/countries.json' with current_app.open_resource(path) as f: records = json.load(f) return [Country(**record) for record in records] def get_country_names() -> list[str]: """Return country names.""" return [country.name for country in get_countries()]
""" byceps.services.country.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations import codecs from dataclasses import dataclass import json from flask import current_app @dataclass(frozen=True) class Country: name: str alpha2: str alpha3: str def get_countries() -> list[Country]: """Load countries from JSON file.""" reader = codecs.getreader('utf-8') path = 'services/country/resources/countries.json' with current_app.open_resource(path) as f: records = json.load(reader(f)) return [Country(**record) for record in records] def get_country_names() -> list[str]: """Return country names.""" return [country.name for country in get_countries()]
Change tab to 4 instead of 8
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), //JS Source files src: { js: ['app/js/**/*.js'] }, //JS Test files test: { karmaConfig: 'test/karma.conf.js', unit: ['test/unit/**/*.js'] }, // Configure Lint\JSHint Task jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= src.js %>', '<%= test.unit %>' ] }, karma: { unit: { configFile: '<%= test.karmaConfig %>', singleRun: true } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), //JS Source files src: { js: ['app/js/**/*.js'] }, //JS Test files test: { karmaConfig: 'test/karma.conf.js', unit: ['test/unit/**/*.js'] }, // Configure Lint\JSHint Task jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= src.js %>', '<%= test.unit %>' ] }, karma: { unit: { configFile: '<%= test.karmaConfig %>', singleRun: true } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); };
Create new database column to store avatar location.
<?php use yii\db\Schema; use yii\db\Migration; class m150720_012512_create_table_account extends Migration { public function up() { $this->createTable('account', [ 'id' => Schema::TYPE_PK, 'user_id' => Schema::integer(), 'bio' => Schema::text() . ' NOT NULL', 'avatar_url' => Schema::string(500), 'website' => Schema::string(500), 'facebook' => Schema::string(500), 'twitter' => Schema::string(500), 'soundcloud' => Schema::string(500), ]); } public function down() { echo "m150720_012512_create_table_account cannot be reverted.\n"; return false; } }
<?php use yii\db\Schema; use yii\db\Migration; class m150720_012512_create_table_account extends Migration { public function up() { $this->createTable('account', [ 'id' => Schema::TYPE_PK, 'user_id' => Schema::integer(), 'bio' => Schema::text() . ' NOT NULL', 'website' => Schema::string(500), 'facebook' => Schema::string(500), 'twitter' => Schema::string(500), 'soundcloud' => Schema::string(500), ]); } public function down() { echo "m150720_012512_create_table_account cannot be reverted.\n"; return false; } }
Update shrinkwrap inflator to pull in versions identically to npm@2
'use strict' var asyncMap = require('slide').asyncMap var path = require('path') var validate = require('aproba') var fetchPackageMetadata = require('../fetch-package-metadata.js') var createChild = require('./node.js').create var inflateShrinkwrap = module.exports = function (tree, swdeps, finishInflating) { validate('OOF', arguments) if (!npm.config.get('shrinkwrap')) return finishInflating() tree.children = [] asyncMap(Object.keys(swdeps), function (name, next) { var sw = swdeps[name] var spec = sw.resolved ? sw.resolved : (sw.from && url.parse(sw.from).protocol) ? sw.from : name + '@' + sw.version fetchPackageMetadata(spec, tree.path, function (er, pkg) { if (er) return next(er) var child = createChild({ package: pkg, loaded: false, parent: tree, path: path.join(tree.path, 'node_modules', pkg.name), realpath: path.resolve(tree.realpath, 'node_modules', pkg.name) }) tree.children.push(child) inflateShrinkwrap(child, sw.dependencies || {}, next) }) }, finishInflating) }
'use strict' var asyncMap = require('slide').asyncMap var path = require('path') var validate = require('aproba') var fetchPackageMetadata = require('../fetch-package-metadata.js') var createChild = require('./node.js').create var inflateShrinkwrap = module.exports = function (tree, swdeps, finishInflating) { validate('OOF', arguments) if (!npm.config.get('shrinkwrap')) return finishInflating() tree.children = [] asyncMap(Object.keys(swdeps), function (name, next) { var sw = swdeps[name] var spec = sw.resolved || name + '@' + sw.version fetchPackageMetadata(spec, tree.path, function (er, pkg) { if (er) return next(er) var child = createChild({ package: pkg, loaded: false, parent: tree, path: path.join(tree.path, 'node_modules', pkg.name), realpath: path.resolve(tree.realpath, 'node_modules', pkg.name) }) tree.children.push(child) inflateShrinkwrap(child, sw.dependencies || {}, next) }) }, finishInflating) }
Add replace method to Arithmetic operation
from thinglang.common import ObtainableValue from thinglang.parser.tokens import BaseToken class ArithmeticOperation(BaseToken, ObtainableValue): OPERATIONS = { "+": lambda rhs, lhs: rhs + lhs, "*": lambda rhs, lhs: rhs * lhs, "-": lambda rhs, lhs: rhs - lhs, "/": lambda rhs, lhs: rhs / lhs } def __init__(self, slice): super(ArithmeticOperation, self).__init__(slice) self.lhs, self.operator, self.rhs = slice def evaluate(self, stack): return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack)) def describe(self): return '|{} {} {}|'.format(self[0], self.operator, self[1]) def replace_argument(self, original, replacement): self.arguments = [replacement if x is original else x for x in self.arguments] def __getitem__(self, item): return self.arguments[item]
from thinglang.common import ObtainableValue from thinglang.parser.tokens import BaseToken class ArithmeticOperation(BaseToken, ObtainableValue): OPERATIONS = { "+": lambda rhs, lhs: rhs + lhs, "*": lambda rhs, lhs: rhs * lhs, "-": lambda rhs, lhs: rhs - lhs, "/": lambda rhs, lhs: rhs / lhs } def __init__(self, slice): super(ArithmeticOperation, self).__init__(slice) self.lhs, self.operator, self.rhs = slice def evaluate(self, stack): return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack)) def describe(self): return '{} {} {}'.format(self.lhs, self.operator, self.rhs)
Validate TLS certificate for connections to Elastsearch By default Python elasticsearch client 1.x sets verify_certs to False, which means it doesn't verify TLS certificates when connecting to Elasticsearch over HTTPS and urllib3 prints an InsecureRequestWarning on each request. Setting `verify_certs=True` explicitly removes the warning and prevents connections if the certificate doesn't validate.
from flask import Flask from config import config as configs from flask.ext.bootstrap import Bootstrap from flask.ext.elasticsearch import FlaskElasticsearch from dmutils import init_app, flask_featureflags bootstrap = Bootstrap() feature_flags = flask_featureflags.FeatureFlag() elasticsearch_client = FlaskElasticsearch() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, feature_flags=feature_flags ) elasticsearch_client.init_app( application, verify_certs=True ) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) if configs[config_name].ALLOW_EXPLORER: from .explorer import explorer as explorer_blueprint application.register_blueprint(explorer_blueprint) return application
from flask import Flask from config import config as configs from flask.ext.bootstrap import Bootstrap from flask.ext.elasticsearch import FlaskElasticsearch from dmutils import init_app, flask_featureflags bootstrap = Bootstrap() feature_flags = flask_featureflags.FeatureFlag() elasticsearch_client = FlaskElasticsearch() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, feature_flags=feature_flags ) elasticsearch_client.init_app(application) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) if configs[config_name].ALLOW_EXPLORER: from .explorer import explorer as explorer_blueprint application.register_blueprint(explorer_blueprint) return application
PROC-361: Fix compile error due to invalid import
package com.indeed.proctor.common.dynamic; import com.indeed.proctor.common.model.ConsumableTestDefinition; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class TestNamePatternFilter implements DynamicFilter { private final Pattern pattern; /** * Construct the filter from regular expression string. * * @param regex regular expression for test name pattern * @throws IllegalArgumentException If the regular expression's syntax is invalid. */ public TestNamePatternFilter(final String regex) { try { this.pattern = Pattern.compile(regex); } catch (final PatternSyntaxException e) { throw new IllegalArgumentException("the regular expression for test name pattern has syntax error.", e); } } @Override public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) { return pattern.matcher(testName).matches(); } }
package com.indeed.proctor.common.dynamic; import com.indeed.proctor.common.model.ConsumableTestDefinition; import com.sun.javaws.exceptions.InvalidArgumentException; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class TestNamePatternFilter implements DynamicFilter { private final Pattern pattern; /** * Construct the filter from regular expression string. * @param regex regular expression for test name pattern * @throws IllegalArgumentException If the regular expression's syntax is invalid. */ public TestNamePatternFilter(final String regex) { try { this.pattern = Pattern.compile(regex); } catch (final PatternSyntaxException e) { throw new IllegalArgumentException("the regular expression for test name pattern has syntax error.", e); } } @Override public boolean matches(final String testName, final ConsumableTestDefinition testDefinition) { return pattern.matcher(testName).matches(); } }
Allow to work in DEV or PROD * If using Rpi, add PROD=true environment to enable Serial and GPIO * PROD=TRUE nodemon server.js
'use strict' var express = require('express'), app = express(), config = require('./libs/config'), router = require('./routes'), SerialPort = require('serialport').SerialPort, serialPort = new SerialPort(config.serial.path, { baudrate: config.serial.buadRate }, false), cards = require('./routes/cards'), door = require('./libs/door'), bodyParser = require('body-parser'); app.use(bodyParser.json()) app.get('/', function(req, res){ res.send({ active: true, timestamp: new Date().getTime() }) }) app.use('/api/v1', router) // Server Listener app.listen(config.app.port, config.app.host, function(e) { console.log('Listening on http://%s:%s', config.app.host, config.app.port) if(process.env.PROD) { door.setup(function() { serialPort.open(function (error) { if ( error ) { console.log('failed to open: '+ error); } else { serialPort.on('data', function(data) { cards.isUIDAllowed(data, function(err, test) { if (err) throw err; door.open(); }); }); } }); }); } })
'use strict' var express = require('express'), app = express(), config = require('./libs/config'), router = require('./routes'), SerialPort = require('serialport').SerialPort, serialPort = new SerialPort(config.serial.path, { baudrate: config.serial.buadRate }, false), cards = require('./routes/cards'), door = require('./libs/door'), bodyParser = require('body-parser'); app.use(bodyParser.json()) app.get('/', function(req, res){ res.send({ active: true, timestamp: new Date().getTime() }) }) app.use('/api/v1', router) // Server Listener app.listen(config.app.port, config.app.host, function(e) { console.log('Listening on http://%s:%s', config.app.host, config.app.port) door.setup(function() { serialPort.open(function (error) { if ( error ) { console.log('failed to open: '+ error); } else { serialPort.on('data', function(data) { cards.isUIDAllowed(data, function(err, test) { if (err) throw err; door.open(); }); }); } }); }); })
Use ResourceStream instead of NIO File access
package org.utplsql.api; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; /** This class is getting updated automatically by the build process. * Please do not update its constants manually cause they will be overwritten. * * @author pesse */ public class JavaApiVersionInfo { private JavaApiVersionInfo() { } private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api"; private static String MAVEN_PROJECT_VERSION = "unknown"; static { try { try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); MAVEN_PROJECT_VERSION = reader.readLine(); reader.close(); } } catch ( IOException e ) { System.out.println("WARNING: Could not get Version information!"); } } public static String getVersion() { return MAVEN_PROJECT_VERSION; } public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); } }
package org.utplsql.api; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; /** This class is getting updated automatically by the build process. * Please do not update its constants manually cause they will be overwritten. * * @author pesse */ public class JavaApiVersionInfo { private JavaApiVersionInfo() { } private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api"; private static String MAVEN_PROJECT_VERSION = "unknown"; static { try { MAVEN_PROJECT_VERSION = Files.readAllLines( Paths.get(JavaApiVersionInfo.class.getClassLoader().getResource("utplsql-api.version").toURI()) , Charset.defaultCharset()) .get(0); } catch ( IOException | URISyntaxException e ) { System.out.println("WARNING: Could not get Version information!"); } } public static String getVersion() { return MAVEN_PROJECT_VERSION; } public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); } }
Event: Fix Network Bus Tests (Hopefully)
package jpower.event.test; import jpower.core.utils.ThreadUtils; import jpower.event.ClientEventBus; import jpower.event.EventHandler; import jpower.event.ServerEventBus; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertTrue; public class NetworkBusTest { private boolean worked; private ServerEventBus server; @Before public void prepare() throws IOException { server = new ServerEventBus("127.0.0.1", 46839); } @Test public void testServerClientInteraction() throws IOException { server.start(); server.register(this); ClientEventBus client = new ClientEventBus("127.0.0.1", 46839); client.connect(); client.post(new TestEvent()); ThreadUtils.sleep(1000); assertTrue(worked); worked = false; server.unregister(this); client.register(this); server.post(new TestEvent()); ThreadUtils.sleep(2000); assertTrue(worked); } @EventHandler public void handleEvent(TestEvent event) { worked = event.getPayload().equals("Success"); } }
package jpower.event.test; import jpower.core.utils.ThreadUtils; import jpower.event.ClientEventBus; import jpower.event.EventHandler; import jpower.event.ServerEventBus; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertTrue; public class NetworkBusTest { private boolean worked; private ServerEventBus server; @Before public void prepare() throws IOException { server = new ServerEventBus("127.0.0.1", 46839); } @Test public void testServerClientInteraction() throws IOException { server.start(); server.register(this); ClientEventBus client = new ClientEventBus("127.0.0.1", 46839); client.connect(); client.post(new TestEvent()); ThreadUtils.sleep(1000); assertTrue(worked); worked = false; server.unregister(this); client.register(this); server.post(new TestEvent()); ThreadUtils.sleep(1000); assertTrue(worked); } @EventHandler public void handleEvent(TestEvent event) { worked = event.getPayload().equals("Success"); } }
Replace mini covers with 8tracks icon
function hide_covers() { // Remove covers $(".mix_element div.cover").remove() // Add class so cards can be restyled $(".mix_card.half_card").addClass("ext-coverless_card") // Remove covers on track page $("#cover_art").remove() // Remove covers in the sidebar of a track page $(".card.sidebar_mix .cover").remove() $(".card.sidebar_mix").addClass("ext-coverless_card") // Remove covers in "suggested collections" $(".suggested_collection .covers").remove() $(".suggested_collection").addClass("ext-coverless_card") // Remove mini covers ("Because you liked ____") // Replace with 8tracks icon $(".card img.mini-cover") .replaceWith("<span class='avatar'><span class='i-logo'></span></span>") } function filter() { chrome.storage.local.get("state", function(result) { if(result["state"] == "on") { hide_covers() } }); } // Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run var observer = new MutationObserver(filter) observer.observe(document.getElementById("main"), {childList: true, subtree: true}) filter();
function hide_covers() { // Remove covers $(".mix_element div.cover").remove() // Add class so cards can be restyled $(".mix_card.half_card").addClass("ext-coverless_card") // Remove covers on track page $("#cover_art").remove() // Remove covers in the sidebar of a track page $(".card.sidebar_mix .cover").remove() $(".card.sidebar_mix").addClass("ext-coverless_card") // Remove covers in "suggested collections" $(".suggested_collection .covers").remove() $(".suggested_collection").addClass("ext-coverless_card") } function filter() { chrome.storage.local.get("state", function(result) { if(result["state"] == "on") { hide_covers() } }); } // Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run var observer = new MutationObserver(filter) observer.observe(document.getElementById("main"), {childList: true, subtree: true}) filter();
Fix extra v1 for microservice user login
"use strict"; const config = require("../../../config.js"); const Client = require("node-rest-client").Client; const client = new Client(); module.exports = function (UserSchema) { UserSchema.methods.sendPushNotification = function (payload) { if (!config.pushNotificationsEnabled) return; var user = this; const username = user.email; const pushData = [ Object.assign({username}, payload) ]; const authArgs = { headers: {"Content-Type": "application/json"}, data: { username: config.pushNotificationsServiceUserUsername, password: config.pushNotificationsServiceUserPassword } }; client.post(`${config.authServiceAPI}/auth/login`, authArgs, function (data, response) { const { token } = data; const pushNotificationArgs = { headers: {"Content-Type": "application/json", "Authorization":"Bearer " + token}, data: {pushData} }; client.post(`${config.notificationServiceAPI}/notifications/sendPushNotifications`, pushNotificationArgs, function (data, response) { }); }); }; };
"use strict"; const config = require("../../../config.js"); const Client = require("node-rest-client").Client; const client = new Client(); module.exports = function (UserSchema) { UserSchema.methods.sendPushNotification = function (payload) { if (!config.pushNotificationsEnabled) return; var user = this; const username = user.email; const pushData = [ Object.assign({username}, payload) ]; const authArgs = { headers: {"Content-Type": "application/json"}, data: { username: config.pushNotificationsServiceUserUsername, password: config.pushNotificationsServiceUserPassword } }; client.post(`${config.authServiceAPI}/v1/auth/login`, authArgs, function (data, response) { const { token } = data; const pushNotificationArgs = { headers: {"Content-Type": "application/json", "Authorization":"Bearer " + token}, data: {pushData} }; client.post(`${config.notificationServiceAPI}/notifications/sendPushNotifications`, pushNotificationArgs, function (data, response) { }); }); }; };