text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Disable survey in test runner, which was making the tests fail.
var assert = require('assert'); var config = require("../config/specs"); var geoServer = require("../geojson-server"); var helper = require("./helper"); require("./util/webdriverio-ext"); describe('maputnik', function() { beforeEach(function() { browser.url(config.baseUrl+"?debug&style="+helper.getStyleUrl([ "geojson:example", "raster:raster" ])); browser.execute(function() { localStorage.setItem("survey", true); }); browser.waitForExist(".maputnik-toolbar-link"); browser.flushReactUpdates(); }); // -------- setup -------- require("./util/coverage"); // ----------------------- // ---- All the tests ---- require("./history"); require("./layers"); require("./map"); require("./modals"); require("./screenshots"); // ------------------------ });
var assert = require('assert'); var config = require("../config/specs"); var geoServer = require("../geojson-server"); var helper = require("./helper"); require("./util/webdriverio-ext"); describe('maputnik', function() { beforeEach(function() { browser.url(config.baseUrl+"?debug&style="+helper.getStyleUrl([ "geojson:example", "raster:raster" ])); browser.waitForExist(".maputnik-toolbar-link"); browser.flushReactUpdates(); }); // -------- setup -------- require("./util/coverage"); // ----------------------- // ---- All the tests ---- require("./history"); require("./layers"); require("./map"); require("./modals"); require("./screenshots"); // ------------------------ });
Use plural for slurm endpoints
from . import views def register_in(router): router.register(r'slurm', views.SlurmServiceViewSet, basename='slurm') router.register( r'slurm-service-project-link', views.SlurmServiceProjectLinkViewSet, basename='slurm-spl', ) router.register( r'slurm-allocations', views.AllocationViewSet, basename='slurm-allocation' ) router.register( r'slurm-allocation-usage', views.AllocationUsageViewSet, basename='slurm-allocation-usage', ) router.register( r'slurm-allocation-user-usage', views.AllocationUserUsageViewSet, basename='slurm-allocation-user-usage', ) router.register( r'slurm-associations', views.AssociationViewSet, basename='slurm-association', )
from . import views def register_in(router): router.register(r'slurm', views.SlurmServiceViewSet, basename='slurm') router.register( r'slurm-service-project-link', views.SlurmServiceProjectLinkViewSet, basename='slurm-spl', ) router.register( r'slurm-allocation', views.AllocationViewSet, basename='slurm-allocation' ) router.register( r'slurm-allocation-usage', views.AllocationUsageViewSet, basename='slurm-allocation-usage', ) router.register( r'slurm-allocation-user-usage', views.AllocationUserUsageViewSet, basename='slurm-allocation-user-usage', ) router.register( r'slurm-association', views.AssociationViewSet, basename='slurm-association', )
Use generic Android Emulator, add device-orientation
// Test runner var runTests = require('./affixing-header-specs'), browsers = [ {browserName: 'chrome'}, {browserName: 'firefox'} ]; // var browserConfig = require('./helpers/browser-config'); if (process.env.TRAVIS_JOB_NUMBER) { browsers.push( {browserName: 'Safari', version: '7'}, {browserName: 'Safari', deviceName: 'iPhone Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7', 'device-orientation': 'portrait'}, {browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7', 'device-orientation': 'portrait'}, {browserName: 'Browser', deviceName: 'Android Emulator', platformName: 'Android', platformVersion: '4.4', appiumVersion: '1.3.7', 'device-orientation': 'portrait'}, {browserName: 'internet explorer'} ); } browsers.forEach(function(browser) { runTests(browser); });
// Test runner var runTests = require('./affixing-header-specs'), browsers = [ {browserName: 'chrome'}, {browserName: 'firefox'} ]; // var browserConfig = require('./helpers/browser-config'); if (process.env.TRAVIS_JOB_NUMBER) { browsers.push( {browserName: 'Safari', version: '7'}, {browserName: 'Safari', deviceName: 'iPhone Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'}, {browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'}, {browserName: 'Browser', deviceName: 'Samsung Galaxy S4 Emulator', platformName: 'Android', platformVersion: '4.4', appiumVersion: '1.3.7'}, {browserName: 'internet explorer'} ); } browsers.forEach(function(browser) { runTests(browser); });
Make it run on PyPy for time tests there
# Run some timing tests of JsonData vs SqliteData. import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = "/src/foo/project/file{i}.py".format(i=i) line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print("Overhead: {overhead:.3f}s".format(overhead=overhead)) print("JSON: {jtime:.3f}s".format(jtime=jtime)) print("SQLite: {stime:.3f}s".format(stime=stime)) print("{slower:.3f}x slower".format(slower=stime/jtime))
import random import time from coverage.data import CoverageJsonData from coverage.sqldata import CoverageSqliteData NUM_FILES = 1000 NUM_LINES = 1000 def gen_data(cdata): rnd = random.Random() rnd.seed(17) def linenos(num_lines, prob): return (n for n in range(num_lines) if random.random() < prob) start = time.time() for i in range(NUM_FILES): filename = f"/src/foo/project/file{i}.py" line_data = { filename: dict.fromkeys(linenos(NUM_LINES, .6)) } cdata.add_lines(line_data) cdata.write() end = time.time() delta = end - start return delta class DummyData: def add_lines(self, line_data): return def write(self): return overhead = gen_data(DummyData()) jtime = gen_data(CoverageJsonData("gendata.json")) - overhead stime = gen_data(CoverageSqliteData("gendata.db")) - overhead print(f"Overhead: {overhead:.3f}s") print(f"JSON: {jtime:.3f}s") print(f"SQLite: {stime:.3f}s") print(f"{stime / jtime:.3f}x slower")
Fix release tracking script (again)
module.exports = { /** * Application configuration section * http://pm2.keymetrics.io/docs/usage/application-declaration/ */ apps: [ { name: 'blair', script: 'dist/index.js', env_production: { NODE_ENV: 'production' }, wait_ready: true, listen_timeout: 4000, kill_timeout: 4000 } ], /** * Deployment section * http://pm2.keymetrics.io/docs/usage/deployment/ */ deploy: { production: { key: '~/.ssh/bot-deploy', // TODO: Create a deploy user user: 'gin', host: 'blair-vm.eastus.cloudapp.azure.com', ref: 'origin/master', repo: 'git@github.com:germanoeich/blair-bot.git', path: '/var/opt/node/blair', 'ssh_options': 'StrictHostKeyChecking=no', 'post-deploy': 'yarn && sudo sh ./sentryRelease.sh && yarn build && pm2 startOrRestart ecosystem.config.js --env production' } } }
module.exports = { /** * Application configuration section * http://pm2.keymetrics.io/docs/usage/application-declaration/ */ apps: [ { name: 'blair', script: 'dist/index.js', env_production: { NODE_ENV: 'production' }, wait_ready: true, listen_timeout: 4000, kill_timeout: 4000 } ], /** * Deployment section * http://pm2.keymetrics.io/docs/usage/deployment/ */ deploy: { production: { key: '~/.ssh/bot-deploy', // TODO: Create a deploy user user: 'gin', host: 'blair-vm.eastus.cloudapp.azure.com', ref: 'origin/master', repo: 'git@github.com:germanoeich/blair-bot.git', path: '/var/opt/node/blair', 'ssh_options': 'StrictHostKeyChecking=no', 'post-deploy': 'yarn && sudo ./sentryRelease.sh && yarn build && pm2 startOrRestart ecosystem.config.js --env production' } } }
Make work when astropy isn't installed.
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() paths = [str(tmpdir), astropy_path] if env.get('PYTHONPATH'): paths.append(env.get('PYTHONPATH')) env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) env = os.environ.copy() env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
Handle using the input function in python 2 for getting username for examples Previously this used the builtin input function to get the username. In python 3 this is fine, but if python 2 this is equivalent to eval(raw_input(prompt)) and thus tried to evaluate the username as a variable and typically failed.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from six.moves import input from devicecloud import DeviceCloud def get_authenticated_dc(): while True: base_url = os.environ.get('DC_BASE_URL', 'https://login.etherios.com') username = os.environ.get('DC_USERNAME', None) if not username: username = input("username: ") password = os.environ.get('DC_PASSWORD', None) if not password: password = getpass("password: ") dc = DeviceCloud(username, password, base_url=base_url) if dc.has_valid_credentials(): print("Credentials accepted!") return dc else: print("Invalid username or password provided, try again")
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from devicecloud import DeviceCloud def get_authenticated_dc(): while True: base_url = os.environ.get('DC_BASE_URL', 'https://login.etherios.com') username = os.environ.get('DC_USERNAME', None) if not username: username = input("username: ") password = os.environ.get('DC_PASSWORD', None) if not password: password = getpass("password: ") dc = DeviceCloud(username, password, base_url=base_url) if dc.has_valid_credentials(): print("Credentials accepted!") return dc else: print("Invalid username or password provided, try again")
Fix bug in question review JS that leaves radio buttons incorrectly disabled. The old version behaved incorrectly when there was already a selected radio button on page load, e.g. when form validation failed on the server side or when using the back button.
// This snippet makes sure that only rationales corresponding to the selected answer can be // selected during question review. $(function() { function setRadioButtonStatus(index) { // Disable or enable the radio buttons for the set of rationales with the given index. var disabled = !$('#id_second_answer_choice_' + index).get(0).checked; $('input[type=radio][name=rationale_choice_' + index + ']').each(function() { this.disabled = disabled; if (disabled) this.checked = false; }); } // Disable all radio buttons until the user has chosen an answer. setRadioButtonStatus(0); setRadioButtonStatus(1); // Enable the right set of rationales when the user changes the selected answer. $('input[type=radio][name=second_answer_choice]').change(function() { setRadioButtonStatus(0); setRadioButtonStatus(1); }); });
// This snippet makes sure that only rationales corresponding to the selected answer can be // selected during question review. $(function() { function setRadioButtonStatus(name, disabled) { // Disable or enable or radio buttons for the given name. $('input[type=radio][name=' + name + ']').each(function() { this.disabled = disabled; if (disabled) this.checked = false; }); } // Disable all radio buttons until the user has chosen an answer. setRadioButtonStatus('rationale_choice_0', true); setRadioButtonStatus('rationale_choice_1', true); // Enable the right set of rationales when the user changes the selected answer. $('input[type=radio][name=second_answer_choice]').change(function() { var n, enable_name, disable_name; enable_name = this.id.replace('id_second_answer', 'rationale'); n = enable_name.length - 1 disable_name = enable_name.substr(0, n) + (enable_name[n] == '0' ? '1' : '0'); setRadioButtonStatus(enable_name, false); setRadioButtonStatus(disable_name, true); }); });
Save button needs to extend from KToolbarButtonPost
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Save Toolbar Button Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesToolbarButtonSave extends KToolbarButtonPost { public function getOnClick() { $msg = JText::_('Category must have a title'); return 'var form =document.adminForm;' .'if(form.title.value != \'\'){'.parent::getOnClick().'} ' .'else { alert(\''.$msg.'\'); return false; }'; } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Save Toolbar Button Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesToolbarButtonSave extends KToolbarButtonSave { public function getOnClick() { $msg = JText::_('Category must have a title'); return 'var form =document.adminForm;' .'if(form.title.value != \'\'){'.parent::getOnClick().'} ' .'else { alert(\''.$msg.'\'); return false; }'; } }
Move block parser outside return function
/* * A Class */ var identifierParser = require('./identifier'); var classBlockParser = require('./class_block.js'); var scope = require('../state.js'); module.exports = function(obj) { if(obj.type !== 'CLASS') { throw "This is not a class!"; } var output; var name = identifierParser(obj.name); scope.enterFunction(name); scope.indent(); if(obj.extends === null) { output = 'class ' + name + ' {\n'; } else { output = 'class ' + name + ' extends ' + identifierParser(obj.extends) + ' {\n'; } var len = obj.block.length; for(var i = 0; i < len; i += 1) { output += classBlockParser(obj.block[i]); } output += '}'; scope.leaveFunction(); scope.dedent(); return output; };
/* * A Class */ var identifierParser = require('./identifier'); var scope = require('../state.js'); module.exports = function(obj) { if(obj.type !== 'CLASS') { throw "This is not a class!"; } var classBlockParser = require('./class_block.js'); var output; var name = identifierParser(obj.name); scope.enterFunction(name); scope.indent(); if(obj.extends === null) { output = 'class ' + name + ' {\n'; } else { output = 'class ' + name + ' extends ' + identifierParser(obj.extends) + ' {\n'; } var len = obj.block.length; for(var i = 0; i < len; i += 1) { output += classBlockParser(obj.block[i]); } output += '}'; scope.leaveFunction(); scope.dedent(); return output; };
Add Bovada endpoint for super bowl lines
const axios = require('axios'); const BovadaParser = require('../services/BovadaParser'); axios.defaults.baseURL = 'https://www.bovada.lv/services/sports/event/v2/events/A/description/football'; axios.defaults.headers.common['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'; module.exports.getLines = async () => { const [regSeasonResp, playoffResp, superBowlResp] = await Promise.all([ axios.get('/nfl?marketFilterId=def&preMatchOnly=true&lang=en'), axios.get('/nfl-playoffs?marketFilterId=def&preMatchOnly=true&lang=en'), axios.get('/super-bowl?marketFilterId=def&preMatchOnly=true&lang=en'), ]); return BovadaParser.call(regSeasonResp.data) .concat(BovadaParser.call(playoffResp.data)) .concat(BovadaParser.call(superBowlResp.data)); };
const axios = require('axios'); const BovadaParser = require('../services/BovadaParser'); axios.defaults.baseURL = 'https://www.bovada.lv/services/sports/event/v2/events/A/description/football'; axios.defaults.headers.common['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'; module.exports.getLines = async () => { const [regSeasonResp, playoffResp] = await Promise.all([ axios.get('/nfl?marketFilterId=def&preMatchOnly=true&lang=en'), axios.get('/nfl-playoffs?marketFilterId=def&preMatchOnly=true&lang=en'), ]); return BovadaParser.call(regSeasonResp.data) .concat(BovadaParser.call(playoffResp.data)); };
Revert "The order of the formats matters. Use OrderedDict instead of dict" I can't rely on the order of dict. The control flow is more complex. This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
#!/usr/bin/env python # -*- coding: utf-8 -*-# import requests import cssutils USER_AGENTS = { 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 } def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*-# from collections import OrderedDict import requests import cssutils USER_AGENTS = OrderedDict() USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2 def main(): font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400' sheets={} for (format, ua) in USER_AGENTS.items(): headers = { 'User-Agent': ua, } r =requests.get(font_url, headers=headers) sheets[format] = cssutils.parseString(r.content) if __name__ == '__main__': main()
Remove not used timed absence type 'WORK'
package org.synyx.urlaubsverwaltung.availability.api; import org.synyx.urlaubsverwaltung.period.DayLength; import java.math.BigDecimal; /** * Details for a (partial) absence of a person on a day. */ class TimedAbsence { enum Type { VACATION, SICK_NOTE, FREETIME, PUBLIC_HOLIDAY } private final Type type; private final BigDecimal ratio; private final String partOfDay; public TimedAbsence(DayLength dayLength, Type type) { this.type = type; this.ratio = dayLength.getDuration(); this.partOfDay = dayLength.name(); } public Type getType() { return type; } public BigDecimal getRatio() { return ratio; } public String getPartOfDay() { return partOfDay; } }
package org.synyx.urlaubsverwaltung.availability.api; import org.synyx.urlaubsverwaltung.period.DayLength; import java.math.BigDecimal; /** * Details for a (partial) absence of a person on a day. */ class TimedAbsence { enum Type { VACATION, SICK_NOTE, WORK, FREETIME, PUBLIC_HOLIDAY } private final Type type; private final BigDecimal ratio; private final String partOfDay; public TimedAbsence(DayLength dayLength, Type type) { this.type = type; this.ratio = dayLength.getDuration(); this.partOfDay = dayLength.name(); } public Type getType() { return type; } public BigDecimal getRatio() { return ratio; } public String getPartOfDay() { return partOfDay; } }
Update distutils script. Release builds still twice the size though...
import sys import os from cx_Freeze import setup, Executable paths = [] paths.extend(sys.path) paths.append('src') build_exe_options = { 'path': paths, 'packages': ['whacked4'], 'include_files': ['res', 'cfg', 'docs', 'LICENSE', 'README.md'], 'optimize': 2, 'include_msvcr': True } base = None if sys.platform == 'win32': base = 'Win32GUI' exe = Executable( 'src/main.py', base=base, targetName=os.environ['app_name_lower'] + '.exe', icon='res/icon-hatchet.ico' ) setup( name = os.environ['app_title'], version = os.environ['app_version_value'], description = os.environ['app_description'], options = {'build_exe': build_exe_options}, executables = [exe] )
import sys import os from cx_Freeze import setup, Executable paths = [] paths.extend(sys.path) paths.append('whacked4') build_exe_options = { 'packages': [], 'path': paths, 'include_files': ['res', 'cfg', 'docs', 'LICENSE', 'README.md'], 'optimize': 2, 'include_msvcr': True } build_exe_options['path'].append('src') base = None if sys.platform == 'win32': base = 'Win32GUI' exe = Executable( 'src/main.py', base=base, targetName=os.environ['app_name_lower'] + '.exe', icon='res/icon-hatchet.ico' ) setup( name = os.environ['app_title'], version = os.environ['app_version_value'], description = os.environ['app_description'], options = {'build_exe': build_exe_options}, executables = [exe] )
Add cname option to init wrapper
import apiClient from 'api-client'; import loader from 'loader'; const init = (apikey, security, cname) => { const client = apiClient.init(apikey, security, cname); return { getSecurity() { return client.getSecurity(); }, setSecurity(sec) { return client.setSecurity(sec); }, pick(options) { return loader.loadModule(ENV.picker) .then((pickerConstructor) => { return pickerConstructor(client, options); }); }, storeURL(url, options) { return client.storeURL(url, options); }, transform(url, options) { return client.transform(url, options); }, upload(file, uploadOptions, storeOptions, token) { return client.upload(file, uploadOptions, storeOptions, token); }, retrieve(handle, options) { return client.retrieve(handle, options); }, remove(handle) { return client.remove(handle); }, metadata(handle, options) { return client.metadata(handle, options); }, }; }; export default { version: '@{VERSION}', init, };
import apiClient from 'api-client'; import loader from 'loader'; const init = (apikey, security) => { const client = apiClient.init(apikey, security); return { getSecurity() { return client.getSecurity(); }, setSecurity(sec) { return client.setSecurity(sec); }, pick(options) { return loader.loadModule(ENV.picker) .then((pickerConstructor) => { return pickerConstructor(client, options); }); }, storeURL(url, options) { return client.storeURL(url, options); }, transform(url, options) { return client.transform(url, options); }, upload(file, uploadOptions, storeOptions, token) { return client.upload(file, uploadOptions, storeOptions, token); }, retrieve(handle, options) { return client.retrieve(handle, options); }, remove(handle) { return client.remove(handle); }, metadata(handle, options) { return client.metadata(handle, options); }, }; }; export default { version: '@{VERSION}', init, };
Update so ony varaibles are passed to end()
<?php namespace Opg\Lpa\DataModel\Validator\Constraints; /** * This train should be included in any 'Validator\Constraints' class that wants to use * its original Symfony Validator (which should be all non-custom ones!). * * Class ValidatorPathTrait * @package Opg\Lpa\DataModel\Validator\Constraints */ trait ValidatorPathTrait { /** * Returns the name of the class that validates this constraint. * * This has been changed to point back to the original Symfony Validators. * * @return string * * @api */ public function validatedBy() { $pathParts = explode('\\',get_class($this)); return 'Symfony\\Component\\Validator\\Constraints\\'.end( $pathParts ).'Validator'; } } // trait
<?php namespace Opg\Lpa\DataModel\Validator\Constraints; /** * This train should be included in any 'Validator\Constraints' class that wants to use * its original Symfony Validator (which should be all non-custom ones!). * * Class ValidatorPathTrait * @package Opg\Lpa\DataModel\Validator\Constraints */ trait ValidatorPathTrait { /** * Returns the name of the class that validates this constraint. * * This has been changed to point back to the original Symfony Validators. * * @return string * * @api */ public function validatedBy() { return 'Symfony\\Component\\Validator\\Constraints\\'.end(explode('\\',get_class($this))).'Validator'; } } // trait
Add back the empty initial response for ANONYMOUS
/* * 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.messaginghub.amqperative.impl.sasl; import org.apache.qpid.proton4j.amqp.Symbol; import org.apache.qpid.proton4j.buffer.ProtonBuffer; /** * Implements the Anonymous SASL authentication mechanism. */ public class AnonymousMechanism extends AbstractMechanism { public static final Symbol ANONYMOUS = Symbol.valueOf("ANONYMOUS"); @Override public Symbol getName() { return ANONYMOUS; } @Override public ProtonBuffer getInitialResponse() { return EMPTY; } }
/* * 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.messaginghub.amqperative.impl.sasl; import org.apache.qpid.proton4j.amqp.Symbol; /** * Implements the Anonymous SASL authentication mechanism. */ public class AnonymousMechanism extends AbstractMechanism { public static final Symbol ANONYMOUS = Symbol.valueOf("ANONYMOUS"); @Override public Symbol getName() { return ANONYMOUS; } }
Add WorkSpaces::ConnectionAlias per 2020-10-01 changes
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 18.6.0 from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import boolean from .validators import integer class ConnectionAlias(AWSObject): resource_type = "AWS::WorkSpaces::ConnectionAlias" props = { 'ConnectionString': (basestring, True), 'Tags': (Tags, False), } class WorkspaceProperties(AWSProperty): props = { 'ComputeTypeName': (basestring, False), 'RootVolumeSizeGib': (integer, False), 'RunningMode': (basestring, False), 'RunningModeAutoStopTimeoutInMinutes': (integer, False), 'UserVolumeSizeGib': (integer, False), } class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'RootVolumeEncryptionEnabled': (boolean, False), 'Tags': (Tags, False), 'UserName': (basestring, True), 'UserVolumeEncryptionEnabled': (boolean, False), 'VolumeEncryptionKey': (basestring, False), 'WorkspaceProperties': (WorkspaceProperties, False), }
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .validators import boolean, integer class WorkspaceProperties(AWSProperty): props = { 'ComputeTypeName': (basestring, False), 'RootVolumeSizeGib': (integer, False), 'RunningMode': (basestring, False), 'RunningModeAutoStopTimeoutInMinutes': (integer, False), 'UserVolumeSizeGib': (integer, False), } class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), 'RootVolumeEncryptionEnabled': (boolean, False), 'Tags': (Tags, False), 'UserVolumeEncryptionEnabled': (boolean, False), 'VolumeEncryptionKey': (basestring, False), 'WorkspaceProperties': (WorkspaceProperties, False), }
Remove leftover relic from supporting CPython 2.6.
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
Fix linting error with HTTPCat plugin
'use strict'; let BotPlug = require( './BotPlug.js' ); let Telegram = require( 'node-telegram-bot-api' ); let config = require( '../config.js' ).telegram; let telegramClient = new Telegram( config.apiKey ); class HttpCatBotPlug extends BotPlug { constructor( bot ){ super( bot ); this.catCommand = '!httpcat'; this.detectCommand( this.catCommand, ( from, text ) => { var number = Number( text.substring( this.catCommand.length ) ); this.sendCat( from, number ); }); } sendCat( user, cat ){ telegramClient.sendMessage( config.users[ user.toLowerCase() ], 'https://http.cat/' + cat ); } } module.exports = HttpCatBotPlug;
'use strict'; let BotPlug = require( './BotPlug.js' ); let Telegram = require( 'node-telegram-bot-api' ); let config = require( '../config.js' ).telegram; let telegramClient = new Telegram( config.apiKey ); class HttpCatBotPlug extends BotPlug { constructor( bot ){ super( bot ); this.catCommand = '!httpcat'; this.detectCommand( this.catCommand, ( from, text, message ) => { var number = Number( text.substring( this.catCommand.length ) ); this.sendCat( from, number ); }); } sendCat( user, cat ){ telegramClient.sendMessage( config.users[ user.toLowerCase() ], 'https://http.cat/' + cat ); } } module.exports = HttpCatBotPlug;
Fix for variations in language tags
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; import Jed from "jed"; import locales from "./locales"; // Convert a language tag to a dash-separated lowercase string function normalize(tag) { return tag.replace(/_/g, "-").toLowerCase(); } export function init(lang) { if (!lang) { lang = window.navigator.languages && window.navigator.languages.length ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage || "en"); } // Normalize the given language tag and extract the language code alone lang = normalize(lang); var langShort = lang.split("-")[0]; // Find the user language in the available locales var allLanguages = Object.keys(locales).map(normalize); var langIndex = allLanguages.indexOf(lang); if (langIndex < 0) { langIndex = allLanguages.indexOf(langShort); } var localeData = langIndex >= 0 ? locales[Object.keys(locales)[langIndex]] : {}; return new Jed(localeData); }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; import Jed from "jed"; import locales from "./locales"; export function init(lang) { if (!lang) { lang = window.navigator.languages && window.navigator.languages.length ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage || "en"); } var langShort = lang.split(/[-_]/)[0]; var localeData = locales[lang] || locales[langShort] || {}; console.log(`User languages: ${lang}, ${langShort}. Using ${locales[lang] ? lang : locales[langShort] ? langShort : "en (default)"}`); return new Jed(localeData); }
Fix misspelled words in a comment.
/** * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 main import "github.com/go-kit/kit/metrics" // This is a non-concurrent safe counter that lets a single goroutine aggregate // a metric before adding them to a larger correlated metric. type SimpleCounter struct { // The active count Count float64 } // With implements Counter. func (s *SimpleCounter) With(labelValues ...string) metrics.Counter { return s } // Add implements Counter. func (s *SimpleCounter) Add(delta float64) { if 0.0 < delta { s.Count += delta } }
/** * Copyright 2018 Comcast Cable Communications Management, LLC * * 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 main import "github.com/go-kit/kit/metrics" // This is a non-concurent safe counter that lets a single goroutine agregate // a metric before adding them to a larger correlated metric. type SimpleCounter struct { // The active count Count float64 } // With implements Counter. func (s *SimpleCounter) With(labelValues ...string) metrics.Counter { return s } // Add implements Counter. func (s *SimpleCounter) Add(delta float64) { if 0.0 < delta { s.Count += delta } }
Fix for PHP < 5.6
<?php namespace Stolz\HtmlTidy; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['stolz.tidy']; } /** * Register bindings in the container. * * @return void */ public function register() { // Merge user's configuration $this->mergeConfigFrom(__DIR__ . '/config.php', 'tidy'); // Bind 'stolz.tidy' shared component to the IoC container $this->app->singleton('stolz.tidy', function ($app) { return new Tidy($app['config']['tidy']); }); } /** * Perform post-registration booting of services. * * @return void */ public function boot() { // Register paths to be published by 'vendor:publish' artisan command $this->publishes([ __DIR__ . '/config.php' => config_path('tidy.php'), ]); } }
<?php namespace Stolz\HtmlTidy; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Path to the default config file. * * @var string */ protected $configFile = __DIR__ . '/config.php'; /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['stolz.tidy']; } /** * Register bindings in the container. * * @return void */ public function register() { // Merge user's configuration $this->mergeConfigFrom($this->configFile, 'tidy'); // Bind 'stolz.tidy' shared component to the IoC container $this->app->singleton('stolz.tidy', function ($app) { return new Tidy($app['config']['tidy']); }); } /** * Perform post-registration booting of services. * * @return void */ public function boot() { // Register paths to be published by 'vendor:publish' artisan command $this->publishes([ $this->configFile => config_path('tidy.php'), ]); } }
Use dataType: json for sortable tables
//= require solidus_admin/Sortable Spree.ready(function() { var sortable_tables = document.querySelectorAll('table.sortable'); _.each(sortable_tables, function(table) { var url = table.getAttribute('data-sortable-link'); var tbody = table.querySelector('tbody'); var sortable = Sortable.create(tbody,{ handle: ".handle", onEnd: function(e) { var positions = {}; _.each(e.to.querySelectorAll('tr'), function(el, index) { var idAttr = el.id; if (idAttr) { var objId = idAttr.split('_').slice(-1); positions['positions['+objId+']'] = index + 1; } }); Spree.ajax({ type: 'POST', dataType: 'json', url: url, data: positions, }); } }); }); });
//= require solidus_admin/Sortable Spree.ready(function() { var sortable_tables = document.querySelectorAll('table.sortable'); _.each(sortable_tables, function(table) { var url = table.getAttribute('data-sortable-link'); var tbody = table.querySelector('tbody'); var sortable = Sortable.create(tbody,{ handle: ".handle", onEnd: function(e) { var positions = {}; _.each(e.to.querySelectorAll('tr'), function(el, index) { var idAttr = el.id; if (idAttr) { var objId = idAttr.split('_').slice(-1); positions['positions['+objId+']'] = index + 1; } }); Spree.ajax({ type: 'POST', dataType: 'script', url: url, data: positions, }); } }); }); });
Send user to home page wen logging out
define([ 'Backbone', //Template 'text!templates/topNavTemplate.html' ], function( Backbone, //Template topNavTemplate ){ var TopNavView = Backbone.View.extend({ events: { 'click a' : 'preventDefault', 'click .logout' : 'logout', 'click .login' : 'login' }, template: _.template(topNavTemplate), initialize: function(){ this.model.bind('change', this.render, this); }, preventDefault: function(event){ event.preventDefault(); }, logout: function(){ var router = this.options.router; this.model.logout(function(){ router.navigate('', true); }); }, login: function(){ this.model.clear({silent: true}); var form = $('#login-form').serialize(); this.model.login(form); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); } }); return TopNavView; });
define([ 'Backbone', //Template 'text!templates/topNavTemplate.html' ], function( Backbone, //Template topNavTemplate ){ var TopNavView = Backbone.View.extend({ events: { 'click a' : 'preventDefault', 'click .logout' : 'logout', 'click .login' : 'login' }, template: _.template(topNavTemplate), initialize: function(){ this.model.bind('change', this.render, this); }, preventDefault: function(event){ event.preventDefault(); }, logout: function(){ this.model.logout(); }, login: function(){ this.model.clear({silent: true}); var form = $('#login-form').serialize(); this.model.login(form); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); } }); return TopNavView; });
Add return in index to prevent 2 write responses
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) http.Handler, template *template.Template, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pipelineDB, err := pipelineDBFactory.BuildWithName(atc.DefaultPipelineName) if err != nil { if err == sql.ErrNoRows { err = template.Execute(w, TemplateData{}) if err != nil { log.Fatal("failed-to-task-template", err, lager.Data{}) } return } logger.Error("failed-to-load-pipelinedb", err) w.WriteHeader(http.StatusInternalServerError) return } pipelineHandler(pipelineDB).ServeHTTP(w, r) }) }
package index import ( "database/sql" "html/template" "log" "net/http" "github.com/concourse/atc" "github.com/concourse/atc/db" "github.com/pivotal-golang/lager" ) type TemplateData struct{} func NewHandler( logger lager.Logger, pipelineDBFactory db.PipelineDBFactory, pipelineHandler func(db.PipelineDB) http.Handler, template *template.Template, ) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pipelineDB, err := pipelineDBFactory.BuildWithName(atc.DefaultPipelineName) if err != nil { if err == sql.ErrNoRows { err = template.Execute(w, TemplateData{}) if err != nil { log.Fatal("failed-to-task-template", err, lager.Data{}) } } logger.Error("failed-to-load-pipelinedb", err) w.WriteHeader(http.StatusInternalServerError) return } pipelineHandler(pipelineDB).ServeHTTP(w, r) }) }
Remove imperative code in favor of declarative statements for building testsuite
const Testcase = require('./Testcase'); class Testsuite { constructor (id, result) { let testcases = result.testResults .filter(result => (result.status !== 'pending')) .map(result => new Testcase(result)); let suite = { _attr: { id, name: result.testFilePath, errors: 0, package: result.testFilePath, hostname: 'localhost', tests: (result.numPendingTests + result.numFailingTests + result.numPassingTests), failures: result.numFailingTests, time: (result.perfStats.end - result.perfStats.start) / 1000, timestamp: new Date(result.perfStats.start).toISOString().slice(0, -5) } }; this.testsuite = [suite, { properties: [] }] .concat( testcases, { 'system-out': {} }, { 'system-err': {} } ); } } module.exports = Testsuite;
const Testcase = require('./Testcase'); class Testsuite { constructor (id, result) { this.testsuite = [{ _attr: { id, name: result.testFilePath, errors: 0, package: result.testFilePath, hostname: 'localhost', tests: (result.numPendingTests + result.numFailingTests + result.numPassingTests), failures: result.numFailingTests, time: (result.perfStats.end - result.perfStats.start) / 1000, timestamp: new Date(result.perfStats.start).toISOString().slice(0, -5) } }]; this.testsuite.push({ properties: [] }); result.testResults .filter(result => (result.status !== 'pending')) .forEach(result => this.testsuite.push(new Testcase(result))); this.testsuite.push({ 'system-out': {} }); this.testsuite.push({ 'system-err': {} }); } } module.exports = Testsuite;
Test zip, and print format
#!/usr/bin/env python import sys import pickle # Test zip, and format in print names = ["xxx", "yyy", "zzz"] ages = [18, 19, 20] persons = zip(names, ages) for name, age in persons: print "{0}'s age is {1}".format(name, age) # Check argument if len(sys.argv) != 2: print("%s filename" % sys.argv[0]) raise SystemExit(1) # Write tuples file = open(sys.argv[1], "wb"); line = [] while True: print("Enter name, age, score (ex: zzz, 16, 90) or quit"); line = sys.stdin.readline() if line == "quit\n": break raws = line.split(",") name = raws[0] age = int(raws[1]) score = int(raws[2]) record = (name, age, score) pickle.dump(record, file) file.close() # Read back file = open(sys.argv[1], "rb"); while True: try: record = pickle.load(file) print record name, age, score= record print("name = %s" % name) print("name = %d" % age) print("name = %d" % score) except (EOFError): break file.close()
#!/usr/bin/env python import sys import pickle # Check argument if len(sys.argv) != 2: print("%s filename" % sys.argv[0]) raise SystemExit(1) # Write tuples file = open(sys.argv[1], "wb"); line = [] while True: print("Enter name, age, score (ex: zzz, 16, 90) or quit"); line = sys.stdin.readline() if line == "quit\n": break raws = line.split(",") name = raws[0] age = int(raws[1]) score = int(raws[2]) record = (name, age, score) pickle.dump(record, file) file.close() # Read back file = open(sys.argv[1], "rb"); while True: try: record = pickle.load(file) print record name, age, score= record print("name = %s" % name) print("name = %d" % age) print("name = %d" % score) except (EOFError): break file.close()
ENH: Add new core.config API functions to the pandas top level module
# pylint: disable=W0614,W0401,W0611 import numpy as np from pandas.core.algorithms import factorize, match, unique, value_counts from pandas.core.common import isnull, notnull, save, load from pandas.core.categorical import Categorical, Factor from pandas.core.format import (set_printoptions, reset_printoptions, set_eng_float_format) from pandas.core.index import Index, Int64Index, MultiIndex from pandas.core.series import Series, TimeSeries from pandas.core.frame import DataFrame from pandas.core.panel import Panel from pandas.core.groupby import groupby from pandas.core.reshape import (pivot_simple as pivot, get_dummies, lreshape) WidePanel = Panel from pandas.tseries.offsets import DateOffset from pandas.tseries.tools import to_datetime from pandas.tseries.index import (DatetimeIndex, Timestamp, date_range, bdate_range) from pandas.tseries.period import Period, PeriodIndex # legacy from pandas.core.daterange import DateRange # deprecated import pandas.core.datetools as datetools from pandas.core.config import get_option,set_option,reset_option,\ reset_options,describe_options
# pylint: disable=W0614,W0401,W0611 import numpy as np from pandas.core.algorithms import factorize, match, unique, value_counts from pandas.core.common import isnull, notnull, save, load from pandas.core.categorical import Categorical, Factor from pandas.core.format import (set_printoptions, reset_printoptions, set_eng_float_format) from pandas.core.index import Index, Int64Index, MultiIndex from pandas.core.series import Series, TimeSeries from pandas.core.frame import DataFrame from pandas.core.panel import Panel from pandas.core.groupby import groupby from pandas.core.reshape import (pivot_simple as pivot, get_dummies, lreshape) WidePanel = Panel from pandas.tseries.offsets import DateOffset from pandas.tseries.tools import to_datetime from pandas.tseries.index import (DatetimeIndex, Timestamp, date_range, bdate_range) from pandas.tseries.period import Period, PeriodIndex # legacy from pandas.core.daterange import DateRange # deprecated import pandas.core.datetools as datetools
Fix linting issue with Posts
import React, { PropTypes } from 'react' import { Link } from 'react-router' import styles from './index.module.css' function Posts (props) { const posts = props.posts.map((post) => { const postRawDate = post.data.date const postDate = new Date(postRawDate).toDateString() return ( <li key={post.path} > <Link to={post.path}> <article className={styles.post}> <h1 className={styles.heading}>{post.data.title}</h1> <time className={styles.time} dateTime={postRawDate}>{postDate}</time> </article> </Link> </li> ) }) return ( <div className={styles.container}> <ul className={styles.list}> {posts} </ul> </div> ) } Posts.propTypes = { posts: PropTypes.array.isRequired } export default Posts
import React, { PropTypes } from 'react' import { Link } from 'react-router' import styles from './index.module.css' function Posts (props) { const posts = props.posts.map((post) => { const postRawDate = post.data.date const postDate = new Date(postRawDate).toDateString() return ( <li key={post.path} > <Link to={post.path}> <article className={styles.post}> <h1 className={styles.heading}>{post.data.title}</h1> <time className={styles.time} dateTime={postRawDate}>{postDate}</time> </article> </Link> </li> ) }) return ( <div className={styles.container}> <ul className={styles.list}> {posts} </ul> </div> ) } Posts.propTypes = { posts: PropTypes.array.isRequired } export default Posts
Add official OSI name in the license metadata This makes it easier for automatic license checkers to verify the license of this package.
import os from setuptools import setup # type: ignore VERSION = '4.4.1' setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, license='MIT License', description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Operating System :: OS Independent", ], )
import os from setuptools import setup # type: ignore VERSION = '4.4.1' setup( name='conllu', packages=["conllu"], python_requires=">=3.6", package_data={ "": ["py.typed"] }, version=VERSION, description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), long_description_content_type="text/markdown", author=u'Emil Stenström', author_email="emil@emilstenstrom.se", url='https://github.com/EmilStenstrom/conllu/', keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Operating System :: OS Independent", ], )
Return blank if length is more than 39.
var url = require('url'); var express = require('express'); var router = express.Router(); var request = require("request"); router.get('/', function (req, res) { res.render('index', {title: 'Github User Search'}); }); //TODO: // Cache expiry - store cache data as object with time //Only pull content if time is greater than expiry time. var CACHE = {}; //this can be moved to another file. router.get("/search", function (req, res) { var url_parts = url.parse(req.url, true); var query = url_parts.query; //if blank or username is more than 39 ignore if(query.length===0 || query.length>39) res.send({}); if (CACHE[query.query]) return res.send(CACHE[query.query]); request.get({ url: "https://api.github.com/users/" + query.query, headers: {Accept: " application/vnd.github.preview", "User-Agent": "test-ws"} }, function (error, response, body) { res.send((CACHE[query.query] = JSON.parse(body))); }); }); module.exports = router;
var url = require('url'); var express = require('express'); var router = express.Router(); var request = require("request"); router.get('/', function (req, res) { res.render('index', {title: 'Github User Search'}); }); //TODO: // Cache expiry - store cache data as object with time //Only pull content if time is greater than expiry time. var CACHE = {}; //this can be moved to another file. router.get("/search", function (req, res) { var url_parts = url.parse(req.url, true); var query = url_parts.query; if(query.length===0) res.send({}); if (CACHE[query.query]) return res.send(CACHE[query.query]); request.get({ url: "https://api.github.com/users/" + query.query, headers: {Accept: " application/vnd.github.preview", "User-Agent": "test-ws"} }, function (error, response, body) { res.send((CACHE[query.query] = JSON.parse(body))); }); }); module.exports = router;
Remove header AFTER response is received.
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.springframework.cloud.gateway.filter.factory; import org.springframework.tuple.Tuple; import org.springframework.web.server.WebFilter; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; /** * @author Spencer Gibb */ public class SetResponseHeaderWebFilterFactory implements WebFilterFactory { @Override public List<String> argNames() { return Arrays.asList(NAME_KEY, VALUE_KEY); } @Override public WebFilter apply(Tuple args) { final String header = args.getString(NAME_KEY); final String value = args.getString(VALUE_KEY); return (exchange, chain) -> chain.filter(exchange).then(Mono.fromRunnable(() -> { exchange.getResponse().getHeaders().set(header, value); })); } }
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.springframework.cloud.gateway.filter.factory; import org.springframework.tuple.Tuple; import org.springframework.web.server.WebFilter; import java.util.Arrays; import java.util.List; /** * @author Spencer Gibb */ public class SetResponseHeaderWebFilterFactory implements WebFilterFactory { @Override public List<String> argNames() { return Arrays.asList(NAME_KEY, VALUE_KEY); } @Override public WebFilter apply(Tuple args) { final String header = args.getString(NAME_KEY); final String value = args.getString(VALUE_KEY); return (exchange, chain) -> { exchange.getResponse().getHeaders().set(header, value); return chain.filter(exchange); }; } }
Add root level js files to eslint
var gulp = require('gulp'); var eslint = require('gulp-eslint'); var runSequence = require('run-sequence'); var concat = require('gulp-concat'); var benchmark = require('gulp-bench'); var gulpShell = require('gulp-shell'); // Registers build tasks require('./build/gulp-clean'); require('./build/gulp-build'); require('./build/gulp-test'); require('./build/gulp-perf'); var srcDir = 'lib'; gulp.task('lint', function() { return gulp.src(['*.js', srcDir + '/**/*.js']). pipe(eslint({ globals: { 'require': false, 'module': false }, reset: true, // dz: remove me after linting is finished, else i can't do one at the time useEslintrc: true })). pipe(eslint.format()). pipe(eslint.failOnError()); // dz: change back after finishing to failAfterError }); gulp.task('doc', ['clean.doc', 'doc-d']); gulp.task('doc-d', gulpShell.task([ './node_modules/.bin/jsdoc lib -r -d doc -c ./build/jsdoc.json --verbose' ])); // Run in serial to fail build if lint fails. gulp.task('default', ['build-with-lint', 'lint']);
var gulp = require('gulp'); var eslint = require('gulp-eslint'); var runSequence = require('run-sequence'); var concat = require('gulp-concat'); var benchmark = require('gulp-bench'); var gulpShell = require('gulp-shell'); // Registers build tasks require('./build/gulp-clean'); require('./build/gulp-build'); require('./build/gulp-test'); require('./build/gulp-perf'); var srcDir = 'lib'; gulp.task('lint', function() { return gulp.src(srcDir + '/**/*.js'). pipe(eslint({ globals: { 'require': false, 'module': false }, reset: true, // dz: remove me after linting is finished, else i can't do one at the time useEslintrc: true })). pipe(eslint.format()). pipe(eslint.failOnError()); // dz: change back after finishing to failAfterError }); gulp.task('doc', ['clean.doc', 'doc-d']); gulp.task('doc-d', gulpShell.task([ './node_modules/.bin/jsdoc lib -r -d doc -c ./build/jsdoc.json --verbose' ])); // Run in serial to fail build if lint fails. gulp.task('default', ['build-with-lint', 'lint']);
Remove unused imports from helloworld sample
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.msf4j.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; /** * Hello service resource class. */ @Path("/hello") public class HelloService { @GET @Path("/{name}") public String hello(@PathParam("name") String name) { System.out.println("Hello"); return "Hello " + name; } }
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.msf4j.example; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; /** * Hello service resource class. */ @Path("/hello") public class HelloService { @GET @Path("/{name}") public String hello(@PathParam("name") String name) { System.out.println("Hello"); return "Hello " + name; } }
Revert "only including tracking if it was not already included before" This reverts commit bfc2b27e3e2386687a8bbf24f36bef46874d939e.
window.$ = window.Zepto = require('zepto-browserify').$; require('./components/polyfills.js')(); let warn = (msg) => { if (!window || !window.console) { return; } window.console.warn(msg); }; window.Storage = require('showcar-storage'); window.Pager = require('./components/pager.js'); require('showcar-icons'); // require('showcar-tracking'); require('./components/custom-dropdown.js'); Zepto(_ => { require('./components/navigation.js'); require('./components/rotating-arrow.js')(); require('./components/sticky.js')(); require('./components/collapse.js')(); require('./components/scroll.js'); }); if (!window.notification) { window.notification = require('./components/notification.js'); } else { warn('window.notification is already registered.'); }
window.$ = window.Zepto = require('zepto-browserify').$; require('./components/polyfills.js')(); let warn = (msg) => { if (!window || !window.console) { return; } window.console.warn(msg); }; window.Storage = require('showcar-storage'); window.Pager = require('./components/pager.js'); require('showcar-icons'); if (document.createElement('as24-tracking').constructor !== HTMLElement) { // only requiring showcar-tracking when it was not already included before require('showcar-tracking'); } require('./components/custom-dropdown.js'); Zepto(_ => { require('./components/navigation.js'); require('./components/rotating-arrow.js')(); require('./components/sticky.js')(); require('./components/collapse.js')(); require('./components/scroll.js'); }); if (!window.notification) { window.notification = require('./components/notification.js'); } else { warn('window.notification is already registered.'); }
Make .json config paths relative
var nconf = require('nconf'); var scheConf = new nconf.Provider(); var mainConf = new nconf.Provider(); var optConf = new nconf.Provider(); var name2Conf = {"sche" : scheConf, "main": mainConf, "opt": optConf}; scheConf.file({file: __dirname + '/app/schedules.json'}); mainConf.file({file: __dirname + '/app/schools.json'}); optConf.file({file: __dirname + '/app/options.json'}); function saveSettings(settingKey, settingValue, file) { var conf = name2Conf[file]; conf.set(settingKey, settingValue); conf.save(); } function readSettings(settingKey, file) { var conf = name2Conf[file]; conf.load(); return conf.get(settingKey); } function getSettings(file) { var conf = name2Conf[file]; conf.load(); return conf.get(); } function clearSetting(key, file) { var conf = name2Conf[file]; conf.load(); conf.clear(key); conf.save(); } module.exports = { saveSettings: saveSettings, readSettings: readSettings, getSettings: getSettings, clearSetting: clearSetting };
var nconf = require('nconf'); var scheConf = new nconf.Provider(); var mainConf = new nconf.Provider(); var optConf = new nconf.Provider(); var name2Conf = {"sche" : scheConf, "main": mainConf, "opt": optConf}; scheConf.file({file: './app/schedules.json'}); mainConf.file({file: './app/schools.json'}); optConf.file({file: './app/options.json'}); function saveSettings(settingKey, settingValue, file) { var conf = name2Conf[file]; conf.set(settingKey, settingValue); conf.save(); } function readSettings(settingKey, file) { var conf = name2Conf[file]; conf.load(); return conf.get(settingKey); } function getSettings(file) { var conf = name2Conf[file]; conf.load(); return conf.get(); } function clearSetting(key, file) { var conf = name2Conf[file]; conf.load(); conf.clear(key); conf.save(); } module.exports = { saveSettings: saveSettings, readSettings: readSettings, getSettings: getSettings, clearSetting: clearSetting };
Add function to save tpcc-mysql results
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' Created on 2015-06-19 @author: mizhon ''' #from common import CommonActions from Logs import logger log = logger.Log() class TpccmysqlActions(object): @classmethod def ta_get_cmds(cls, cmd_action): try: cmds = None if cmd_action == 'prepare': pass elif cmd_action == 'run': pass elif cmd_action == 'cleanup': pass return cmds except Exception as e: log.error(e) @classmethod def ta_get_scenario_info(cls): pass @classmethod def ta_save_results(cls, result): pass
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' Created on 2015-06-19 @author: mizhon ''' #from common import CommonActions from Logs import logger log = logger.Log() class TpccmysqlActions(object): @classmethod def ta_get_cmds(cls, cmd_action): try: cmds = None if cmd_action == 'prepare': pass elif cmd_action == 'run': pass elif cmd_action == 'cleanup': pass return cmds except Exception as e: log.error(e) @classmethod def ta_get_scenario_info(cls): pass
Use `package.name` in the app definition.
// New Relic Server monitoring support if ( process.env.NEW_RELIC_ENABLED ) { require( "newrelic" ); } const restify = require('restify'); const applyRoutes = require('./routes'); const logger = require('./lib/logger') const middleware = require('./lib/middleware') const package = require('../package') const server = restify.createServer({ name: package.name, version: package.version, log: logger, }); server.pre(restify.pre.sanitizePath()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser({mapParams: false})); server.use(restify.bodyParser({mapParams: false, rejectUnknown: true})); server.use(middleware.verifyRequest()) server.use(middleware.attachResolvePath()) server.use(middleware.attachErrorLogger()) applyRoutes(server); module.exports = server; if (!module.parent) { server.listen(process.env.PORT || 8080, function () { console.log('%s listening at %s', server.name, server.url); }); }
// New Relic Server monitoring support if ( process.env.NEW_RELIC_ENABLED ) { require( "newrelic" ); } const restify = require('restify'); const applyRoutes = require('./routes'); const logger = require('./lib/logger') const middleware = require('./lib/middleware') const package = require('../package') const server = restify.createServer({ name: 'openbadger', version: package.version, log: logger, }); server.pre(restify.pre.sanitizePath()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser({mapParams: false})); server.use(restify.bodyParser({mapParams: false, rejectUnknown: true})); server.use(middleware.verifyRequest()) server.use(middleware.attachResolvePath()) server.use(middleware.attachErrorLogger()) applyRoutes(server); module.exports = server; if (!module.parent) { server.listen(process.env.PORT || 8080, function () { console.log('%s listening at %s', server.name, server.url); }); }
Make npm link work with babel-loader.
const { mix } = require('laravel-mix'), webpack = require('webpack'); mix .webpackConfig({ plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'Tether': 'tether', 'window.axios': 'axios' }) ], resolve: { symlinks: false } }) .copy( 'node_modules/kent-bar/build/deploy/assets/app.js', 'public/js/kent-bar.js' ) .copy( 'node_modules/kent-bar/build/deploy/assets/main.css', 'public/css/kent-bar.css' ) .js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap', 'element-ui']);
const { mix } = require('laravel-mix'), webpack = require('webpack'); mix .webpackConfig({ plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'Tether': 'tether', 'window.axios': 'axios' }) ] }) .copy( 'node_modules/kent-bar/build/deploy/assets/app.js', 'public/js/kent-bar.js' ) .copy( 'node_modules/kent-bar/build/deploy/assets/main.css', 'public/css/kent-bar.css' ) .js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .extract(['vue', 'jquery', 'axios', 'tether', 'bootstrap']);
Comment explaining random.choice() on 1-item list
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
Update tests to test onChange and value.
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import { find } from 'ember-native-dom-helpers'; import MediumEditor from 'medium-editor'; const meClass = '.medium-editor-element'; moduleForComponent('medium-editor', 'Integration | Component | medium editor', { integration: true }); test('it renders', function(assert) { assert.expect(1); this.render(hbs`{{medium-editor}}`); assert.equal(find(meClass).innerHTML, ''); }); test('it sets initial value and updates it', function(assert) { assert.expect(2); this.set('tempValue', '<h1>Value</h1>'); this.render(hbs`{{medium-editor tempValue}}`); assert.equal(find('h1').innerHTML, 'Value'); this.set('tempValue', '<h2>New value</h2>'); assert.equal(find('h2').innerHTML, 'New value'); }); test('it should trigger onChange action when content changed', function(assert) { assert.expect(1); this.set('onChange', (actual) => { assert.equal(actual, '<p>typed value</p>'); }); this.render(hbs`{{medium-editor onChange=(action onChange)}}`); let editor = MediumEditor.getEditorFromElement(find(meClass)); editor.setContent('<p>typed value</p>'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import { find, fillIn } from 'ember-native-dom-helpers'; import { skip } from 'qunit'; moduleForComponent('medium-editor', 'Integration | Component | medium editor', { integration: true }); test('it renders', function(assert) { assert.expect(1); this.render(hbs`{{medium-editor}}`); assert.equal(find('.medium-editor-element').innerHTML, ''); }); test('it sets initial value and updates it', function(assert) { assert.expect(1); this.render(hbs`{{medium-editor "<h1>Value</h1>"}}`); assert.equal(find('h1').innerHTML, 'Value'); skip('value didUpdateAttrs test', function() { this.set('value', '<h2>New value</h2>'); assert.equal(this.$('h2').text(), 'New value'); }); }); skip('onChange action', function() { test('it should trigger onChange action when content changed', async function(assert) { assert.expect(1); this.set('onChange', (actual) => { assert.equal(actual, '<p>typed value</p>'); }); this.render(hbs`{{medium-editor onChange=(action onChange)}}`); await fillIn('.medium-editor-element', '<p>typed value</p>'); }); });
Mark invariant as an external module
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/index.js', output: { file: pkg.browser, format: 'umd', name: 'ReactStaticGoogleMap', }, plugins: [ resolve(), commonjs(), babel({ exclude: ['node_modules/**'], }), ], external: ['react', 'prop-types'], }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // the `targets` option which can specify `dest` and `format`) { input: 'src/index.js', output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' }, ], plugins: [ babel({ exclude: ['node_modules/**'], }), ], external: ['react', 'prop-types', 'react-promise', 'invariant'], }, ];
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/index.js', output: { file: pkg.browser, format: 'umd', name: 'ReactStaticGoogleMap', }, plugins: [ resolve(), commonjs(), babel({ exclude: ['node_modules/**'], }), ], external: ['react', 'prop-types'], }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // the `targets` option which can specify `dest` and `format`) { input: 'src/index.js', output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' }, ], plugins: [ babel({ exclude: ['node_modules/**'], }), ], external: ['react', 'prop-types', 'react-promise'], }, ];
Use config files to construct the tree of examples.
#------------------------------------------------------------------------------- # # Copyright (c) 2009, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Vibha Srinivasan # Date: 02/03/2009 # #------------------------------------------------------------------------------- """ Run the Chaco demo. """ from enthought.traits.ui.extras.demo import demo # Uncomment the config_filename portion to see a tree editor based on the # examples.cfg file. demo(use_files=True, config_filename='examples.cfg' )
#------------------------------------------------------------------------------- # # Copyright (c) 2009, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Vibha Srinivasan # Date: 02/03/2009 # #------------------------------------------------------------------------------- """ Run the Chaco demo. """ from enthought.traits.ui.extras.demo import demo # Uncomment the config_filename portion to see a tree editor based on the # examples.cfg file. demo(use_files=True, # config_filename='examples.cfg' )
Reset config to default values
<?php return [ /* |-------------------------------------------------------------------------- | Namespace Tablenames |-------------------------------------------------------------------------- | | If this option is set to true, all tablenames will be auto-generated from | namespace. For example a class with the namespace 'Acme\User' will have | the tablename 'acme_user'. | */ 'namespace_tablenames' => true, /* |-------------------------------------------------------------------------- | Morph Class Abbreviations |-------------------------------------------------------------------------- | | If this option is enabled, all morph classnames will be converted to a | short lower case abbreviation. For example 'Acme\User' will be shortened | to 'user'. | */ 'morphclass_abbreviations' => true, /* |-------------------------------------------------------------------------- | Models Namespace |-------------------------------------------------------------------------- | | If a models namespace is defined, only the entities and value objects in | the sub-namespace will be scanned by the schema commands. Also you only | have to name the sub-namespace in annotations (i. e. for the | relatedEntity parameter of the @Relation annotation). | */ 'models_namespace' => '', /* |-------------------------------------------------------------------------- | Presenters Namespace |-------------------------------------------------------------------------- | | If a presenters namespace is defined, only the classes in the sub-namespace | will be scanned by the schema commands. | */ 'presenters_namespace' => '', ];
<?php return [ /* |-------------------------------------------------------------------------- | Namespace Tablenames |-------------------------------------------------------------------------- | | If this option is set to true, all tablenames will be auto-generated from | namespace. For example a class with the namespace 'Acme\User' will have | the tablename 'acme_user'. | */ 'namespace_tablenames' => true, /* |-------------------------------------------------------------------------- | Morph Class Abbreviations |-------------------------------------------------------------------------- | | If this option is enabled, all morph classnames will be converted to a | short lower case abbreviation. For example 'Acme\User' will be shortened | to 'user'. | */ 'morphclass_abbreviations' => true, /* |-------------------------------------------------------------------------- | Models Namespace |-------------------------------------------------------------------------- | | If a models namespace is defined, only the entities and value objects in | the sub-namespace will be scanned by the schema commands. Also you only | have to name the sub-namespace in annotations (i. e. for the | relatedEntity parameter of the @Relation annotation). | */ 'models_namespace' => 'Examunity\Test', /* |-------------------------------------------------------------------------- | Presenters Namespace |-------------------------------------------------------------------------- | | If a presenters namespace is defined, only the classes in the sub-namespace | will be scanned by the schema commands. | */ 'presenters_namespace' => 'Examunity\Test', ];
Return by ID in client model
package com.emc.ecs.managementClient; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import com.emc.ecs.managementClient.model.DataServiceReplicationGroup; import com.emc.ecs.managementClient.model.DataServiceReplicationGroupList; import com.emc.ecs.serviceBroker.EcsManagementClientException; import com.emc.ecs.serviceBroker.EcsManagementResourceNotFoundException; public class ReplicationGroupAction { public static List<DataServiceReplicationGroup> list(Connection connection) throws EcsManagementClientException { UriBuilder uri = connection.getUriBuilder().segment("vdc", "data-service", "vpools"); Response response = connection.handleRemoteCall("get", uri, null); DataServiceReplicationGroupList rgList = response .readEntity(DataServiceReplicationGroupList.class); return rgList.getReplicationGroups(); } public static DataServiceReplicationGroup get(Connection connection, String id) throws EcsManagementClientException, EcsManagementResourceNotFoundException { List<DataServiceReplicationGroup> repGroups = list(connection); Optional<DataServiceReplicationGroup> optionalRg = repGroups.stream() .filter(rg -> rg.getId().equals(id)).findFirst(); try { return optionalRg.get(); } catch (NoSuchElementException e) { throw new EcsManagementResourceNotFoundException(e.getMessage()); } } }
package com.emc.ecs.managementClient; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import com.emc.ecs.managementClient.model.DataServiceReplicationGroup; import com.emc.ecs.managementClient.model.DataServiceReplicationGroupList; import com.emc.ecs.serviceBroker.EcsManagementClientException; import com.emc.ecs.serviceBroker.EcsManagementResourceNotFoundException; public class ReplicationGroupAction { public static List<DataServiceReplicationGroup> list(Connection connection) throws EcsManagementClientException { UriBuilder uri = connection.getUriBuilder().segment("vdc", "data-service", "vpools"); Response response = connection.handleRemoteCall("get", uri, null); DataServiceReplicationGroupList rgList = response .readEntity(DataServiceReplicationGroupList.class); return rgList.getReplicationGroups(); } public static DataServiceReplicationGroup get(Connection connection, String id) throws EcsManagementClientException, EcsManagementResourceNotFoundException { List<DataServiceReplicationGroup> repGroups = list(connection); Optional<DataServiceReplicationGroup> optionalRg = repGroups.stream() .filter(rg -> rg.getName().equals(id)).findFirst(); try { return optionalRg.get(); } catch (NoSuchElementException e) { throw new EcsManagementResourceNotFoundException(e.getMessage()); } } }
Remove Debugging Paths, Comment Out Unfinished Portions
from django.conf import settings from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Blog URLs #url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), # Handle all of the "static" pages url(r'^$', 'fragdev.views.home', name='home'), url(r'^about$', 'fragdev.views.about', name='about'), url(r'^contact$', 'fragdev.views.contact', name='contact'), url(r'^contacted$', 'fragdev.views.contacted', name='contacted'), url(r'^projects$', 'fragdev.views.projects', name='projects'), url(r'^resume$', 'fragdev.views.resume', name='resume'), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
from django.conf import settings from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Blog URLs url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), # Handle all of the "static" pages url(r'^$', 'fragdev.views.home', name='home'), url(r'^about$', 'fragdev.views.about', name='about'), url(r'^contact$', 'fragdev.views.contact', name='contact'), url(r'^contacted$', 'fragdev.views.contacted', name='contacted'), url(r'^projects$', 'fragdev.views.projects', name='projects'), url(r'^resume$', 'fragdev.views.resume', name='resume'), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # Static files: Should be handled by the web server! #url(r'^css/(?P<path>.*)$', 'django.views.static.serve', # {'document_root': '/data/documents/web/fragdev4000/css'}), #url(r'^fonts/(?P<path>.*)$', 'django.views.static.serve', # {'document_root': '/data/documents/web/fragdev4000/fonts'}), )
Add more granular date locators
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator def parse_break_str(txt): "parses '10 weeks' into tuple (10, week)." txt = txt.strip() if len(txt.split()) == 2: n, units = txt.split() else: n,units = 1, txt units = units.rstrip('s') # e.g. weeks => week n = int(n) return n, units # matplotlib's YearLocator uses different named # arguments than the others LOCATORS = { 'minute': MinuteLocator, 'hour': HourLocator, 'day': DayLocator, 'week': WeekdayLocator, 'month': MonthLocator, 'year': lambda interval: YearLocator(base=interval) } def date_breaks(width): """ "Regularly spaced dates." width: an interval specification. must be one of [minute, hour, day, week, month, year] usage: date_breaks(width = '1 year') date_breaks(width = '6 weeks') date_breaks('months') """ period, units = parse_break_str(width) Locator = LOCATORS.get(units) locator = Locator(interval=period) return locator
from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator def parse_break_str(txt): "parses '10 weeks' into tuple (10, week)." txt = txt.strip() if len(txt.split()) == 2: n, units = txt.split() else: n,units = 1, txt units = units.rstrip('s') # e.g. weeks => week n = int(n) return n, units # matplotlib's YearLocator uses different named # arguments than the others LOCATORS = { 'day': DayLocator, 'week': WeekdayLocator, 'month': MonthLocator, 'year': lambda interval: YearLocator(base=interval) } def date_breaks(width): """ "Regularly spaced dates." width: an interval specification. must be one of [day, week, month, year] usage: date_breaks(width = '1 year') date_breaks(width = '6 weeks') date_breaks('months') """ period, units = parse_break_str(width) Locator = LOCATORS.get(units) locator = Locator(interval=period) return locator
Fix for exception on client leave for DMs
package mzsJVM.Event; import mzsJVM.Entities.PlayerEntity; import mzsJVM.GameObject.PlayerGO; import mzsJVM.IScriptEventHandler; import mzsJVM.Repository.PlayerRepository; import org.nwnx.nwnx2.jvm.*; @SuppressWarnings("unused") public class Module_OnClientLeave implements IScriptEventHandler { @Override public void runScript(NWObject objSelf) { NWObject pc = NWScript.getExitingObject(); NWScript.exportSingleCharacter(pc); SaveCharacter(pc); NWScript.executeScript("fky_chat_clexit", objSelf); } private void SaveCharacter(NWObject pc) { if(NWScript.getIsDM(pc)) return; PlayerGO gameObject = new PlayerGO(pc); PlayerRepository repo = new PlayerRepository(); String uuid = gameObject.getUUID(); NWLocation location = NWScript.getLocation(pc); PlayerEntity entity = repo.getByUUID(uuid); if(entity == null) { return; } entity.setCharacterName(NWScript.getName(pc, false)); entity.setHitPoints(NWScript.getCurrentHitPoints(pc)); entity.setLocationAreaTag(NWScript.getTag(NWScript.getArea(pc))); entity.setLocationOrientation(NWScript.getFacing(pc)); entity.setLocationX(location.getX()); entity.setLocationY(location.getY()); entity.setLocationZ(location.getZ()); repo.save(entity); } }
package mzsJVM.Event; import mzsJVM.Entities.PlayerEntity; import mzsJVM.GameObject.PlayerGO; import mzsJVM.IScriptEventHandler; import mzsJVM.Repository.PlayerRepository; import org.nwnx.nwnx2.jvm.*; @SuppressWarnings("unused") public class Module_OnClientLeave implements IScriptEventHandler { @Override public void runScript(NWObject objSelf) { NWObject pc = NWScript.getExitingObject(); NWScript.exportSingleCharacter(pc); SaveCharacter(pc); NWScript.executeScript("fky_chat_clexit", objSelf); } private void SaveCharacter(NWObject pc) { if(NWScript.getIsDM(pc)) return; PlayerGO gameObject = new PlayerGO(pc); PlayerRepository repo = new PlayerRepository(); String uuid = gameObject.getUUID(); NWLocation location = NWScript.getLocation(pc); PlayerEntity entity = repo.getByUUID(uuid); entity.setCharacterName(NWScript.getName(pc, false)); entity.setHitPoints(NWScript.getCurrentHitPoints(pc)); entity.setLocationAreaTag(NWScript.getTag(NWScript.getArea(pc))); entity.setLocationOrientation(NWScript.getFacing(pc)); entity.setLocationX(location.getX()); entity.setLocationY(location.getY()); entity.setLocationZ(location.getZ()); repo.save(entity); } }
Create new Board object in reducer * store singleton object, so board object does not modify by #movePiece.
import Shogi from '../src/shogi'; const InitialState = { board: Shogi.Board, isHoldingPiece: undefined }; const ShogiReducer = (state = InitialState, action) => { switch (action.type) { case 'MOVE_PIECE': // if empty piece click when no holding piece, do nothing. if (action.piece.type === '*' && typeof state.isHoldingPiece === 'undefined' ) { return state; } // if same piece click, release piece. if (state.isHoldingPiece) { if (state.isHoldingPiece.equals(action.piece)) { return Object.assign({}, state, { isHoldingPiece: undefined }); } var movedBoard = state.board.movePiece(state.isHoldingPiece, action.piece); var newBoard = new state.board.constructor; newBoard.board = movedBoard; return Object.assign({}, { board: newBoard }, { isHoldingPiece: undefined }); } else { return Object.assign({}, state, { isHoldingPiece: action.piece }); } default: return state; } }; export default ShogiReducer;
import Shogi from '../src/shogi'; const InitialState = { board: Shogi.Board, isHoldingPiece: undefined }; const ShogiReducer = (state = InitialState, action) => { switch (action.type) { case 'MOVE_PIECE': // if empty piece click when no holding piece, do nothing. if (action.piece.type === '*' && typeof state.isHoldingPiece === 'undefined' ) { return state; } // if same piece click, release piece. if (state.isHoldingPiece) { if (state.isHoldingPiece.equals(action.piece)) { return Object.assign({}, state, { isHoldingPiece: undefined }); } state.board.movePiece(state.isHoldingPiece, action.piece); return Object.assign({}, { board: state.board }, { isHoldingPiece: undefined }); } else { return Object.assign({}, state, { isHoldingPiece: action.piece }); } default: return state; } }; export default ShogiReducer;
Allow libraries like moment.js to attach to window instead of global. Closes #5
(function(window) { if (!window.nwDispatcher) return; // Move `global.window` out of the way as it causes some third-party // libraries to expose themselves via `global` instead of `window`. var globalWindow = global.window; delete global.window; // Rename node's `require` to avoid conflicts with AMD's `require`. var requireNode = window.requireNode = window.require; delete window.require; window.addEventListener('load', function() { // Restore `global`. global.window = globalWindow; // Once the document is loaded, make node's `require` function // available again. This is required for certain node modules that // can't work with the alias, and for nw.js's GUI to function properly // (e.g. opening the dev tools from the window toolbar). var requireAMD = window.require; if (requireAMD) { window.require = function() { try { return requireAMD.apply(null, arguments); } catch (e) { return requireNode.apply(null, arguments); } }; } else { window.require = requireNode; } }); })(this);
(function(window) { if (!window.nwDispatcher) return; // Rename node's `require` to avoid conflicts with AMD's `require`. var requireNode = window.requireNode = window.require; delete window.require; window.addEventListener('load', function() { // Once the document is loaded, make node's `require` function // available again. This is required for certain node modules that // can't work with the alias, and for nw.js's GUI to function properly // (e.g. opening the dev tools from the window toolbar). var requireAMD = window.require; if (requireAMD) { window.require = function() { try { return requireAMD.apply(null, arguments); } catch (e) { return requireNode.apply(null, arguments); } }; } else { window.require = requireNode; } }); })(this);
Fix typo of Weasel type.
<?php /** * @author Jonathan Oddy <jonathan@moo.com> * @copyright Copyright (c) 2012, Moo Print Ltd. * @license ISC */ namespace Weasel\JsonMarshaller\Config\Serialization; use Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonProperty; use Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonTypeName; /** * Class GetterSerialization * @package Weasel\JsonMarshaller\Config\Serialization * @JsonTypeName("getter") */ class GetterSerialization extends PropertySerialization { /** * @var string * @JsonProperty(type="string") */ public $method; function __construct($method = null, $type = null, $include = null, $typeInfo = null) { $this->method = $method; $this->include = $include; $this->type = $type; $this->typeInfo = $typeInfo; } public function __toString() { return "[GetterSerialization method={$this->method} include={$this->include} type={$this->type} typeInfo={$this->typeInfo}]"; } }
<?php /** * @author Jonathan Oddy <jonathan@moo.com> * @copyright Copyright (c) 2012, Moo Print Ltd. * @license ISC */ namespace Weasel\JsonMarshaller\Config\Serialization; use Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonProperty; use Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonTypeName; /** * Class GetterSerialization * @package Weasel\JsonMarshaller\Config\Serialization * @JsonTypeName("getter") */ class GetterSerialization extends PropertySerialization { /** * @var string * @JsonProperty(type="method") */ public $method; function __construct($method = null, $type = null, $include = null, $typeInfo = null) { $this->method = $method; $this->include = $include; $this->type = $type; $this->typeInfo = $typeInfo; } public function __toString() { return "[GetterSerialization method={$this->method} include={$this->include} type={$this->type} typeInfo={$this->typeInfo}]"; } }
[JENKINS-42584] Fix upstream job priority retrieval - NPE fix
package jenkins.advancedqueue; import hudson.Plugin; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); // Can be null if job didn't run yet if (itemInfo != null) { priorityCallback.setPrioritySelection(itemInfo.getPriority()); } else { priorityCallback.setPrioritySelection(PrioritySorterConfiguration.get().getStrategy().getDefaultPriority()); } return priorityCallback; } static boolean isPlaceholderTaskUsed() { Plugin plugin = Jenkins.getInstance().getPlugin("workflow-durable-task-step"); return plugin != null && plugin.getWrapper().isActive(); } }
package jenkins.advancedqueue; import hudson.Plugin; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { Plugin plugin = Jenkins.getInstance().getPlugin("workflow-durable-task-step"); return plugin != null && plugin.getWrapper().isActive(); } }
Use false instead of null to avoid using a layout
var Handlebars = require('handlebars'); function Exbars(options) { this.defaultLayout = options.defaultLayout ? options.defaultLayout : null; this.compilerOptions = options.compilerOptions ? options.compilerOptions : {}; this.handlebars = Handlebars; this.compiledTemplates = {}; this.registerHelper = function(name, helper) { return this.handlebars.registerHelper(name, helper); }; this.registerPartial = function(name, content) { return this.handlebars.registerPartial(name, content); }; this.compile = function(template, content) { this.compiledTemplates[template] = this.handlebars.compile(content, this.compilerOptions); }; this.render = function(filePath, options, callback) { var template = this.compiledTemplates[filePath]; var layout = options.layout === false ? null : options.layout || this.defaultLayout; if(layout) { var layoutTemplate = this.compiledTemplates[process.cwd() + '/views/layouts/' + layout + '.hbs']; options.body = template(options); return callback(null, layoutTemplate(options)); } return callback(null, template(options)); }; this.engine = function() { return this.render.bind(this); }; } module.exports = Exbars;
var Handlebars = require('handlebars'); function Exbars(options) { this.defaultLayout = options.defaultLayout ? options.defaultLayout : null; this.handlebars = Handlebars; this.compilerOptions = options.compilerOptions ? options.compilerOptions : {}; this.compiledTemplates = {}; this.registerHelper = function(name, helper) { return this.handlebars.registerHelper(name, helper); }; this.registerPartial = function(name, content) { return this.handlebars.registerPartial(name, content); }; this.compile = function(template, content) { this.compiledTemplates[template] = this.handlebars.compile(content, this.compilerOptions); }; this.render = function(filePath, options, callback) { var template = this.compiledTemplates[filePath]; var layout = options.layout === null ? null : options.layout || this.defaultLayout; if(layout) { var layoutTemplate = this.compiledTemplates[process.cwd() + '/views/layouts/' + layout + '.hbs']; options.body = template(options); return callback(null, layoutTemplate(options)); } return callback(null, template(options)); }; this.engine = function() { return this.render.bind(this); }; } module.exports = Exbars;
Add sphinx & theme to requirements
#!/usr/bin/env python3 from distutils.core import setup setup( name='LoadStone', version='0.1', description='Interface for FFXIV Lodestone', author='Sami Elahmadie', author_email='s.elahmadie@gmail.com', url='https://github.com/Demotivated/loadstone/', packages=['api'], install_requires=[ 'flask==0.10.1', 'flask_sqlalchemy==2.0', 'lxml==3.4.4', 'psycopg2==2.6.1', 'pytest==2.8.2', 'pytest-flask==0.10.0', 'requests==2.8.1', 'sphinx==1.3.1', 'sphinx-rtd-theme==0.1.9' ] )
#!/usr/bin/env python3 from distutils.core import setup setup( name='LoadStone', version='0.1', description='Interface for FFXIV Lodestone', author='Sami Elahmadie', author_email='s.elahmadie@gmail.com', url='https://github.com/Demotivated/loadstone/', packages=['api'], install_requires=[ 'flask==0.10.1', 'flask_sqlalchemy==2.0', 'lxml==3.4.4', 'psycopg2==2.6.1', 'pytest==2.8.2', 'pytest-flask==0.10.0', 'requests==2.8.1', ] )
Add request encoding to WMTS source
/******************************************************************************* * Copyright 2014, 2019 gwt-ol * * 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 ol.source; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; /** * WMTS options. * * @author Tino Desjardins * */ @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") public class WmtsOptions extends TileImageOptions { /** * Sets the layername. * * @param layer layername */ @JsProperty public native void setLayer(String layer); /** * @param requestEncoding Request encoding. */ @JsProperty public native void setRequestEncoding(String requestEncoding); @JsProperty public native void setStyle(String style); @JsProperty public native void setFormat(String format); @JsProperty public native void setVersion(String version); @JsProperty public native void setMatrixSet(String matrixSet); }
/******************************************************************************* * Copyright 2014, 2017 gwt-ol3 * * 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 ol.source; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; /** * WMTS options. * * @author Tino Desjardins * */ @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") public class WmtsOptions extends TileImageOptions { /** * Sets the layername. * * @param layer layername */ @JsProperty public native void setLayer(String layer); @JsProperty public native void setStyle(String style); @JsProperty public native void setFormat(String format); @JsProperty public native void setVersion(String version); @JsProperty public native void setMatrixSet(String matrixSet); }
Use Silex Application as TwigServiceProvider is dependent on a lot of services defined there
<?php namespace Brick\Tests\Provider; use Silex\Application; use Silex\Provider\TwigServiceProvider; use Brick\Provider\ExceptionServiceProvider; class ExceptionServiceProviderTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->app = new Application(); $this->app->register(new TwigServiceProvider); $this->app->register(new ExceptionServiceProvider); } public function testOverrideExceptionHandler() { $this->assertInstanceOf('Symfony\Component\HttpKernel\EventListener\ExceptionListener', $this->app['exception_handler']); } public function testExceptionController() { $provider = new TwigServiceProvider; $provider->register($this->app); $this->assertInstanceOf('Brick\Controller\ExceptionController', $this->app['exception_controller']); } }
<?php namespace Brick\Tests\Provider; use Silex\Provider\TwigServiceProvider; use Brick\Provider\ExceptionServiceProvider; use Pimple\Container; class ExceptionServiceProviderTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->pimple = new Container([ 'exception_handler' => function () { return 'exception_handler'; }, 'logger' => function () {}, ]); $this->pimple->register(new TwigServiceProvider); $this->pimple->register(new ExceptionServiceProvider); } public function testOverrideExceptionHandler() { $this->assertInstanceOf('Symfony\Component\HttpKernel\EventListener\ExceptionListener', $this->pimple['exception_handler']); } public function testExceptionController() { $provider = new TwigServiceProvider; $provider->register($this->pimple); $this->assertInstanceOf('Brick\Controller\ExceptionController', $this->pimple['exception_controller']); } }
Fix broken tests for count column
package com.facebook.presto.operator.aggregation; import com.facebook.presto.block.Block; import com.facebook.presto.block.BlockBuilder; import static com.facebook.presto.operator.aggregation.CountColumnAggregation.COUNT_COLUMN; import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG; public class TestCountColumnAggregation extends AbstractTestAggregationFunction { @Override public Block getSequenceBlock(int start, int length) { BlockBuilder blockBuilder = new BlockBuilder(SINGLE_LONG); for (int i = start; i < start + length; i++) { blockBuilder.append(i); } return blockBuilder.build(); } @Override public AggregationFunction getFunction() { return COUNT_COLUMN; } @Override public Number getExpectedValue(int start, int length) { return (long) length; } }
package com.facebook.presto.operator.aggregation; import com.facebook.presto.block.Block; import com.facebook.presto.block.BlockBuilder; import static com.facebook.presto.operator.aggregation.CountColumnAggregation.COUNT_COLUMN; import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG; public class TestCountColumnAggregation extends AbstractTestAggregationFunction { @Override public Block getSequenceBlock(int start, int length) { BlockBuilder blockBuilder = new BlockBuilder(SINGLE_LONG); for (int i = start; i < start + length; i++) { blockBuilder.append(i); } return blockBuilder.build(); } @Override public AggregationFunction getFunction() { return COUNT_COLUMN; } @Override public Number getExpectedValue(int start, int length) { if (length == 0) { return null; } return (long) length; } }
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-font-family/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/font-family/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-font-family/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/font-family/index.html', html)
Allow app to be imported Flask httpdomain needs to import the Flask app. It turns out the the way to get the path to the configuration file assumed the app was always being run/imported from the base of the ltd-keeper repo, which isn't always true, especially for Sphinx doc builds. This correctly derives a path from the absolute path of the Python module itself. For DM-5100.
import os from flask import Flask, jsonify, g from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(config_name): """Create an application instance. This is called by a runner script, such as /run.py. """ from .auth import password_auth app = Flask(__name__) # apply configuration _this_dir = os.path.dirname(os.path.abspath(__file__)) cfg = os.path.join(_this_dir, '../config', config_name + '.py') app.config.from_pyfile(cfg) # initialize extensions db.init_app(app) # register blueprints from .api_v1 import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/v1') # authentication token route @app.route('/token') @password_auth.login_required def get_auth_token(): return jsonify({'token': g.user.generate_auth_token()}) return app
import os from flask import Flask, jsonify, g from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(config_name): """Create an application instance. This is called by a runner script, such as /run.py. """ from .auth import password_auth app = Flask(__name__) # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # initialize extensions db.init_app(app) # register blueprints from .api_v1 import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/v1') # authentication token route @app.route('/token') @password_auth.login_required def get_auth_token(): return jsonify({'token': g.user.generate_auth_token()}) return app
Set case-id on job data
<?php /** * @package plugins.businessProcessNotification * @subpackage model */ class BusinessProcessSignalNotificationTemplate extends BusinessProcessNotificationTemplate { const CUSTOM_DATA_MESSAGE = 'message'; const CUSTOM_DATA_EVENT_ID = 'eventId'; public function __construct() { $this->setType(BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_SIGNAL)); parent::__construct(); } /* (non-PHPdoc) * @see BusinessProcessNotificationTemplate::getJobData() */ public function getJobData(kScope $scope = null) { $jobData = parent::getJobData($scope); if($jobData->getObject()) { $caseId = $this->getCaseId($jobData->getObject()); $jobData->setCaseId($caseId); } return $jobData; } public function getMessage() {return $this->getFromCustomData(self::CUSTOM_DATA_MESSAGE);} public function getEventId() {return $this->getFromCustomData(self::CUSTOM_DATA_EVENT_ID);} public function setMessage($v) {return $this->putInCustomData(self::CUSTOM_DATA_MESSAGE, $v);} public function setEventId($v) {return $this->putInCustomData(self::CUSTOM_DATA_EVENT_ID, $v);} }
<?php /** * @package plugins.businessProcessNotification * @subpackage model */ class BusinessProcessSignalNotificationTemplate extends BusinessProcessNotificationTemplate { const CUSTOM_DATA_MESSAGE = 'message'; const CUSTOM_DATA_EVENT_ID = 'eventId'; public function __construct() { $this->setType(BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_SIGNAL)); parent::__construct(); } public function getMessage() {return $this->getFromCustomData(self::CUSTOM_DATA_MESSAGE);} public function getEventId() {return $this->getFromCustomData(self::CUSTOM_DATA_EVENT_ID);} public function setMessage($v) {return $this->putInCustomData(self::CUSTOM_DATA_MESSAGE, $v);} public function setEventId($v) {return $this->putInCustomData(self::CUSTOM_DATA_EVENT_ID, $v);} }
Allow to set default value in template
from django.forms.models import model_to_dict from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('simpleseo/metadata.html', takes_context=True) def get_seo(context, **kwargs): path = context['request'].path lang_code = get_language()[:2] try: metadata = model_to_dict(SeoMetadata.objects.get(path=path, lang_code=lang_code)) except SeoMetadata.DoesNotExist: metadata = {} result = {} for item in ['title', 'description']: result[item] = (metadata.get(item) or kwargs.get(item) or getattr(settings, 'FALLBACK_{0}'.format(item.upper()))) return result @register.simple_tag(takes_context=True) def get_seo_title(context, default=''): return get_seo(context, title=default).get('title') @register.simple_tag(takes_context=True) def get_seo_description(context, default=''): return get_seo(context, description=default).get('description')
from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('simpleseo/metadata.html', takes_context=True) def get_seo(context): lang_code = get_language()[:2] path = context['request'].path try: metadata = SeoMetadata.objects.get(path=path, lang_code=lang_code) except SeoMetadata.DoesNotExist: metadata = None if metadata is None: return {'title': settings.FALLBACK_TITLE, 'description': settings.FALLBACK_DESCRIPTION} return {'title': metadata.title, 'description': metadata.description} @register.simple_tag(takes_context=True) def get_seo_title(context): return get_seo(context)['title'] @register.simple_tag(takes_context=True) def get_seo_description(context): return get_seo(context)['description']
Set timeout default value to 30sec.
var os = require('os'); var path = require('path'); var paths = require('./paths'); // Guess proxy defined in the env /*jshint camelcase: false*/ var proxy = process.env.HTTP_PROXY || process.env.http_proxy || null; var httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null; /*jshint camelcase: true*/ var defaults = { 'cwd': process.cwd(), 'directory': 'bower_components', 'registry': 'https://bower.herokuapp.com', 'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git', 'tmp': os.tmpdir ? os.tmpdir() : os.tmpDir(), 'proxy': proxy, 'https-proxy': httpsProxy, 'timeout': 30000, 'ca': { search: [] }, 'strict-ssl': true, 'user-agent': 'node/' + process.version + ' ' + process.platform + ' ' + process.arch, 'color': true, 'interactive': false, 'storage': { packages: path.join(paths.cache, 'packages'), links: path.join(paths.data, 'links'), completion: path.join(paths.data, 'completion'), registry: path.join(paths.cache, 'registry'), git: path.join(paths.data, 'git') } }; module.exports = defaults;
var os = require('os'); var path = require('path'); var paths = require('./paths'); // Guess proxy defined in the env /*jshint camelcase: false*/ var proxy = process.env.HTTP_PROXY || process.env.http_proxy || null; var httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null; /*jshint camelcase: true*/ var defaults = { 'cwd': process.cwd(), 'directory': 'bower_components', 'registry': 'https://bower.herokuapp.com', 'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git', 'tmp': os.tmpdir ? os.tmpdir() : os.tmpDir(), 'proxy': proxy, 'https-proxy': httpsProxy, 'timeout': 60000, 'ca': { search: [] }, 'strict-ssl': true, 'user-agent': 'node/' + process.version + ' ' + process.platform + ' ' + process.arch, 'color': true, 'interactive': false, 'storage': { packages: path.join(paths.cache, 'packages'), links: path.join(paths.data, 'links'), completion: path.join(paths.data, 'completion'), registry: path.join(paths.cache, 'registry'), git: path.join(paths.data, 'git') } }; module.exports = defaults;
Add CONN_MAX_AGE setting because it makes a huge difference on busy sites
from project.settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'skeleton', 'USER': 'skeleton', 'PASSWORD': 'skeleton', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 60 } } MEDIA_ROOT = abspath("..", "skeleton-media") STATIC_ROOT = abspath("..", "skeleton-static") CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads") CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'KEY_PREFIX': 'skeleton_live', } } COMPRESS_ENABLED = True # Uncomment to use atlas. Remember to change the database engine to GIS aware. #INSTALLED_APPS += ("atlas", "django.contrib.gis") SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE' SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient' RAVEN_CONFIG = { 'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE', } ALLOWED_HOSTS = [ "*" ]
from project.settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'skeleton', 'USER': 'skeleton', 'PASSWORD': 'skeleton', 'HOST': 'localhost', 'PORT': '5432', } } MEDIA_ROOT = abspath("..", "skeleton-media") STATIC_ROOT = abspath("..", "skeleton-static") CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, "uploads") CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'KEY_PREFIX': 'skeleton_live', } } COMPRESS_ENABLED = True # Uncomment to use atlas. Remember to change the database engine to GIS aware. #INSTALLED_APPS += ("atlas", "django.contrib.gis") SENTRY_DSN = 'ENTER_YOUR_SENTRY_DSN_HERE' SENTRY_CLIENT = 'raven.contrib.django.celery.CeleryClient' RAVEN_CONFIG = { 'dsn': 'ENTER_YOUR_SENTRY_DSN_HERE', } ALLOWED_HOSTS = [ "*" ]
Fix missing space seperator betwen auto register passwords
package com.github.games647.lambdaattack.bot.listener; import com.github.games647.lambdaattack.LambdaAttack; import com.github.games647.lambdaattack.bot.Bot; import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import com.github.steveice10.packetlib.event.session.SessionAdapter; import java.util.logging.Level; public abstract class SessionListener extends SessionAdapter { protected final Bot owner; public SessionListener(Bot owner) { this.owner = owner; } @Override public void disconnected(DisconnectedEvent disconnectedEvent) { String reason = disconnectedEvent.getReason(); owner.getLogger().log(Level.INFO, "Disconnected: {0}", reason); } public void onJoin() { if (LambdaAttack.getInstance().isAutoRegister()) { String password = LambdaAttack.PROJECT_NAME; owner.sendMessage(Bot.COMMAND_IDENTIFIER + "register " + password + ' ' + password); owner.sendMessage(Bot.COMMAND_IDENTIFIER + "login " + password); } } }
package com.github.games647.lambdaattack.bot.listener; import com.github.games647.lambdaattack.LambdaAttack; import com.github.games647.lambdaattack.bot.Bot; import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import com.github.steveice10.packetlib.event.session.SessionAdapter; import java.util.logging.Level; public abstract class SessionListener extends SessionAdapter { protected final Bot owner; public SessionListener(Bot owner) { this.owner = owner; } @Override public void disconnected(DisconnectedEvent disconnectedEvent) { String reason = disconnectedEvent.getReason(); owner.getLogger().log(Level.INFO, "Disconnected: {0}", reason); } public void onJoin() { if (LambdaAttack.getInstance().isAutoRegister()) { String password = LambdaAttack.PROJECT_NAME; owner.sendMessage(Bot.COMMAND_IDENTIFIER + "register " + password + password); owner.sendMessage(Bot.COMMAND_IDENTIFIER + "login " + password); } } }
Create 'Add Task' link on project/view page Reviewed by: epriestley See: https://github.com/facebook/phabricator/pull/368
<?php final class ManiphestPeopleMenuEventListener extends PhutilEventListener { public function register() { $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS); } public function handleEvent(PhutilEvent $event) { switch ($event->getType()) { case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS: $this->handleActionsEvent($event); break; } } private function handleActionsEvent($event) { $actions = $event->getValue('actions'); $action = id(new PhabricatorActionView()) ->setIcon('maniphest-dark') ->setIconSheet(PHUIIconView::SPRITE_APPS) ->setName(pht('View Tasks')); $object = $event->getValue('object'); if ($object instanceof PhabricatorUser) { $href = '/maniphest/view/action/?users='.$object->getPHID(); $actions[] = $action->setHref($href); } else if ($object instanceof PhabricatorProject) { $href = '/maniphest/view/all/?projects='.$object->getPHID(); $actions[] = $action->setHref($href); $actions[] = id(new PhabricatorActionView()) ->setName(pht("Add Task")) ->setIcon('create') ->setHref('/maniphest/task/create/?projects=' . $object->getPHID()); } $event->setValue('actions', $actions); } }
<?php final class ManiphestPeopleMenuEventListener extends PhutilEventListener { public function register() { $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS); } public function handleEvent(PhutilEvent $event) { switch ($event->getType()) { case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS: $this->handleActionsEvent($event); break; } } private function handleActionsEvent($event) { $actions = $event->getValue('actions'); $action = id(new PhabricatorActionView()) ->setIcon('maniphest-dark') ->setIconSheet(PHUIIconView::SPRITE_APPS) ->setName(pht('View Tasks')); $object = $event->getValue('object'); if ($object instanceof PhabricatorUser) { $href = '/maniphest/view/action/?users='.$object->getPHID(); $actions[] = $action->setHref($href); } else if ($object instanceof PhabricatorProject) { $href = '/maniphest/view/all/?projects='.$object->getPHID(); $actions[] = $action->setHref($href); } $event->setValue('actions', $actions); } }
Fix bug on HUAWEI phone.
package cn.mutils.app.ui; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class GridViewer extends GridView { /** 设置是否高度全部显示 */ protected boolean mShowAll = false; public GridViewer(Context context, AttributeSet attrs) { super(context, attrs); } public GridViewer(Context context) { super(context); } public GridViewer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public boolean isShowAll() { return mShowAll; } public void setShowAll(boolean showAll) { this.mShowAll = showAll; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mShowAll) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
package cn.mutils.app.ui; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class GridViewer extends GridView { /** 设置是否高度全部显示 */ protected boolean mShowAll = false; public GridViewer(Context context, AttributeSet attrs) { super(context, attrs); } public GridViewer(Context context) { super(context); } public GridViewer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public boolean isShowAll() { return mShowAll; } public void setShowAll(boolean showAll) { this.mShowAll = showAll; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mShowAll) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, MeasureSpec.AT_MOST); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
Update serial port and baud rate
import sys import serial import threading from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyS0" else: port = args[0] player = None with serial.Serial(port, 19200) as serial_port: try: player = blueplayer.BluePlayer(serial_port) player_thread = threading.Thread(target=player.start) serial_thread = threading.Thread(target=player.run) player_thread.start() serial_thread.start() player_thread.join() serial_thread.join() except KeyboardInterrupt as ex: print("\nBluePlayer cancelled by user") except Exception as ex: print("How embarrassing. The following error occurred {}".format(ex)) finally: if player: player.end() player.stop() if __name__ == "__main__": main()
import sys import serial import threading from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port: try: player = blueplayer.BluePlayer(serial_port) player_thread = threading.Thread(target=player.start) serial_thread = threading.Thread(target=player.run) player_thread.start() serial_thread.start() player_thread.join() serial_thread.join() except KeyboardInterrupt as ex: print("\nBluePlayer cancelled by user") except Exception as ex: print("How embarrassing. The following error occurred {}".format(ex)) finally: if player: player.end() player.stop() if __name__ == "__main__": main()
Use datastax.com instead of google.com for address-resolution-test.
var assert = require('assert'); var util = require('util'); var events = require('events'); var async = require('async'); var dns = require('dns'); var addressResolution = require('../../lib/policies/address-resolution'); var EC2MultiRegionTranslator = addressResolution.EC2MultiRegionTranslator; describe('EC2MultiRegionTranslator', function () { this.timeout(5000); describe('#translate()', function () { it('should return the same address when it could not be resolved', function (done) { var t = new EC2MultiRegionTranslator(); t.translate('127.100.100.1', 9042, function (endPoint) { assert.strictEqual(endPoint, '127.100.100.1:9042'); done(); }); }); it('should do a reverse and a forward dns lookup', function (done) { var t = new EC2MultiRegionTranslator(); dns.lookup('datastax.com', function (err, address) { assert.ifError(err); assert.ok(address); t.translate(address, 9001, function (endPoint) { assert.strictEqual(endPoint, address + ':9001'); done(); }); }); }); }); });
var assert = require('assert'); var util = require('util'); var events = require('events'); var async = require('async'); var dns = require('dns'); var addressResolution = require('../../lib/policies/address-resolution'); var EC2MultiRegionTranslator = addressResolution.EC2MultiRegionTranslator; describe('EC2MultiRegionTranslator', function () { this.timeout(5000); describe('#translate()', function () { it('should return the same address when it could not be resolved', function (done) { var t = new EC2MultiRegionTranslator(); t.translate('127.100.100.1', 9042, function (endPoint) { assert.strictEqual(endPoint, '127.100.100.1:9042'); done(); }); }); it('should do a reverse and a forward dns lookup', function (done) { var t = new EC2MultiRegionTranslator(); dns.lookup('google.com', function (err, address) { assert.ifError(err); assert.ok(address); t.translate(address, 9001, function (endPoint) { assert.strictEqual(endPoint, address + ':9001'); done(); }); }); }); }); });
Add Markov Chain representation class
from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text to the markov chain """ word_list = text.split(separator) for i in range(0, len(word_list)-1): self._states_map.setdefault(word_list[i], []).append(word_list[i+1]) return self def add_text_collection(self, text_col, separator=" "): """ Adds a collection of text strings to the markov chain """ for line in text_col: if line not in ["", "\n", None]: self.add_text(line, separator) def get_word(self, key): """ Returns a word from Markov Chain associated with the key """ values = self._states_map.get(key) return choice(values) if values is not None else None
from random import choice class MarkovChain(object): """ An interface for signle-word states Markov Chains """ def __init__(self, text=None): self._states_map = {} if text is not None: self.add_text(text) def add_text(self, text, separator=" "): """ Adds text to the markov chain """ word_list = text.split(separator) for i in range(0, len(word_list)-1): self._states_map.setdefault(word_list[i], []).append(word_list[i+1]) return self def get_word(self, key): """ Returns a word from Markov Chain associated with the key """ values = self._states_map.get(key) return choice(values) if values is not None else None
Make dependency versions more explicit
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup setup( name = "open511", version = "0.1", url='', license = "", packages = [ 'open511', ], install_requires = [ 'lxml>=2.3', 'WebOb>=1.2,<2', 'python-dateutil>=1.5,<2.0', 'requests>=1.2,<2', 'pytz>=2013b', 'django-appconf==0.5', 'cssselect==0.8', ], entry_points = { 'console_scripts': [ 'mtl_kml_to_open511 = open511.scripts.mtl_kml_to_open511:main', 'scrape_mtq_to_open511 = open511.scripts.scrape_mtq_to_open511:main', ] }, )
from distribute_setup import use_setuptools use_setuptools() from setuptools import setup setup( name = "open511", version = "0.1", url='', license = "", packages = [ 'open511', ], install_requires = [ 'lxml', 'webob', 'python-dateutil>=1.5,<2.0', 'requests', 'pytz', 'django-appconf==0.5', ], entry_points = { 'console_scripts': [ 'mtl_kml_to_open511 = open511.scripts.mtl_kml_to_open511:main', 'scrape_mtq_to_open511 = open511.scripts.scrape_mtq_to_open511:main', ] }, )
Use a 'valid' doc number
import re from unittest import TestCase from mock import patch from django.test.client import Client class ViewsSideBarViewTest(TestCase): """Integration tests for the sidebar""" @patch('regulations.views.sidebar.api_reader') def test_get(self, api_reader): api_reader.Client.return_value.layer.return_value = { '1111-1': [ {'reference': ['1992-1', '1111-1']}, {'reference': ['1992-2', '1111-1']}, ], '1111-1-a': [{'reference': ['1992-1', '1111-1-a']}] } response = Client().get('/partial/sidebar/1111-1/verver') self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content))) self.assertTrue('1111.1(a)' in response.content) self.assertTrue('1992-2' in response.content) self.assertTrue('1111-1' in response.content) self.assertTrue('1992-1' in response.content) self.assertTrue('1111-1-a' in response.content)
import re from unittest import TestCase from mock import patch from django.test.client import Client class ViewsSideBarViewTest(TestCase): """Integration tests for the sidebar""" @patch('regulations.views.sidebar.api_reader') def test_get(self, api_reader): api_reader.Client.return_value.layer.return_value = { '1111-1': [ {'reference': ['doc1', '1111-1']}, {'reference': ['doc2', '1111-1']}, ], '1111-1-a': [{'reference': ['doc1', '1111-1-a']}] } response = Client().get('/partial/sidebar/1111-1/verver') self.assertTrue(bool(re.search(r'\b1111\.1\b', response.content))) self.assertTrue('1111.1(a)' in response.content)
Make sure we cleanup even if fails in example
""" This example: 1. Connects to the current model 2. Deploy a local charm with a oci-image resource and waits until it reports itself active 3. Destroys the unit and application """ from juju import jasyncio from juju.model import Model from pathlib import Path async def main(): model = Model() print('Connecting to model') # connect to current model with current user, per Juju CLI await model.connect() application = None try: print('Deploying local-charm') base_dir = Path(__file__).absolute().parent.parent charm_path = '{}/tests/integration/file-resource-charm'.format(base_dir) resources = {"file-res": "test.file"} application = await model.deploy( charm_path, resources=resources, ) print('Waiting for active') await model.wait_for_idle() print('Removing Charm') await application.remove() except Exception as e: print(e) if application: await application.remove() await model.disconnect() finally: print('Disconnecting from model') await model.disconnect() if __name__ == '__main__': jasyncio.run(main())
""" This example: 1. Connects to the current model 2. Deploy a local charm with a oci-image resource and waits until it reports itself active 3. Destroys the unit and application """ from juju import jasyncio from juju.model import Model from pathlib import Path async def main(): model = Model() print('Connecting to model') # connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying local-charm') base_dir = Path(__file__).absolute().parent.parent charm_path = '{}/tests/integration/file-resource-charm'.format(base_dir) resources = {"file-res": "test.file"} application = await model.deploy( charm_path, resources=resources, ) print('Waiting for active') await model.wait_for_idle() print('Removing Charm') await application.remove() finally: print('Disconnecting from model') await model.disconnect() if __name__ == '__main__': jasyncio.run(main())
Update for PYTHON 985: MongoClient properties now block until connected.
# Copyright 2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from mockupdb import MockupDB, wait_until from pymongo import MongoClient from tests import unittest class TestInitialIsMaster(unittest.TestCase): def test_initial_ismaster(self): server = MockupDB() server.run() self.addCleanup(server.stop) start = time.time() client = MongoClient(server.uri) self.addCleanup(client.close) # A single ismaster is enough for the client to be connected. self.assertFalse(client.nodes) server.receives('ismaster').ok(ismaster=True) wait_until(lambda: client.nodes, 'update nodes', timeout=1) # At least 10 seconds before next heartbeat. server.receives('ismaster').ok(ismaster=True) self.assertGreaterEqual(time.time() - start, 10) if __name__ == '__main__': unittest.main()
# Copyright 2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from mockupdb import MockupDB, wait_until from pymongo import MongoClient from tests import unittest class TestInitialIsMaster(unittest.TestCase): def test_initial_ismaster(self): server = MockupDB() server.run() self.addCleanup(server.stop) start = time.time() client = MongoClient(server.uri) self.addCleanup(client.close) # A single ismaster is enough for the client to be connected. self.assertIsNone(client.address) server.receives('ismaster').ok() wait_until(lambda: client.address is not None, 'update address', timeout=1) # At least 10 seconds before next heartbeat. server.receives('ismaster').ok() self.assertGreaterEqual(time.time() - start, 10) if __name__ == '__main__': unittest.main()
Add fn to read package.json
'use strict'; var path = require('path'), fs = require('fs'), Promise = require('rsvp').Promise; var readPackageJson = function (dir) { return new Promise(function(resolve, reject) { fs.readFile(path.join(dir, 'package.json'), 'utf8', function (err, data) { if (err) { reject(err); } else { try { resolve(JSON.parse(data)); } catch (err) { reject(err); } } }); }); }; var JspmNuget = function (options, ui) { }; // static configuration function JspmNuget.configure = function(config, ui) { }; // regular expression to verify package names JspmNuget.packageFormat = /^[^\/]+\/[^\/]+/; JspmNuget.prototype = { // Given a package name, return a list of versions of the looked up package name // return values // { versions: versions: { // '1.2.3': { hash: 'asdf' }, // 'branch-name': { hash: '8j3mjw8fwef7a', stable: false, meta: { custom: 'lookup data' } } // } } // OR // { notfound: true } lookup: function (packageName) { }, // Given a package name, download version into the specified directory // return value: Promise containing package.json content download: function (packageName, version, hash, meta, dir) { } }; module.exports = JspmNuget;
'use strict'; var JspmNuget = function (options, ui) { }; // static configuration function JspmNuget.configure = function(config, ui) { }; // regular expression to verify package names JspmNuget.packageFormat = /^[^\/]+\/[^\/]+/; JspmNuget.prototype = { // Given a package name, return a list of versions of the looked up package name // return values // { versions: versions: { // '1.2.3': { hash: 'asdf' }, // 'branch-name': { hash: '8j3mjw8fwef7a', stable: false, meta: { custom: 'lookup data' } } // } } // OR // { notfound: true } lookup: function (packageName) { }, // Given a package name, download version into the specified directory // return value: Promise containing package.json content download: function (packageName, version, hash, meta, dir) { } }; module.exports = JspmNuget;
style(badge): Change badge style on sidebar notification count
import classNames from "classnames"; import React from "react"; import { Link } from "react-router"; import NotificationStore from "../stores/NotificationStore"; const PrimarySidebarLink = ({ to, children, hasChildren, icon, isChildActive, isExpanded, onClick }) => { const notificationCount = NotificationStore.getNotificationCount(to); let sidebarText = ( <span className="sidebar-menu-item-label"> {children} </span> ); if (notificationCount > 0) { sidebarText = ( <span className="sidebar-menu-item-label badge-container"> <span className="sidebar-menu-item-label-text badge-container-text"> {children} </span> <span className="badge">{notificationCount}</span> </span> ); } if (hasChildren) { const classes = classNames( { clickable: !isChildActive, "is-expanded": isExpanded }, "expandable" ); return ( <a className={classes} onClick={onClick}> {icon}{sidebarText} </a> ); } return <Link to={to}>{icon}{sidebarText}</Link>; }; module.exports = PrimarySidebarLink;
import classNames from "classnames"; import React from "react"; import { Link } from "react-router"; import NotificationStore from "../stores/NotificationStore"; const PrimarySidebarLink = ({ to, children, hasChildren, icon, isChildActive, isExpanded, onClick }) => { const notificationCount = NotificationStore.getNotificationCount(to); let sidebarText = ( <span className="sidebar-menu-item-label"> {children} </span> ); if (notificationCount > 0) { sidebarText = ( <span className="sidebar-menu-item-label badge-container"> <span className="sidebar-menu-item-label-text badge-container-text"> {children} </span> <span className="badge badge-rounded">{notificationCount}</span> </span> ); } if (hasChildren) { const classes = classNames( { clickable: !isChildActive, "is-expanded": isExpanded }, "expandable" ); return ( <a className={classes} onClick={onClick}> {icon}{sidebarText} </a> ); } return <Link to={to}>{icon}{sidebarText}</Link>; }; module.exports = PrimarySidebarLink;
Fix newNode assignments and find logic.
package kace type node struct { val rune end bool links []*node } func newNode(val rune, isEnd bool) *node { return &node{ val: val, end: isEnd, links: make([]*node, 0), } } func (n *node) add(rs []rune) { cur := n for k, v := range rs { isEnd := k == len(rs)-1 link := cur.linkByVal(v) if link == nil { link = newNode(v, isEnd) cur.links = append(cur.links, link) } cur = link } } func (n *node) find(rs []rune) bool { cur := n for _, v := range rs { cur = cur.linkByVal(v) if cur == nil { return false } } return cur.end } func (n *node) linkByVal(val rune) *node { for _, v := range n.links { if v.val == val { return v } } return nil }
package kace type node struct { val rune end bool links []*node } func newNode() *node { return &node{links: make([]*node, 0)} } func (n *node) add(rs []rune) { cur := n for _, v := range rs { link := cur.linkByVal(v) if link == nil { link = newNode() cur.links = append(cur.links, link) } cur = link } } func (n *node) find(rs []rune) bool { cur := n for _, v := range rs { cur = cur.linkByVal(v) if cur == nil { return false } } return cur.end } func (n *node) linkByVal(val rune) *node { for _, v := range n.links { if v.val == val { return v } } return nil }
Print encrypted records for debugging.
#! /usr/bin/env python3 import sqlite3 import bcrypt import hashlib from Crypto.Cipher import AES import codecs import json from password import encrypt, decrypt, toHex, fromHex pwdatabase = 'passwords.db' jsonfile = open('passwords.json', mode='w') password = input('Enter password: ') conn = sqlite3.connect(pwdatabase) pwHash, salt = conn.execute('select * from master_pass').fetchone() if bcrypt.checkpw(password, pwHash): print('Password is correct.') aes_key = toHex(bcrypt.kdf(password, salt, 16, 32)) records = [list(i) for i in conn.execute('select * from passwords')] print(records) for i in range(len(records)): records[i][3] = decrypt(aes_key, records[i][3]).decode() records[i][4] = decrypt(aes_key, records[i][4]).decode() json.dump(records,jsonfile) else: print('Incorrect password.') jsonfile.close() conn.close()
#! /usr/bin/env python3 import sqlite3 import bcrypt import hashlib from Crypto.Cipher import AES import codecs import json from password import encrypt, decrypt, toHex, fromHex pwdatabase = 'passwords.db' jsonfile = open('passwords.json', mode='w') password = input('Enter password: ') conn = sqlite3.connect(pwdatabase) pwHash, salt = conn.execute('select * from master_pass').fetchone() if bcrypt.checkpw(password, pwHash): print('Password is correct.') aes_key = toHex(bcrypt.kdf(password, salt, 16, 32)) records = [list(i) for i in conn.execute('select * from passwords')] for i in range(len(records)): records[i][3] = decrypt(aes_key, records[i][3]).decode() records[i][4] = decrypt(aes_key, records[i][4]).decode() json.dump(records,jsonfile) else: print('Incorrect password.') jsonfile.close() conn.close()
Use importlib from std (if possible)
""" An implementation of JSON Schema for Python The main functionality is provided by the validator classes for each of the supported JSON Schema versions. Most commonly, `validate` is the quickest way to simply validate a given instance under a schema, and will create a validator for you. """ from jsonschema.exceptions import ( ErrorTree, FormatError, RefResolutionError, SchemaError, ValidationError ) from jsonschema._format import ( FormatChecker, draft3_format_checker, draft4_format_checker, draft6_format_checker, draft7_format_checker, ) from jsonschema._types import TypeChecker from jsonschema.validators import ( Draft3Validator, Draft4Validator, Draft6Validator, Draft7Validator, RefResolver, validate, ) try: from importlib import metadata except ImportError: # for Python<3.8 import importlib_metadata as metdata __version__ = metadata.version("jsonschema")
""" An implementation of JSON Schema for Python The main functionality is provided by the validator classes for each of the supported JSON Schema versions. Most commonly, `validate` is the quickest way to simply validate a given instance under a schema, and will create a validator for you. """ from jsonschema.exceptions import ( ErrorTree, FormatError, RefResolutionError, SchemaError, ValidationError ) from jsonschema._format import ( FormatChecker, draft3_format_checker, draft4_format_checker, draft6_format_checker, draft7_format_checker, ) from jsonschema._types import TypeChecker from jsonschema.validators import ( Draft3Validator, Draft4Validator, Draft6Validator, Draft7Validator, RefResolver, validate, ) import importlib_metadata __version__ = importlib_metadata.version("jsonschema")
Fix version when typing version command Please also Update this when updating the version of the package.json
#! /usr/bin/env node var program = require('commander') var childProcess = require('child_process') var Generator = require('./generator') program .version('0.3.3') program .command('new <name>') .description('Generate scaffold for new Electron application') .action(function (name, options) { new Generator(name, options).generate() }) program .command('start') .description('Compile and run application') .action(function () { childProcess.spawn('gulp', ['start'], { stdio: 'inherit' }) }) program .command('test') .description('Compile and run application') .action(function () { childProcess.spawn('gulp', ['test'], { stdio: 'inherit' }) }) program .command('clear') .description('Clear builds and releases directories') .action(function () { childProcess.spawn('gulp', ['clear'], { stdio: 'inherit' }) }) program .command('package') .description('Build and Package applications for platforms defined in package.json') .action(function () { childProcess.spawn('gulp', ['package'], { stdio: 'inherit' }) }) program.parse(process.argv)
#! /usr/bin/env node var program = require('commander') var childProcess = require('child_process') var Generator = require('./generator') program .version('0.1.0') program .command('new <name>') .description('Generate scaffold for new Electron application') .action(function (name, options) { new Generator(name, options).generate() }) program .command('start') .description('Compile and run application') .action(function () { childProcess.spawn('gulp', ['start'], { stdio: 'inherit' }) }) program .command('test') .description('Compile and run application') .action(function () { childProcess.spawn('gulp', ['test'], { stdio: 'inherit' }) }) program .command('clear') .description('Clear builds and releases directories') .action(function () { childProcess.spawn('gulp', ['clear'], { stdio: 'inherit' }) }) program .command('package') .description('Build and Package applications for platforms defined in package.json') .action(function () { childProcess.spawn('gulp', ['package'], { stdio: 'inherit' }) }) program.parse(process.argv)
Change copyright in Apache 2 license to 2013
/** * Copyright © 2011-2013 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.dao; /** * * Phenotyping project data access manager interface. * * @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk> * @since February 2012 */ import java.util.List; import uk.ac.ebi.phenotype.pojo.Project; public interface ProjectDAO { /** * Get all projects in the system * @return all projects */ public List<Project> getAllProjects(); /** * Find an project by its number. * @param name the project name * @return the project */ public Project getProjectByName(String name); }
/** * Copyright © 2011-2012 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.dao; /** * * Phenotyping project data access manager interface. * * @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk> * @since February 2012 */ import java.util.List; import uk.ac.ebi.phenotype.pojo.Project; public interface ProjectDAO { /** * Get all projects in the system * @return all projects */ public List<Project> getAllProjects(); /** * Find an project by its number. * @param name the project name * @return the project */ public Project getProjectByName(String name); }
Delete double formatting in string field
<?php namespace Zerg\Field; use Zerg\Stream\AbstractStream; /** * String represents string type data. * * Data, parsed by this type of field returns as it is in binary file. * @since 0.1 * */ class String extends Scalar { /** * @var bool Whether returned string should process like UTF-8 encoded. * */ protected $utf; /** * Read string from stream as it is. * * @param AbstractStream $stream Stream from which read. * @return string Returned string. */ public function read(AbstractStream $stream) { $string = $stream->getReader() ->setCurrentBit(0) ->readString($this->getSize()); if ($this->utf) { if (strlen($string) < 2) { return ''; } if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff || ord($string[0]) == 0xff && ord($string[1]) == 0xfe) { $string = substr($string, 2); } return $string; } return $string; } }
<?php namespace Zerg\Field; use Zerg\Stream\AbstractStream; /** * String represents string type data. * * Data, parsed by this type of field returns as it is in binary file. * @since 0.1 * */ class String extends Scalar { /** * @var bool Whether returned string should process like UTF-8 encoded. * */ protected $utf; /** * Read string from stream as it is. * * @param AbstractStream $stream Stream from which read. * @return string Returned string. */ public function read(AbstractStream $stream) { $string = $stream->getReader() ->setCurrentBit(0) ->readString($this->getSize()); if ($this->utf) { if (strlen($string) < 2) { return ''; } if (ord($string[0]) == 0xfe && ord($string[1]) == 0xff || ord($string[0]) == 0xff && ord($string[1]) == 0xfe) { $string = substr($string, 2); } return $string; } return $this->format($string); } }
Remove useless assertion in quotes test.
"use strict"; var vows = require("vows"), assert = require("assert"), quotes = require("../lib/quotes"); vows.describe("Quotes tests").addBatch({ "get quotes with ref date in the past": { topic: function () { quotes.getQuotes(["YHOO"], new Date("Sat Aug 06 2011 12:00:00"), this.callback); }, "check quotes with ref date in the past": function (err, qs) { assert.ok(!err && qs[0].beforeRefDate.length > 0); assert.ok(!err && qs[0].afterRefDate.length > 0); } }, "get quotes": { topic: function () { quotes.getQuotes(["YHOO"], new Date(), this.callback); }, "check quotes": function (err, qs) { assert.ok(!err && qs[0].beforeRefDate.length > 0); assert.ok(!err && qs[0].afterRefDate.length === 0); } } }).export(module);
"use strict"; var vows = require("vows"), assert = require("assert"), quotes = require("../lib/quotes"); vows.describe("Quotes tests").addBatch({ "get quotes with ref date in the past": { topic: function () { quotes.getQuotes(["YHOO"], new Date("Sat Aug 06 2011 12:00:00"), this.callback); }, "check quotes with ref date in the past": function (err, qs) { assert.ok(!err && qs[0].beforeRefDate.length > 0); assert.ok(!err && qs[0].afterRefDate.length > 0); assert.ok(!err && (qs[0].beforeRefDate.length === qs[0].beforeRefDate.length)); } }, "get quotes": { topic: function () { quotes.getQuotes(["YHOO"], new Date(), this.callback); }, "check quotes": function (err, qs) { assert.ok(!err && qs[0].beforeRefDate.length > 0); assert.ok(!err && qs[0].afterRefDate.length === 0); } } }).export(module);
Fix webpack 5 library type
/* eslint-disable @typescript-eslint/no-var-requires */ "use strict"; var resolve = require("path").resolve; var webpack = require("webpack"); module.exports = { mode: "production", entry: ["regenerator-runtime/runtime", resolve(__dirname, "src/web.js")], devtool: "source-map", output: { path: resolve(__dirname, "build"), filename: "web.js", library: { name: "arangojs", type: "umd" }, }, module: { rules: [ // NOTE: these rules apply in reverse order { test: /\.(ts|js)$/, loader: "babel-loader", }, ], }, resolve: { extensions: [".web.js", ".web.ts", ".js", ".ts", ".json"], fallback: { url: require.resolve("url/"), querystring: require.resolve("querystring/"), }, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: '"production"' }, }), ], };
/* eslint-disable @typescript-eslint/no-var-requires */ "use strict"; var resolve = require("path").resolve; var webpack = require("webpack"); module.exports = { mode: "production", entry: ["regenerator-runtime/runtime", resolve(__dirname, "src/web.js")], devtool: "source-map", output: { path: resolve(__dirname, "build"), filename: "web.js", library: "arangojs", libraryTarget: "umd", }, module: { rules: [ // NOTE: these rules apply in reverse order { test: /\.(ts|js)$/, loader: "babel-loader", }, ], }, resolve: { extensions: [".web.js", ".web.ts", ".js", ".ts", ".json"], fallback: { url: require.resolve("url/"), querystring: require.resolve("querystring/"), }, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: '"production"' }, }), ], };
Use tan for cool effects
const WIDTH = 800; const HEIGHT = 600; const SPACING = 25; const RECT_SIZE_X = 15; const RECT_SIZE_Y = 2; var setup = function() { createCanvas(WIDTH, HEIGHT); background(0); fill(255); angleMode(RADIANS); stroke(255); strokeWeight(1); strokeCap(SQUARE); } var drawRectangle = (posX, posY, angle) => { push(); translate(posX, posY); rotate(angle); rect(-(RECT_SIZE_X/2), -(RECT_SIZE_Y/2), RECT_SIZE_X, RECT_SIZE_Y); pop(); } var draw = function() { const targetX = 3; const targetY = 5; for (let x = 1; x < 32; x++) { for (let y = 1; y < 24; y++) { const angle = Math.atan(x - targetX/y - targetY); drawRectangle(x * SPACING, y * SPACING, angle); } } }
const WIDTH = 800; const HEIGHT = 600; const SPACING = 25; const RECT_SIZE_X = 15; const RECT_SIZE_Y = 2; var setup = function() { createCanvas(WIDTH, HEIGHT); background(0); fill(255); angleMode(DEGREES); stroke(255); strokeWeight(1); strokeCap(SQUARE); } var drawRectangle = (posX, posY, angle) => { push(); translate(posX, posY); rotate(angle); rect(-(RECT_SIZE_X/2), -(RECT_SIZE_Y/2), RECT_SIZE_X, RECT_SIZE_Y); pop(); } var draw = function() { translate(SPACING, SPACING); const targetX = 3; const targetY = 5; for (let x = 0; x < 31; x++) { for (let y = 0; y < 23; y++) { if (!(x === targetX && y === targetY)) { drawRectangle(x * SPACING, y * SPACING, 45); } } } }
Add check for if request was for profile data
angular .module('confRegistrationWebApp') .factory( 'unauthorizedInterceptor', function ($window, $q, $cookies, envService, $location, loginDialog) { return { responseError: function (rejection) { if ( rejection.status === 401 && !rejection.config.url.includes('/profile') && angular.isDefined($cookies.get('crsToken')) ) { if ($cookies.get('crsAuthProviderType') === 'NONE') { $window.location.href = envService.read('apiUrl') + 'auth/none/login'; } else { if (!/^\/auth\/.*/.test($location.url())) { $cookies.put('intendedRoute', $location.path()); } loginDialog.show({ status401: true }); } } return $q.reject(rejection); }, }; }, );
angular .module('confRegistrationWebApp') .factory( 'unauthorizedInterceptor', function ($window, $q, $cookies, envService, $location, loginDialog) { return { responseError: function (rejection) { if ( rejection.status === 401 && angular.isDefined($cookies.get('crsToken')) ) { if ($cookies.get('crsAuthProviderType') === 'NONE') { $window.location.href = envService.read('apiUrl') + 'auth/none/login'; } else { if (!/^\/auth\/.*/.test($location.url())) { $cookies.put('intendedRoute', $location.path()); } loginDialog.show({ status401: true }); } } return $q.reject(rejection); }, }; }, );
Add images and flavors commands
var path = require('path'); var fs = require('fs'); var flatiron = require('flatiron'); var pkgcloud = require('pkgcloud'); var santa = module.exports = flatiron.app; santa.use(flatiron.plugins.cli, { version: true, source: path.join(__dirname, 'commands'), usage: [ 'Welcome to santa!', '', 'Available commands:', '', 'Servers', '', ' santa servers list', ' santa servers destroy <id>', '', '', 'Images', '', ' santa images list', '', 'Flavors', '', ' santa flavors list', '', 'Deployment', '', ' santa deploy', '' ] }); var packageUri = path.join(process.cwd(), 'package.json'); var santaConf = {}; try { santaConf = JSON.parse(fs.readFileSync(packageUri)).santaConfig || {} } catch (err) { /* do nothing */ } santa.config .env() .file(santa.argv.config || santa.argv.c || path.join(process.env.HOME, '.santaconf')) .defaults(santaConf) santa.use(require('flatiron-cli-config'), { store: 'file' }); santa.pkgcloud = pkgcloud.compute.createClient(santa.config.get('provider'));
var path = require('path'); var fs = require('fs'); var flatiron = require('flatiron'); var pkgcloud = require('pkgcloud'); var santa = module.exports = flatiron.app; santa.use(flatiron.plugins.cli, { version: true, source: path.join(__dirname, 'commands'), usage: [ 'Welcome to santa!', '', 'Available commands:', '', 'Servers', '', ' santa servers list', ' santa servers destroy <id>', '', 'Deployment', '', ' santa deploy', '' ] }); var packageUri = path.join(process.cwd(), 'package.json'); var santaConf = {}; try { santaConf = JSON.parse(fs.readFileSync(packageUri)).santaConfig || {} } catch (err) { /* do nothing */ } santa.config .env() .file(santa.argv.config || santa.argv.c || path.join(process.env.HOME, '.santaconf')) .defaults(santaConf) santa.use(require('flatiron-cli-config'), { store: 'file' }); santa.pkgcloud = pkgcloud.compute.createClient(santa.config.get('provider'));
Update example to use state-reuse init
var flux = require('flux-redux'); /** * To take over from server rendering, we must re-use the data that the * server used, by passing it into the dispatcher init */ /*global initialStoreData*/ var state = typeof initialStoreData == 'object' ? initialStoreData : {}; var dispatcher = flux.createDispatcher({state}); /** * Hot reloading stores! * * The trick is to always re-use the `dispatcher` instance * * dispatcher.addStore will use the stores' merge functions * when re-adding another store with the same key */ if (module.hot) { if (module.hot.data) { dispatcher = module.hot.data.dispatcher; } module.hot.accept(); module.hot.dispose(hot => hot.dispatcher = dispatcher); } var data = require('./data'); var routing = require('./stores/routing'); dispatcher.addInterceptor('routing', routing.interceptor); dispatcher.addStore('routing', routing.store); var films = require('./stores/films'); data.addHandlers(films.handlers); dispatcher.addStore('films', films.store); var planets = require('./stores/planets'); data.addHandlers(planets.handlers); dispatcher.addStore('planets', planets.store); module.exports = dispatcher;
var flux = require('flux-redux'); /** * Hot reloading stores! * * The trick is to always re-use the `dispatcher` instance * * dispatcher.addStore will use the stores' merge functions * when re-adding another store with the same key */ var dispatcher = flux.createDispatcher(); if (module.hot) { if (module.hot.data) { dispatcher = module.hot.data.dispatcher; } module.hot.accept(); module.hot.dispose(hot => hot.dispatcher = dispatcher); } // Server data hydration - this should be in the core lib /*global initialStoreData*/ if (typeof initialStoreData == 'object') { Object.keys(initialStoreData).forEach(k => { dispatcher.addStore(k, {initial: () => initialStoreData[k]}); delete initialStoreData[k]; }); } var data = require('./data'); var routing = require('./stores/routing'); dispatcher.addInterceptor('routing', routing.interceptor); dispatcher.addStore('routing', routing.store); var films = require('./stores/films'); data.addHandlers(films.handlers); dispatcher.addStore('films', films.store); var planets = require('./stores/planets'); data.addHandlers(planets.handlers); dispatcher.addStore('planets', planets.store); module.exports = dispatcher;
Check if argument provided is a plin object
module.exports = (function () { 'use strict'; // Require dependencies var u = require('utils/index'), iterate = require('_iterator'); /** * Applies CSS styles to DOM element(s). * @param {object} styles Object literal holding CSS style properties. * @return {object} The DOMQuery object */ return function css(styles) { /** * @private * @param {object} element The HTML element to add the styles on. */ function applyStyles(element) { u.is.plainObject(styles) && Object.keys(styles).forEach(function (key) { element.style[key] = styles[key]; }); } iterate(this, function (el) { u.is.element(el) && applyStyles(el); }); return this; }; }());
module.exports = (function () { 'use strict'; // Require dependencies var u = require('utils/index'), iterate = require('_iterator'); /** * Applies CSS styles to DOM element(s). * @param {object} styles Object literal holding CSS style properties. * @return {*} */ return function css(styles) { /** * @private * @param {object} element The HTML element to add the syyles on. */ function applyStyles(element) { Object.keys(styles).forEach(function (key) { element.style[key] = styles[key]; }); } iterate(this, function (el) { u.is.element(el) && applyStyles(el); }); return this; }; }());
Add summary lines to output
let tests = [ // what result to expect, string to match against [ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ], [ true, '/home/mike/git/work/stripes-loader/' ], [ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ], [ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ], [ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ], ]; // The regexp used in webpack.config.base.js to choose which source files get transpiled let re = /\/stripes-/; let failed = 0; for (let i = 0; i < tests.length; i++) { var test = tests[i]; var expected = test[0]; var string = test[1]; var result = !!string.match(re); print(i + ": '" + string + "': " + "expected " + expected + ", got " + result + ": " + (result == expected ? "OK" : "FAIL")); if (result != expected) failed++; } let passed = tests.length - failed; print("Passed " + passed + " of " + tests.length + " tests"); if (failed > 0) { print("FAILED " + failed + " of " + tests.length + " tests"); }
let tests = [ // what result to expect, string to match against [ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ], [ true, '/home/mike/git/work/stripes-loader/' ], [ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ], [ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ], [ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ], ]; // The regexp used in webpack.config.base.js to choose which source files get transpiled let re = /\/stripes-/; for (let i = 0; i < tests.length; i++) { var test = tests[i]; var expected = test[0]; var string = test[1]; var result = !!string.match(re); print(i + ": '" + string + "': " + "expected " + expected + ", got " + result + ": " + (result == expected ? "OK" : "FAIL")); }
:bug: Fix first option not changed
import Select from '../u-select.vue'; export default { name: 'u-select--0', childName: 'u-select--0-item', mixins: [Select], methods: { select($event) { const oldValue = this.value; const value = $event.target.value || undefined; this.watchValue(value); const item = this.selectedVM && this.selectedVM.item; this.$emit('input', value); this.$emit('update:value', value); this.$emit('select', { value, oldValue, item, itemVM: this.selectedVM, }); }, }, };
import Select from '../u-select.vue'; export default { name: 'u-select--0', childName: 'u-select--0-item', mixins: [Select], methods: { select($event) { const oldValue = this.value; const value = $event.target.value; this.selectedVM = this.itemVMs.find((itemVM) => itemVM.value === value); const item = this.selectedVM && this.selectedVM.item; this.$emit('input', value); this.$emit('update:value', value); this.$emit('select', { value, oldValue, item, itemVM: this.selectedVM, }); }, }, };
Fix eslint ts override tsx matching
module.exports = { "extends": ["matrix-org", "matrix-org/react"], "env": { "browser": true, "node": true, }, "rules": { "quotes": "off", }, "overrides": [{ "files": ["src/**/*.{ts,tsx}"], "extends": ["matrix-org/ts", "matrix-org/react"], "env": { "browser": true, }, "rules": { "quotes": "off", // While converting to ts we allow this "@typescript-eslint/no-explicit-any": "off", "prefer-promise-reject-errors": "off", }, }], };
module.exports = { "extends": ["matrix-org", "matrix-org/react"], "env": { "browser": true, "node": true, }, "rules": { "quotes": "off", }, "overrides": [{ "files": ["src/**/*.{ts, tsx}"], "extends": ["matrix-org/ts", "matrix-org/react"], "env": { "browser": true, }, "rules": { "quotes": "off", // While converting to ts we allow this "@typescript-eslint/no-explicit-any": "off", "prefer-promise-reject-errors": "off", }, }], };
Fix case issue on class name.
<?php namespace Travis; class Inline { /** * Return HTML w/ inline CSS. * * @param string $html * @return string */ public static function run($html) { // build object $clean = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles(); // set html $clean->setHTML($html); // css included w/ html $clean->setUseInlineStylesBlock(true); // convert to html $html = $clean->convert(false); // false for HTML mode (not XHTML, works better) // return return $html; } /** * Legacy alias method. * * @param string $html * @return string */ public static function convert($html) { // legacy alias return static::run($html); } }
<?php namespace Travis; class Inline { /** * Return HTML w/ inline CSS. * * @param string $html * @return string */ public static function run($html) { // build object $clean = new \TijsVerkoyen\CssToInlineStyles\CSSToInlineStyles(); // set html $clean->setHTML($html); // css included w/ html $clean->setUseInlineStylesBlock(true); // convert to html $html = $clean->convert(false); // false for HTML mode (not XHTML, works better) // return return $html; } /** * Legacy alias method. * * @param string $html * @return string */ public static function convert($html) { // legacy alias return static::run($html); } }
Change font sizes on form
import React from 'react'; import { View, TextInput, Text, StyleSheet } from 'react-native'; const InputField = ({ label, secureTextEntry, placeholder, onChangeText, value, autoCorrect, autoFocus }) => { return( <View> <Text style={styles.labelText}> {label} </Text> <TextInput style={styles.inputBox} secureTextEntry={secureTextEntry} placeholder={placeholder} onChangeText={onChangeText} value={value} autoCorrect={false} autoFocus={autoFocus} /> </View> ); }; const styles = StyleSheet.create ({ inputBox: { marginBottom: 20, fontSize: 20 }, labelText: { fontSize: 16 } }) export default InputField;
import React from 'react'; import { View, TextInput, Text, StyleSheet } from 'react-native'; const InputField = ({ label, secureTextEntry, placeholder, onChangeText, value, autoCorrect, autoFocus }) => { return( <View> <Text style={styles.labelText}> {label} </Text> <TextInput style={styles.inputBox} secureTextEntry={secureTextEntry} placeholder={placeholder} onChangeText={onChangeText} value={value} autoCorrect={false} autoFocus={autoFocus} /> </View> ); }; const styles = StyleSheet.create ({ inputBox: { marginBottom: 20, fontSize: 24 }, labelText: { fontSize: 18 } }) export default InputField;
[FIX] mrp_product_variants: Fix MTO configurator not filled
# -*- coding: utf-8 -*- # © 2015 Oihane Crucelaegui - AvanzOSC # © 2016 Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import api, models class ProcurementOrder(models.Model): _inherit = 'procurement.order' @api.model def _prepare_mo_vals(self, procurement): result = super(ProcurementOrder, self)._prepare_mo_vals(procurement) product_id = result.get('product_id') product = self.env['product.product'].browse(product_id) result['product_tmpl_id'] = product.product_tmpl_id.id product_attribute_ids = product._get_product_attributes_values_dict() result['product_attribute_ids'] = map( lambda x: (0, 0, x), product_attribute_ids) for val in result['product_attribute_ids']: val = val[2] val['product_tmpl_id'] = product.product_tmpl_id.id val['owner_model'] = 'mrp.production' return result
# -*- coding: utf-8 -*- # © 2015 Oihane Crucelaegui - AvanzOSC # © 2016 Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import api, models class ProcurementOrder(models.Model): _inherit = 'procurement.order' @api.model def _prepare_mo_vals(self, procurement): result = super(ProcurementOrder, self)._prepare_mo_vals(procurement) product_id = result.get('product_id') product = self.env['product.product'].browse(product_id) result['product_tmpl_id'] = product.product_tmpl_id.id result['product_attribute_ids'] = ( (0, 0, x) for x in product._get_product_attributes_values_dict()) for val in result['product_attribute_ids']: val = val[2] val['product_tmpl_id'] = product.product_tmpl_id.id val['owner_model'] = 'mrp.production' return result
Extend a request body parsing
import mongoose from 'mongoose' import {logger, http_logger} from './utils/logger' import express from 'express' import cookie_parser from 'cookie-parser' import body_parser from 'body-parser' import express_validator from 'express-validator' import {group_router} from './routers/group_router' import {user_router} from './routers/user_router' import {error_handler} from './utils/errors' mongoose.Promise = global.Promise mongoose .connect( process.env.VK_GROUP_STATS_MONGODB_HOST || 'localhost', process.env.VK_GROUP_STATS_MONGODB_DATABASE || 'vk-group-stats', process.env.VK_GROUP_STATS_MONGODB_PORT || 27017 ) .then(() => { logger.info('app connected to MongoDB') const app = express() app.use(http_logger) app.use(cookie_parser()) app.use(body_parser.urlencoded({ extended: true, })) app.use(body_parser.json()) app.use(express_validator()) app.use(group_router) app.use(user_router) app.use(error_handler) const port = process.env.VK_GROUP_STATS_SERVER_PORT || 3000 app.listen(port, () => { logger.info(`app listening on port ${port}`) }) }) .catch(error => { logger.error(`app can't connect to MongoDB: ${util.inspect(error)}`) })
import mongoose from 'mongoose' import {logger, http_logger} from './utils/logger' import express from 'express' import cookie_parser from 'cookie-parser' import body_parser from 'body-parser' import express_validator from 'express-validator' import {group_router} from './routers/group_router' import {user_router} from './routers/user_router' import {error_handler} from './utils/errors' mongoose.Promise = global.Promise mongoose .connect( process.env.VK_GROUP_STATS_MONGODB_HOST || 'localhost', process.env.VK_GROUP_STATS_MONGODB_DATABASE || 'vk-group-stats', process.env.VK_GROUP_STATS_MONGODB_PORT || 27017 ) .then(() => { logger.info('app connected to MongoDB') const app = express() app.use(http_logger) app.use(cookie_parser()) app.use(body_parser.json()) app.use(express_validator()) app.use(group_router) app.use(user_router) app.use(error_handler) const port = process.env.VK_GROUP_STATS_SERVER_PORT || 3000 app.listen(port, () => { logger.info(`app listening on port ${port}`) }) }) .catch(error => { logger.error(`app can't connect to MongoDB: ${util.inspect(error)}`) })
Remove misplaced optimism about escape analysis.
package multihash import ( "errors" ) // ErrSumNotSupported is returned when the Sum function code is not implemented var ErrSumNotSupported = errors.New("Function not implemented. Complain to lib maintainer.") var ErrLenTooLarge = errors.New("requested length was too large for digest") // Sum obtains the cryptographic sum of a given buffer. The length parameter // indicates the length of the resulting digest and passing a negative value // use default length values for the selected hash function. func Sum(data []byte, code uint64, length int) (Multihash, error) { // Get the algorithm. hasher, err := GetHasher(code) if err != nil { return nil, err } // Feed data in. hasher.Write(data) // Compute final hash. // A new slice is allocated. FUTURE: see other comment below about allocation, and review together with this line to try to improve. sum := hasher.Sum(nil) // Deal with any truncation. if length < 0 { length = hasher.Size() } if len(sum) < length { return nil, ErrLenTooLarge } if length >= 0 { sum = sum[:length] } // Put the multihash metainfo bytes at the front of the buffer. // FUTURE: try to improve allocations here. Encode does several which are probably avoidable, but it's the shape of the Encode method arguments that forces this. return Encode(sum, code) }
package multihash import ( "errors" ) // ErrSumNotSupported is returned when the Sum function code is not implemented var ErrSumNotSupported = errors.New("Function not implemented. Complain to lib maintainer.") var ErrLenTooLarge = errors.New("requested length was too large for digest") // Sum obtains the cryptographic sum of a given buffer. The length parameter // indicates the length of the resulting digest and passing a negative value // use default length values for the selected hash function. func Sum(data []byte, code uint64, length int) (Multihash, error) { // Get the algorithm. hasher, err := GetHasher(code) if err != nil { return nil, err } // Feed data in. hasher.Write(data) // Compute hash. // Use a fixed size array here: should keep things on the stack. var space [64]byte sum := hasher.Sum(space[0:0]) // Deal with any truncation. if length < 0 { length = hasher.Size() } if len(sum) < length { return nil, ErrLenTooLarge } if length >= 0 { sum = sum[:length] } // Put the multihash metainfo bytes at the front of the buffer. // FIXME: this does many avoidable allocations, but it's the shape of the Encode method arguments that forces this. return Encode(sum, code) }
Fix the things that are broken
####################### # PRODUCTION SETTINGS # ####################### from os import environ from django.core.exceptions import ImproperlyConfigured from .base import * DEBUG = False def get_env_setting(setting): """ Get the environment setting or return exception """ try: return environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) ###################### # HOST CONFIGURATION # ###################### # https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts # https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production ALLOWED_HOSTS = ['.texastribune.org'] ############################ # SECRET KEY CONFIGURATION # ############################ # https://docs.djangoproject.com/en/1.7/ref/settings/#secret-key SECRET_KEY = get_env_setting('SECRET_KEY')
####################### # PRODUCTION SETTINGS # ####################### from os import environ from django.core.exceptions import ImproperlyConfigured from .base import * DEBUG = False def get_env_setting(setting): """ Get the environment setting or return exception """ try: return environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) ###################### # HOST CONFIGURATION # ###################### # https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts # https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production ALLOWED_HOSTS = ['*.texastribune.org'] ############################ # SECRET KEY CONFIGURATION # ############################ # https://docs.djangoproject.com/en/1.7/ref/settings/#secret-key SECRET_KEY = get_env_setting('SECRET_KEY')
Revert "Removed Django requirement due versioning" This reverts commit 78bae13778ec70cd3654e74a684839914f44364e.
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-mailer", version=__import__("mailer").__version__, description="A reusable Django app for queuing the sending of email", long_description=open("docs/usage.rst").read() + open("CHANGES.rst").read(), author="Pinax Team", author_email="developers@pinaxproject.com", url="http://github.com/pinax/django-mailer/", packages=find_packages(), package_dir={"mailer": "mailer"}, package_data={'mailer': ['locale/*/LC_MESSAGES/*.*']}, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Framework :: Django", ], install_requires=[ 'Django >= 1.4', 'lockfile >= 0.8', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-mailer", version=__import__("mailer").__version__, description="A reusable Django app for queuing the sending of email", long_description=open("docs/usage.rst").read() + open("CHANGES.rst").read(), author="Pinax Team", author_email="developers@pinaxproject.com", url="http://github.com/pinax/django-mailer/", packages=find_packages(), package_dir={"mailer": "mailer"}, package_data={'mailer': ['locale/*/LC_MESSAGES/*.*']}, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Framework :: Django", ], install_requires=[ # 'Django', 'lockfile >= 0.8', ], )
Improve logging for HTTP debug mode
var assert = require('assert'); var expect = require('chai').expect; var Fabric = require('../'); var server = new Fabric.HTTP(); describe('HTTP', function () { before(function (done) { server.define('Widget', { properties: { name: { type: String , maxLength: 100 } }, routes: { query: '/widgets', get: '/widgets/:id' } }); server.start(done); }); after(async function () { await server.stop(); }); it('should expose a constructor', function () { assert.equal(typeof Fabric.HTTP, 'function'); }); it('can serve a resource', async function () { let remote = new Fabric.Remote({ host: 'localhost:3000' }); let payload = { name: 'foobar' }; let vector = new Fabric.Vector(payload); vector._sign(); let result = await remote._POST('/widgets', payload); let object = await remote._GET('/widgets'); console.log('result:', result); console.log('object:', object); assert.equal(result['@id'], vector['@id']); assert.equal(object[0]['@id'], vector['@id']); }); });
var assert = require('assert'); var expect = require('chai').expect; var Fabric = require('../'); var server = new Fabric.HTTP(); describe('HTTP', function () { before(function (done) { server.define('Widget', { properties: { name: { type: String , maxLength: 100 } }, routes: { query: '/widgets', get: '/widgets/:id' } }); server.start(done); }); after(async function () { await server.stop(); }); it('should expose a constructor', function () { assert.equal(typeof Fabric.HTTP, 'function'); }); it('can serve a resource', async function () { let remote = new Fabric.Remote({ host: 'localhost:3000' }); let payload = { name: 'foobar' }; let vector = new Fabric.Vector(payload); vector._sign(); let result = await remote._POST('/widgets', payload); let object = await remote._GET('/widgets'); assert.equal(result['@id'], vector['@id']); assert.equal(object[0]['@id'], vector['@id']); }); });