text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set private repo from ENV var
export default { port: process.env.UPDATES_PORT || process.env.PORT || 3000, host: process.env.UPDATES_HOST || '0.0.0.0', github: { token: process.env.GITHUB_TOKEN, api: { version: '3.0.0', headers: { 'user-agent': 'Aluxian/squirrel-updates-server' } } }, user: process.env.REPO_OWNER || 'Aluxian', repo: process.env.REPO_NAME || 'Whatsie', privateRepo: process.env.UPDATES_PRIVATE_REPO || false, patterns: { darwin: { dmg: /-osx\.dmg/, zip: /-osx\.zip/ }, win32: { installer: /-win32-setup\.exe/, zip: /-win32-portable\.zip/ }, linux: { deb: { i386: /-linux-i386\.deb/, amd64: /-linux-amd64\.deb/ }, rpm: { i386: /-linux-i386\.rpm/, x86_64: /-linux-x86_64\.rpm/ } } } };
export default { port: process.env.UPDATES_PORT || process.env.PORT || 3000, host: process.env.UPDATES_HOST || '0.0.0.0', github: { token: process.env.GITHUB_TOKEN, api: { version: '3.0.0', headers: { 'user-agent': 'Aluxian/squirrel-updates-server' } } }, user: process.env.REPO_OWNER || 'Aluxian', repo: process.env.REPO_NAME || 'Whatsie', privateRepo: false, patterns: { darwin: { dmg: /-osx\.dmg/, zip: /-osx\.zip/ }, win32: { installer: /-win32-setup\.exe/, zip: /-win32-portable\.zip/ }, linux: { deb: { i386: /-linux-i386\.deb/, amd64: /-linux-amd64\.deb/ }, rpm: { i386: /-linux-i386\.rpm/, x86_64: /-linux-x86_64\.rpm/ } } } };
Call the right method on the send_weekly_emails Command.
# This file is part of OpenHatch. # Copyright (C) 2010 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.core.management.base import BaseCommand import logging import mysite.profile.tasks import mysite.profile.management.commands.send_weekly_emails class Command(BaseCommand): help = "Run this once daily for the OpenHatch profile app." def handle(self, *args, **options): # Garbage collect forwarders root_logger = logging.getLogger('') root_logger.setLevel(logging.WARN) mysite.profile.tasks.GarbageCollectForwarders().run() # Try to send the emails. The command will only actually send emails at # most once per week. command = mysite.profile.management.commands.send_weekly_emails.Command() command.handle()
# This file is part of OpenHatch. # Copyright (C) 2010 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.core.management.base import BaseCommand import logging import mysite.profile.tasks import mysite.profile.management.commands.send_weekly_emails class Command(BaseCommand): help = "Run this once daily for the OpenHatch profile app." def handle(self, *args, **options): # Garbage collect forwarders root_logger = logging.getLogger('') root_logger.setLevel(logging.WARN) mysite.profile.tasks.GarbageCollectForwarders().run() # Try to send the emails. The command will only actually send emails at # most once per week. command = mysite.profile.management.commands.send_weekly_emails.Command() command.run()
Allow Instatrace().init(None) to disable tracing at runtime
# Copyright (C) 2010 Peter Teichman import math import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """High resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) self._fd.flush()
# Copyright (C) 2010 Peter Teichman import math import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """High resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) self._fd.flush()
Disable pull-to-refresh and overscroll glow
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; overscroll-behavior-y: none; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
Fix warning message caused by d5ee6ed
define( [ "store/TwitchSerializer" ], function( TwitchSerializer ) { return TwitchSerializer.extend({ primaryKey: "name", modelNameFromPayloadKey: function() { return "twitchChannel"; }, normalizeResponse: function( store, primaryModelClass, payload, id, requestType ) { payload = { twitchChannel: payload }; return this._super( store, primaryModelClass, payload, id, requestType ); }, normalize: function( modelClass, resourceHash, prop ) { // Twitch.tv API bug? // Sometimes a user record (/user/:user - model not implemented) is embedded into // a stream record instead of a channels record (/channels/:channel - the current model) if ( resourceHash ) { delete resourceHash.bio; delete resourceHash.type; // also remove the teams property for now delete resourceHash.teams; } return this._super( modelClass, resourceHash, prop ); } }); });
define( [ "store/TwitchSerializer" ], function( TwitchSerializer ) { return TwitchSerializer.extend({ primaryKey: "name", modelNameFromPayloadKey: function() { return "twitchChannel"; }, attrs : { teams: { deserialize: "records" } }, normalizeResponse: function( store, primaryModelClass, payload, id, requestType ) { payload = { twitchChannel: payload }; return this._super( store, primaryModelClass, payload, id, requestType ); }, normalize: function( modelClass, resourceHash, prop ) { // Twitch.tv API bug? // Sometimes a user record (/user/:user - model not implemented) is embedded into // a stream record instead of a channels record (/channels/:channel - the current model) if ( resourceHash ) { delete resourceHash.bio; delete resourceHash.type; // also remove the teams property for now delete resourceHash.teams; } return this._super( modelClass, resourceHash, prop ); } }); });
Downgrade migration table name updated is current
"""create redmine tables Revision ID: d596dc9b53d9 Revises: 2ffb0d589280 Create Date: 2017-08-14 14:43:31.234637 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd596dc9b53d9' down_revision = '2ffb0d589280' branch_labels = None depends_on = None def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('redmine_users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Unicode(length=16), nullable=False), sa.Column('api_key', sa.Unicode(length=40), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_table('redmine_projectchannel', sa.Column('id', sa.Integer(), nullable=False), sa.Column('project_id', sa.Integer(), nullable=False), sa.Column('channels', sa.Unicode(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('redmine_projectchannel') op.drop_table('redmine_users') ### end Alembic commands ###
"""create redmine tables Revision ID: d596dc9b53d9 Revises: 2ffb0d589280 Create Date: 2017-08-14 14:43:31.234637 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd596dc9b53d9' down_revision = '2ffb0d589280' branch_labels = None depends_on = None def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('redmine_users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Unicode(length=16), nullable=False), sa.Column('api_key', sa.Unicode(length=40), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_table('redmine_projectchannel', sa.Column('id', sa.Integer(), nullable=False), sa.Column('project_id', sa.Integer(), nullable=False), sa.Column('channels', sa.Unicode(length=255), nullable=False), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('remine_projectroom') op.drop_table('redmine_users') ### end Alembic commands ###
Update pyyaml dep to 5.1+ Allows to turn off automatic sorting of dict keys.
import codecs from setuptools import find_packages, setup import digestive setup( name='digestive', version=digestive.__version__, # TODO: don't read this from (uninstalled) module url='https://github.com/akaIDIOT/Digestive', packages=find_packages(), description='Run several digest algorithms on the same data efficiently', author='Mattijs Ugen', author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'), license='ISC', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', ], install_requires=( 'decorator~=4.0', 'pyyaml~=5.1' ), entry_points={ 'console_scripts': { 'digestive = digestive.main:main' } } )
import codecs from setuptools import find_packages, setup import digestive setup( name='digestive', version=digestive.__version__, # TODO: don't read this from (uninstalled) module url='https://github.com/akaIDIOT/Digestive', packages=find_packages(), description='Run several digest algorithms on the same data efficiently', author='Mattijs Ugen', author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'), license='ISC', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3 :: Only', ], install_requires=( 'decorator~=4.0', 'pyyaml~=5.0' ), entry_points={ 'console_scripts': { 'digestive = digestive.main:main' } } )
Fix bug if model is initially null.
angular.module('gm.typeaheadDropdown', ['ui.bootstrap']) .directive('typeaheadDropdown', function() { return { templateUrl:'templates/typeaheadDropdown.tpl.html', scope: { model:'=ngModel', getOptions:'&options', config:'=?', required:'=?ngRequired' }, replace:true, controller: ['$scope', '$q', function($scope, $q) { $scope.config = angular.extend({ modelLabel:"name", optionLabel:"name" }, $scope.config); $q.when($scope.getOptions()) .then(function(options) { $scope.options = options; }); $scope.onSelect = function($item, $model, $label) { if(!$scope.model) $scope.model = {}; angular.extend($scope.model, $item); $scope.model[$scope.config.modelLabel] = $item[$scope.config.optionLabel]; } }] } })
angular.module('gm.typeaheadDropdown', ['ui.bootstrap']) .directive('typeaheadDropdown', function() { return { templateUrl:'templates/typeaheadDropdown.tpl.html', scope: { model:'=ngModel', getOptions:'&options', config:'=?', required:'=?ngRequired' }, replace:true, controller: ['$scope', '$q', function($scope, $q) { $scope.config = angular.extend({ modelLabel:"name", optionLabel:"name" }, $scope.config); $q.when($scope.getOptions()) .then(function(options) { $scope.options = options; }); $scope.onSelect = function($item, $model, $label) { angular.extend($scope.model, $item); $scope.model[$scope.config.modelLabel] = $item[$scope.config.optionLabel]; } }] } })
Use a bigger volume so it doesn't fill up
# Creates an EBS volume for the index and attaches it to a given instance as /dev/xvdf. # Prints the volume ID on stdout. # Usage: attach-index-volume.py <channel> <instance-id> import sys import boto3 import awslib from datetime import datetime channel = sys.argv[1] instanceId = sys.argv[2] ec2 = boto3.resource('ec2') client = boto3.client('ec2') # Find availability zone instances = ec2.instances.filter(InstanceIds=[instanceId]) instance = list(instances)[0] r = client.create_volume( Size=200, VolumeType='gp2', AvailabilityZone=instance.placement['AvailabilityZone'], ) volumeId = r['VolumeId'] awslib.await_volume(client, volumeId, 'creating', 'available') client.create_tags(Resources=[volumeId], Tags=[{ 'Key': 'index', 'Value': str(datetime.now()), }, { 'Key': 'channel', 'Value': channel, }]) instance.attach_volume(VolumeId=volumeId, Device='xvdf') awslib.await_volume(client, volumeId, 'available', 'in-use') print volumeId
# Creates an EBS volume for the index and attaches it to a given instance as /dev/xvdf. # Prints the volume ID on stdout. # Usage: attach-index-volume.py <channel> <instance-id> import sys import boto3 import awslib from datetime import datetime channel = sys.argv[1] instanceId = sys.argv[2] ec2 = boto3.resource('ec2') client = boto3.client('ec2') # Find availability zone instances = ec2.instances.filter(InstanceIds=[instanceId]) instance = list(instances)[0] r = client.create_volume( Size=100, VolumeType='gp2', AvailabilityZone=instance.placement['AvailabilityZone'], ) volumeId = r['VolumeId'] awslib.await_volume(client, volumeId, 'creating', 'available') client.create_tags(Resources=[volumeId], Tags=[{ 'Key': 'index', 'Value': str(datetime.now()), }, { 'Key': 'channel', 'Value': channel, }]) instance.attach_volume(VolumeId=volumeId, Device='xvdf') awslib.await_volume(client, volumeId, 'available', 'in-use') print volumeId
Change VSTS integration for markup change
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.tfs-selector span').innerText, container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.commandbar.header-bottom > .commandbar-item > .displayed').innerText; link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.menu-item.l1-navigation-text.drop-visible .text').textContent.trim(), container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.hub-list .menu-item.currently-selected').textContent.trim(); link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items*" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
Return null instead of void The return value is used in unit tests for comparisons, and returning null is slightly more specific.
<?php /* * This file is part of the Ivory Http Adapter package. * * (c) Eric GELOEN <geloen.eric@gmail.com> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\HttpAdapter\Normalizer; use Ivory\HttpAdapter\Asset\AbstractUninstantiableAsset; use Ivory\HttpAdapter\Message\RequestInterface; /** * Body normalizer. * * @author GeLo <geloen.eric@gmail.com> */ class BodyNormalizer extends AbstractUninstantiableAsset { /** * Normalizes the body. * * @param mixed $body The body. * @param string $method The method. * * @return mixed The normalized body. */ public static function normalize($body, $method) { if ($method === RequestInterface::METHOD_HEAD || empty($body)) { return null; } if (is_callable($body)) { return call_user_func($body); } return $body; } }
<?php /* * This file is part of the Ivory Http Adapter package. * * (c) Eric GELOEN <geloen.eric@gmail.com> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\HttpAdapter\Normalizer; use Ivory\HttpAdapter\Asset\AbstractUninstantiableAsset; use Ivory\HttpAdapter\Message\RequestInterface; /** * Body normalizer. * * @author GeLo <geloen.eric@gmail.com> */ class BodyNormalizer extends AbstractUninstantiableAsset { /** * Normalizes the body. * * @param mixed $body The body. * @param string $method The method. * * @return mixed The normalized body. */ public static function normalize($body, $method) { if ($method === RequestInterface::METHOD_HEAD || empty($body)) { return; } if (is_callable($body)) { return call_user_func($body); } return $body; } }
Remove default setting for TOC hierarchy
<?php # THIS ONE DOES NOT HAVE AddPageByArray ANY MORE :-) include("../mpdf.php"); $html_data = file_get_contents("body.html"); $html = substr($html_data, 12, strlen($html_data)-27); $style_data = file_get_contents("style_current.css"); $frontmatter_data = file_get_contents("frontmatter_current.html"); // Create new PDF with font subsetting, 234mm wide, 297mm high $mpdf = new mPDF('s', array(234,297)); // Make it DOUBLE SIDED document with 4mm bleed $mpdf->mirrorMargins = 1; $mpdf->bleedMargin = 4; $mpdf->WriteHTML($style_data, 1); $mpdf->WriteHTML($frontmatter_data, 2); $mpdf->WriteHTML($html, 2); $mpdf->SetTitle("An Example Title"); $mpdf->SetAuthor("Aco"); $mpdf->SetCreator("Booktype 2.0 and mPDF 6.0"); $mpdf->SetSubject("History"); $mpdf->SetKeywords("Middle Ages, Jet Travel"); $mpdf->Output(); ?>
<?php # THIS ONE DOES NOT HAVE AddPageByArray ANY MORE :-) include("../mpdf.php"); $html_data = file_get_contents("body.html"); $html = substr($html_data, 12, strlen($html_data)-27); $style_data = file_get_contents("style_current.css"); $frontmatter_data = file_get_contents("frontmatter_current.html"); // Create new PDF with font subsetting, 234mm wide, 297mm high $mpdf = new mPDF('s', array(234,297)); // Make it DOUBLE SIDED document with 4mm bleed $mpdf->mirrorMargins = 1; $mpdf->bleedMargin = 4; $mpdf->h2toc = array(); $mpdf->WriteHTML($style_data, 1); $mpdf->WriteHTML($frontmatter_data, 2); $mpdf->WriteHTML($html, 2); $mpdf->SetTitle("An Example Title"); $mpdf->SetAuthor("Aco"); $mpdf->SetCreator("Booktype 2.0 and mPDF 6.0"); $mpdf->SetSubject("History"); $mpdf->SetKeywords("Middle Ages, Jet Travel"); $mpdf->Output(); ?>
Add default report only for travis-ci.
<?php use mageekguy\atoum\reports; $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $travis = getenv('TRAVIS'); if ($travis) { $script->addDefaultReport(); $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName('travis-ci') ->setServiceJobId(getenv('TRAVIS_JOB_ID')) ->addDefaultWriter() ; $runner->addReport($coverallsReport); } }
<?php use mageekguy\atoum\reports; $script->addDefaultReport(); $runner ->addTestsFromDirectory(__DIR__ . '/tests/units/classes') ->disallowUndefinedMethodInInterface() ; $coverallsToken = getenv('COVERALLS_REPO_TOKEN'); if ($coverallsToken) { $coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken); $defaultFinder = $coverallsReport->getBranchFinder(); $coverallsReport ->setBranchFinder(function() use ($defaultFinder) { if (($branch = getenv('TRAVIS_BRANCH')) === false) { $branch = $defaultFinder(); } return $branch; } ) ->setServiceName(getenv('TRAVIS') ? 'travis-ci' : null) ->setServiceJobId(getenv('TRAVIS_JOB_ID') ?: null) ->addDefaultWriter() ; $runner->addReport($coverallsReport); }
Convert TransformLog to ES class.
import { TransformNotLoggedException } from 'orbit/lib/exceptions'; export default class TransformLog { constructor() { this._log = []; } append(transformId) { this._log.push(transformId); } head() { return this._log[this._log.length - 1]; } entries() { return this._log; } length() { return this._log.length; } after(transformId) { const index = this._indexOf(transformId); return this._log.slice(index + 1); } rollback(transformId) { const index = this._indexOf(transformId); return this._log.length = index + 1; } clear() { this._log = []; } isEmpty() { return this._log.length === 0; } contains(transformId) { return this._log.indexOf(transformId) !== -1; } _indexOf(transformId) { const index = this._log.indexOf(transformId); return index !== -1 ? index : this._throwTransformNotLogged(transformId); } _throwTransformNotLogged(transformId) { throw new TransformNotLoggedException(transformId); } }
import { Class } from 'orbit/lib/objects'; import { TransformNotLoggedException } from 'orbit/lib/exceptions'; export default Class.extend({ init() { this._log = []; }, append(transformId) { this._log.push(transformId); }, head() { return this._log[this._log.length - 1]; }, entries() { return this._log; }, length() { return this._log.length; }, after(transformId) { const index = this._indexOf(transformId); return this._log.slice(index + 1); }, rollback(transformId) { const index = this._indexOf(transformId); return this._log.length = index + 1; }, clear() { this._log = []; }, isEmpty() { return this._log.length === 0; }, contains(transformId) { return this._log.indexOf(transformId) !== -1; }, _indexOf(transformId) { const index = this._log.indexOf(transformId); return index !== -1 ? index : this._throwTransformNotLogged(transformId); }, _throwTransformNotLogged(transformId) { throw new TransformNotLoggedException(transformId); } });
Fix hardwired redirect to analytics options page
<?php class Analytics_Options_Serializer { public function init() { add_action( 'admin_post_analytics_options', array( $this, 'save' ) ); } public static function save() { $option_name = 'analytics'; if ( empty( $_POST['id'] ) || empty( $_POST['vendor-type'] ) || empty( $_POST['config'] ) ) { return; } $new_analytics_options = array( $_POST['id'], $_POST['vendor-type'], stripslashes($_POST['config']) ); $inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id']; $analytics_options = get_option($option_name); if ( ! $analytics_options ) { $analytics_options = array(); } if ( isset($_POST['delete']) ) { unset($analytics_options[$inner_option_name]); } else { $analytics_options[$inner_option_name] = $new_analytics_options; } update_option( $option_name, $analytics_options, false); // [Redirect] Keep the user in the analytics options page header('Location: ' . admin_url('admin.php?page=amp-analytics-options')); } }
<?php class Analytics_Options_Serializer { public function init() { add_action( 'admin_post_analytics_options', array( $this, 'save' ) ); } public static function save() { $option_name = 'analytics'; if ( empty( $_POST['id'] ) || empty( $_POST['vendor-type'] ) || empty( $_POST['config'] ) ) { return; } $new_analytics_options = array( $_POST['id'], $_POST['vendor-type'], stripslashes($_POST['config']) ); $inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id']; $analytics_options = get_option($option_name); if ( ! $analytics_options ) { $analytics_options = array(); } if ( isset($_POST['delete']) ) { unset($analytics_options[$inner_option_name]); } else { $analytics_options[$inner_option_name] = $new_analytics_options; } update_option( $option_name, $analytics_options, false); // TODO(@amedina): change this hardwired redirect to use a variable reference header('Location: http://localhost:8888/amp-wp-plugin-dev/wp-admin/admin.php?page=amp-analytics-options'); } }
Revert ntob check to imperative style As context manager isn't available under Python 2.6
"""Test Python 2/3 compatibility module.""" from __future__ import unicode_literals import unittest import pytest import six from cheroot import _compat as compat class StringTester(unittest.TestCase): """Tests for string conversion.""" @pytest.mark.skipif(six.PY3, reason='Only useful on Python 2') def test_ntob_non_native(self): """ntob should raise an Exception on unicode. (Python 2 only) See #1132 for discussion. """ self.assertRaises(TypeError, compat.ntob, 'fight') class EscapeTester(unittest.TestCase): """Class to test escape_html function from _cpcompat.""" def test_escape_quote(self): """Verify the output for &<>"' chars.""" self.assertEqual("""xx&amp;&lt;&gt;"aa'""", compat.escape_html("""xx&<>"aa'"""))
"""Test Python 2/3 compatibility module.""" from __future__ import unicode_literals import unittest import pytest import six from cheroot import _compat as compat class StringTester(unittest.TestCase): """Tests for string conversion.""" @pytest.mark.skipif(six.PY3, reason='Only useful on Python 2') def test_ntob_non_native(self): """ntob should raise an Exception on unicode. (Python 2 only) See #1132 for discussion. """ with self.assertRaises(TypeError): compat.ntob('fight') class EscapeTester(unittest.TestCase): """Class to test escape_html function from _cpcompat.""" def test_escape_quote(self): """Verify the output for &<>"' chars.""" self.assertEqual("""xx&amp;&lt;&gt;"aa'""", compat.escape_html("""xx&<>"aa'"""))
Add an is_validated key t OrganisationUserSerializer.
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
Rename "[in]valid name" to "[in]valid title"
package seedu.geekeep.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class TitleTest { @Test public void isValidTitle() { // invalid title assertFalse(Title.isValidTitle("")); // empty string assertFalse(Title.isValidTitle(" ")); // spaces only assertFalse(Title.isValidTitle("^")); // only non-alphanumeric characters assertFalse(Title.isValidTitle("peter*")); // contains non-alphanumeric characters // valid title assertTrue(Title.isValidTitle("peter jack")); // alphabets only assertTrue(Title.isValidTitle("12345")); // numbers only assertTrue(Title.isValidTitle("peter the 2nd")); // alphanumeric characters assertTrue(Title.isValidTitle("Capital Tan")); // with capital letters assertTrue(Title.isValidTitle("David Roger Jackson Ray Jr 2nd")); // long names } }
package seedu.geekeep.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class TitleTest { @Test public void isValidTitle() { // invalid name assertFalse(Title.isValidTitle("")); // empty string assertFalse(Title.isValidTitle(" ")); // spaces only assertFalse(Title.isValidTitle("^")); // only non-alphanumeric characters assertFalse(Title.isValidTitle("peter*")); // contains non-alphanumeric characters // valid name assertTrue(Title.isValidTitle("peter jack")); // alphabets only assertTrue(Title.isValidTitle("12345")); // numbers only assertTrue(Title.isValidTitle("peter the 2nd")); // alphanumeric characters assertTrue(Title.isValidTitle("Capital Tan")); // with capital letters assertTrue(Title.isValidTitle("David Roger Jackson Ray Jr 2nd")); // long names } }
Fix ConfigObject to use class instead of class_name. Pass infinite width when dumping to yaml.
import yaml def from_config(config): config = dict(config) # shallow copy return config.pop('class').from_config(config) def from_yaml(yaml_string): config = yaml.load(yaml_string) return from_config(config) class ConfigObject: def get_config(self): return {'class': self.__class__} @classmethod def from_config(cls, config): # TODO pop class? return cls(**config) def to_yaml(self, *args, width=float('inf'), **kwargs): config = self.get_config() return yaml.dump(config, *args, width=width, **kwargs) @classmethod def from_yaml(cls, yaml_string): config = yaml.load(yaml_string) return cls.from_config(config)
import yaml def from_config(config): config = dict(config) # shallow copy return config.pop('class').from_config(config) def from_yaml(yaml_string): config = yaml.load(yaml_string) return from_config(config) class ConfigObject: def get_config(self): return dict(class_name=self.__class__.__name__) @classmethod def from_config(cls, config): # TODO pop class? return cls(**config) def to_yaml(self, *args, **kwargs): config = self.get_config() return yaml.dump(config, *args, **kwargs) @classmethod def from_yaml(cls, yaml_string): config = yaml.load(yaml_string) return cls.from_config(config)
Use name over path for s3 backend support
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.path class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
Make thread pool scheduler behave as a pooled new thread scheduler
from concurrent.futures import ThreadPoolExecutor from rx.core import Scheduler from .newthreadscheduler import NewThreadScheduler class ThreadPoolScheduler(NewThreadScheduler): """A scheduler that schedules work via the thread pool.""" class ThreadPoolThread: """Wraps a concurrent future as a thread.""" def __init__(self, executor, run): self.run = run self.future = None self.executor = executor def start(self): self.future = self.executor.submit(self.run) def cancel(self): self.future.cancel() def __init__(self, max_workers=None): super(ThreadPoolScheduler, self).__init__(self.thread_factory) self.executor = ThreadPoolExecutor(max_workers=max_workers) def thread_factory(self, target, *args): return self.ThreadPoolThread(self.executor, target) Scheduler.thread_pool = thread_pool_scheduler = ThreadPoolScheduler()
import logging from concurrent.futures import ThreadPoolExecutor from rx.core import Scheduler, Disposable from rx.disposables import SingleAssignmentDisposable, CompositeDisposable from .timeoutscheduler import TimeoutScheduler log = logging.getLogger("Rx") class ThreadPoolScheduler(TimeoutScheduler): """A scheduler that schedules work via the thread pool and threading timers.""" def __init__(self, max_workers=None): self.executor = ThreadPoolExecutor(max_workers=max_workers) def schedule(self, action, state=None): """Schedules an action to be executed.""" disposable = SingleAssignmentDisposable() def run(): disposable.disposable = self.invoke_action(action, state) future = self.executor.submit(run) def dispose(): future.cancel() return CompositeDisposable(disposable, Disposable.create(dispose)) Scheduler.thread_pool = thread_pool_scheduler = ThreadPoolScheduler()
Fix intermittent failure in l10n language selector test
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(base_url, selenium): page = HomePage(base_url, selenium).open() initial = page.footer.language # avoid selecting the same language or locales that have homepage redirects excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN'] available = [l for l in page.footer.languages if l not in excluded] new = random.choice(available) page.footer.select_language(new) assert '/{0}/'.format(new) in selenium.current_url, 'Language is not in URL' assert new == page.footer.language, 'Language has not been selected'
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(base_url, selenium): page = HomePage(base_url, selenium).open() initial = page.footer.language # avoid selecting the same language or locales that have homepage redirects excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN'] available = [l for l in page.footer.languages if l not in excluded] new = random.choice(available) page.footer.select_language(new) assert new in selenium.current_url, 'Language is not in URL' assert new == page.footer.language, 'Language has not been selected'
Fix an error in the clean task
var del = require('del'); var gulp = require('gulp'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var $ = require('gulp-load-plugins')(); var config = require('./webpack.config.js'); gulp.task('js', function (cb) { webpack(config, function (err, stats) { if(err) throw new gutil.PluginError("webpack", err); $.util.log("[webpack]", stats.toString({ colors: true })); cb(); }); }); gulp.task('html', function () { gulp.src('./src/*.html') .pipe(gulp.dest('./build')); }); gulp.task('css', function () { gulp.src('./src/css/*.css') .pipe(gulp.dest('./build/css')); }); gulp.task('clean', function (cb) { del(['build']).then(function () { cb() }); }); gulp.task('build', ['html', 'css', 'js']); gulp.task('dev', ['html', 'css'], function () { // Start a webpack-dev-server var compiler = webpack(config); new WebpackDevServer(compiler, { // server and middleware options }).listen(8080, "localhost", function(err) { if(err) throw new gutil.PluginError("webpack-dev-server", err); // Server listening $.util.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html"); }); });
var del = require('del'); var gulp = require('gulp'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var $ = require('gulp-load-plugins')(); var config = require('./webpack.config.js'); gulp.task('js', function (cb) { webpack(config, function (err, stats) { if(err) throw new gutil.PluginError("webpack", err); $.util.log("[webpack]", stats.toString({ colors: true })); cb(); }); }); gulp.task('html', function () { gulp.src('./src/*.html') .pipe(gulp.dest('./build')); }); gulp.task('css', function () { gulp.src('./src/css/*.css') .pipe(gulp.dest('./build/css')); }); gulp.task('clean', function (cb) { del(['build']).then(cb); }); gulp.task('build', ['html', 'css', 'js']); gulp.task('dev', ['html', 'css'], function () { // Start a webpack-dev-server var compiler = webpack(config); new WebpackDevServer(compiler, { // server and middleware options }).listen(8080, "localhost", function(err) { if(err) throw new gutil.PluginError("webpack-dev-server", err); // Server listening $.util.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html"); }); });
chore: Add browserstack capabilities to webdriver config
import { Builder, Key } from 'selenium-webdriver'; export const driver = new Builder() .forBrowser('chrome') .withCapabilities({ 'browserstack.local': true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER || process.env.TRAVIS_JOB_NUMBER }) .usingServer('http://localhost:4444/wd/hub') .build(); export const isMac = async () => { const capabilities = await driver.getCapabilities(); const os = capabilities.get('platform'); return os.toUpperCase().indexOf('MAC') >= 0; }; export const isChrome = async () => { const capabilities = await driver.getCapabilities(); const browser = capabilities.get('browserName'); return browser.toUpperCase().indexOf('CHROME') >= 0; } export const getModifierKey = async () => { const mac = await isMac(); return mac ? Key.COMMAND : Key.CONTROL; } afterAll(async () => { // Cleanup `process.on('exit')` event handlers to prevent a memory leak caused by the combination of `jest` & `tmp`. for (const listener of process.listeners('exit')) { listener(); process.removeListener('exit', listener); } await driver.quit(); }); export const defaultTimeout = 10e3;
import { Builder, Key } from 'selenium-webdriver'; export const driver = new Builder() .forBrowser('chrome') .usingServer('http://localhost:4444/wd/hub') .build(); export const isMac = async () => { const capabilities = await driver.getCapabilities(); const os = capabilities.get('platform'); return os.toUpperCase().indexOf('MAC') >= 0; }; export const isChrome = async () => { const capabilities = await driver.getCapabilities(); const browser = capabilities.get('browserName'); return browser.toUpperCase().indexOf('CHROME') >= 0; } export const getModifierKey = async () => { const mac = await isMac(); return mac ? Key.COMMAND : Key.CONTROL; } afterAll(async () => { // Cleanup `process.on('exit')` event handlers to prevent a memory leak caused by the combination of `jest` & `tmp`. for (const listener of process.listeners('exit')) { listener(); process.removeListener('exit', listener); } await driver.quit(); }); export const defaultTimeout = 10e3;
Update testmod to use the new method
package info.u_team.u_team_test; import org.apache.logging.log4j.*; import info.u_team.u_team_core.construct.ConstructManager; import info.u_team.u_team_core.integration.IntegrationManager; import info.u_team.u_team_core.util.annotation.AnnotationManager; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.fml.common.Mod; @Mod(TestMod.MODID) public class TestMod { public static final String MODID = "uteamtest"; public static final Logger LOGGER = LogManager.getLogger("UTeamTest"); public TestMod() { JarSignVerifier.checkSigned(MODID); LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------"); // TestCommonBusRegister.register(); // DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register); AnnotationManager.callAnnotations(MODID); } }
package info.u_team.u_team_test; import org.apache.logging.log4j.*; import info.u_team.u_team_core.construct.ConstructManager; import info.u_team.u_team_core.integration.IntegrationManager; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.fml.common.Mod; @Mod(TestMod.MODID) public class TestMod { public static final String MODID = "uteamtest"; public static final Logger LOGGER = LogManager.getLogger("UTeamTest"); public TestMod() { JarSignVerifier.checkSigned(MODID); LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------"); // TestCommonBusRegister.register(); // DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register); ConstructManager.constructConstructs(MODID); IntegrationManager.constructIntegrations(MODID); } }
Update template for RoboVM 0.0.11
package {{package}}; import clojure.lang.RT; import clojure.lang.Symbol; import com.badlogic.gdx.*; import com.badlogic.gdx.backends.iosrobovm.*; import org.robovm.apple.foundation.*; import org.robovm.apple.uikit.*; public class {{ios-class-name}} extends IOSApplication.Delegate { protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); RT.var("clojure.core", "require").invoke(Symbol.intern("{{namespace}}")); try { Game game = (Game) RT.var("{{namespace}}", "{{app-name}}").deref(); return new IOSApplication(game, config); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, {{ios-class-name}}.class); pool.close(); } }
package {{package}}; import clojure.lang.RT; import clojure.lang.Symbol; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import com.badlogic.gdx.Game; import org.robovm.cocoatouch.foundation.NSAutoreleasePool; import org.robovm.cocoatouch.uikit.UIApplication; public class {{ios-class-name}} extends IOSApplication.Delegate { protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); RT.var("clojure.core", "require").invoke(Symbol.intern("{{namespace}}")); try { Game game = (Game) RT.var("{{namespace}}", "{{app-name}}").deref(); return new IOSApplication(game, config); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, {{ios-class-name}}.class); pool.drain(); } }
Remove file extension (dynamically) from indexed list of files and their contents
'use strict'; var fs = require('fs'); /* * read *.txt files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { textFiles[files[file] .slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
'use strict'; var fs = require('fs'); /* * read *.txt files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { textFiles[files[file]] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
Add routing exception for docs
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
Watch also *.scss sources for rebuild
module.exports = function(gulp, config) { return function(done) { var c = require('better-console') c.info('watch sources') var path = require('path') var glob = [ '**/*.{css,styl,scss,js,jsx,coffee,jade}', '!' + config.dist_folder + '/**/*' ] var options = { base: path.resolve(config.dir, config.src_folder), read: false } var changeHandler = function(file) { c.log('- handling change', path.relative(config.dir, file.path)) var ext = path.extname(file.path) switch(ext) { case '.css': case '.styl': case '.scss': return gulp.start('styles') case '.js': case '.jsx': case '.coffee': return gulp.start('scripts') case '.jade': return gulp.start('templates') default: return c.log('! unknown extension', ext) } } return gulp.watch(glob, options, changeHandler) } }
module.exports = function(gulp, config) { return function(done) { var c = require('better-console') c.info('watch sources') var path = require('path') var glob = [ '**/*.{css,styl,js,jsx,coffee,jade}', '!' + config.dist_folder + '/**/*' ] var options = { base: path.resolve(config.dir, config.src_folder), read: false } var changeHandler = function(file) { c.log('- handling change', path.relative(config.dir, file.path)) var ext = path.extname(file.path) switch(ext) { case '.css': case '.styl': return gulp.start('styles') case '.js': case '.jsx': case '.coffee': return gulp.start('scripts') case '.jade': return gulp.start('templates') default: return c.log('! unknown extension', ext) } } return gulp.watch(glob, options, changeHandler) } }
Test should only use a single root git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1704735 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.webresources; import java.io.File; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.WebResourceSet; public class TestDirResourceSetInternal extends TestDirResourceSet { @Override public WebResourceRoot getWebResourceRoot() { File f = new File("test/"); TesterWebResourceRoot root = new TesterWebResourceRoot(); WebResourceSet webResourceSet = new DirResourceSet(root, "/", f.getAbsolutePath(), "/webresources/dir1"); root.setMainResources(webResourceSet); return root; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.webresources; import java.io.File; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.WebResourceSet; public class TestDirResourceSetInternal extends TestDirResourceSet { @Override public WebResourceRoot getWebResourceRoot() { File f = new File("test/"); TesterWebResourceRoot root = new TesterWebResourceRoot(); WebResourceSet webResourceSet = new DirResourceSet(new TesterWebResourceRoot(), "/", f.getAbsolutePath(), "/webresources/dir1"); root.setMainResources(webResourceSet); return root; } }
Move manual project ID dropdown to Bootstrap styles
import React, { Component } from 'react'; export default class AddProject extends Component { constructor() { super(); this.state = { projectId: '', }; this.submit = this.submit.bind(this); } submit(e) { e.preventDefault(); this.props.onAdd(this.state.projectId); } render() { return ( <form onSubmit={this.submit}> <div><label htmlFor="projectId">Project ID</label></div> <div className="input-group input-group-sm"> <input id="projectId" onChange={e => this.setState({ projectId: e.target.value })} type="number" value={this.state.projectId} className="form-control" /> <div className="input-group-btn"> <button type="submit" className="btn btn-primary">Add</button> </div> </div> </form> ); } }
import React, { Component } from 'react'; export default class AddProject extends Component { constructor() { super(); this.state = { projectId: '', }; this.submit = this.submit.bind(this); } submit(e) { e.preventDefault(); this.props.onAdd(this.state.projectId); } render() { return ( <form onSubmit={this.submit}> <div><label htmlFor="projectId">Project ID</label></div> <input id="projectId" onChange={e => this.setState({ projectId: e.target.value })} type="number" value={this.state.projectId} /> <button type="submit">Add</button> </form> ); } }
Change components to bower_components for bower 1.0.0 References #1
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'bower_components/underscore/underscore.js', 'bower_components/jquery/jquery.js', 'src/*.coffee', 'src/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.coffee' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress || growl reporters = ['progress']; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['PhantomJS']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 10000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
// Karma configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'components/underscore/underscore.js', 'components/jquery/jquery.js', 'src/*.coffee', 'src/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.coffee' ]; // list of files to exclude exclude = []; // test results reporter to use // possible values: dots || progress || growl reporters = ['progress']; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers = ['PhantomJS']; // If browser does not capture in given timeout [ms], kill it captureTimeout = 10000; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
Fix create table syntax error.
package org.zeropage.apps.zeropage.database.notification; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class NotificationOpenHelper extends SQLiteOpenHelper { private static final int VERSION = 1; private static final String DATABASE_NAME = "notification.db"; NotificationOpenHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + NotificationTable.NAME + "(" + " _id integer primary key autoincrement, " + NotificationTable.Column.DATE + ", " + NotificationTable.Column.TITLE + ", " + NotificationTable.Column.BODY + ")" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
package org.zeropage.apps.zeropage.database.notification; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class NotificationOpenHelper extends SQLiteOpenHelper { private static final int VERSION = 1; private static final String DATABASE_NAME = "notification.db"; NotificationOpenHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + NotificationTable.NAME + "(" + " _id integer primary key autoincrement, " + NotificationTable.Column.DATE + ", " + NotificationTable.Column.TITLE + ", " + NotificationTable.Column.BODY + ", " + ")" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Make Cloud Spanner transaction id public. Allows to build non-library transforms that run in the same transaction with library ones. Change-Id: Ibf4edd56aec791f7baca8f7e0b79bd0d4ba7a10f
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.gcp.spanner; import com.google.auto.value.AutoValue; import com.google.cloud.spanner.BatchTransactionId; import java.io.Serializable; import javax.annotation.Nullable; /** A transaction object. */ @AutoValue public abstract class Transaction implements Serializable { @Nullable public abstract BatchTransactionId transactionId(); public static Transaction create(BatchTransactionId txId) { return new AutoValue_Transaction(txId); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.gcp.spanner; import com.google.auto.value.AutoValue; import com.google.cloud.spanner.BatchTransactionId; import java.io.Serializable; import javax.annotation.Nullable; /** A transaction object. */ @AutoValue public abstract class Transaction implements Serializable { @Nullable abstract BatchTransactionId transactionId(); public static Transaction create(BatchTransactionId txId) { return new AutoValue_Transaction(txId); } }
Remove visibilities from interface methods.
/* * Copyright 2016, Frederik Boster * * 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 de.syquel.bushytail.controller; import org.apache.olingo.server.api.uri.UriParameter; import java.util.List; /** * Interface for all ODataControllers. Provides CRUD Operations. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 * * @param <T> Entity which is handled by the controller. */ public interface IBushyTailController<T> { T read(List<UriParameter> keyPredicates); T create(T entity); }
/* * Copyright 2016, Frederik Boster * * 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 de.syquel.bushytail.controller; import org.apache.olingo.server.api.uri.UriParameter; import java.util.List; /** * Interface for all ODataControllers. Provides CRUD Operations. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 * * @param <T> Entity which is handled by the controller. */ public interface IBushyTailController<T> { public T read(List<UriParameter> keyPredicates); public T create(T entity); }
Disable contracts in jobs parser
# coding: utf-8 import urllib from celery import shared_task from apps.vacancies.parsers import VacancySync, YandexRabotaParser @shared_task(ignore_result=True) def update_vacancies(): fulltime = { 'rid': 213, 'currency': 'RUR', 'text': 'python программист', 'strict': 'false', 'employment': 'FULL_EMPLOYMENT' } part_time = fulltime.copy() part_time['employment'] = 'TEMPORARY_EMPLOYMENT' syncer = VacancySync(parsers=[ YandexRabotaParser(urllib.parse.urlencode(fulltime), type='fulltime'), # Contract feed is broken as of 13 july (shows same data as fulltime) # YandexRabotaParser(urllib.parse.urlencode(part_time), type='contract') ]) return syncer.sync()
# coding: utf-8 import urllib from celery import shared_task from apps.vacancies.parsers import VacancySync, YandexRabotaParser @shared_task(ignore_result=True) def update_vacancies(): fulltime = { 'rid': 213, 'currency': 'RUR', 'text': 'python программист', 'strict': 'false', 'employment': 'FULL_EMPLOYMENT' } part_time = fulltime.copy() part_time['employment'] = 'TEMPORARY_EMPLOYMENT' syncer = VacancySync(parsers=[ YandexRabotaParser(urllib.parse.urlencode(fulltime), type='fulltime'), YandexRabotaParser(urllib.parse.urlencode(part_time), type='contract') ]) return syncer.sync()
Update creator type modal copy
import React from 'react' import CreatorTypeContainer from '../../containers/CreatorTypeContainer' import * as s from '../../styles/jso' import { css, media } from '../../styles/jss' const creatorTypeModalStyle = css( s.bgcWhite, s.fullWidth, s.mxAuto, s.p10, { borderRadius: 5, maxWidth: 510 }, media(s.minBreak2, s.p20), ) const titleStyle = css( s.colorBlack, s.fontSize14, { marginRight: 60, marginBottom: 40 }, ) export default () => ( <div className={creatorTypeModalStyle}> <h3 className={titleStyle}>We&apos;re doing a quick survey to find out a little more about the artistic composition of the Ello Community. You can always update your selection(s) on your settings page. Thank you!</h3> <CreatorTypeContainer /> </div> )
import React from 'react' import CreatorTypeContainer from '../../containers/CreatorTypeContainer' import * as s from '../../styles/jso' import { css, media } from '../../styles/jss' const creatorTypeModalStyle = css( s.bgcWhite, s.fullWidth, s.mxAuto, s.p10, { borderRadius: 5, maxWidth: 510 }, media(s.minBreak2, s.p20), ) const titleStyle = css( s.colorBlack, s.fontSize14, { marginRight: 60, marginBottom: 40 }, ) export default () => ( <div className={creatorTypeModalStyle}> <h3 className={titleStyle}>We&apos;re doing a quick survey to find out a little more about the artistic composition of the Ello Community. You can always update your answers on your settings page. Thank you!</h3> <CreatorTypeContainer /> </div> )
Change forEach to lodash each functions
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); _.each(filenames, function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it('should markup ' + testName, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.should.equal(expected); done(); }); }); }); }); } describe('markup generation test', function() { var languages = fs.readdirSync(utility.buildPath('markup')); _.each(languages, testLanguage, this); });
'use strict'; var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); filenames.forEach(function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it('should markup ' + testName, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.should.equal(expected); done(); }); }); }); }); } describe('markup generation test', function() { var languages = fs.readdirSync(utility.buildPath('markup')); languages.forEach(testLanguage); });
Fix crash (change Power type to double)
package io.github.aquerr.eaglefactions.entities; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.world.Chunk; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by Aquerr on 2017-07-13. */ public class Faction { public String Name; public double Power; public List<String> Members; public List<String> Alliances; public List<String> Enemies; public UUID Leader; public List<String> Officers; public List<Chunk> Claims; public Faction(String factionName, UUID factionLeader) { this.Name = factionName; this.Leader = factionLeader; this.Power = 0; this.Members = new ArrayList<>(); this.Claims = new ArrayList<>(); this.Officers = new ArrayList<>(); this.Alliances = new ArrayList<>(); this.Enemies = new ArrayList<>(); } }
package io.github.aquerr.eaglefactions.entities; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.world.Chunk; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by Aquerr on 2017-07-13. */ public class Faction { public String Name; public int Power; public List<String> Members; public List<String> Alliances; public List<String> Enemies; public UUID Leader; public List<String> Officers; public List<Chunk> Claims; public Faction(String factionName, UUID factionLeader) { this.Name = factionName; this.Leader = factionLeader; this.Power = 0; this.Members = new ArrayList<>(); this.Claims = new ArrayList<>(); this.Officers = new ArrayList<>(); this.Alliances = new ArrayList<>(); this.Enemies = new ArrayList<>(); } }
Select chosen stylesheet on load
/* * style-select.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js * * Changes the stylesheet chooser links to a <select> * * Released under the MIT license * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/style-select.js'; * */ onready(function(){ var stylesDiv = $('div.styles'); var stylesSelect = $('<select></select>'); var i = 1; stylesDiv.children().each(function() { var opt = $('<option></option>') .text(this.innerText.replace(/(^\[|\]$)/g, '')) .val(i); if ($(this).hasClass('selected')) opt.attr('selected', true); stylesSelect.append(opt); $(this).attr('id', 'style-select-' + i); i++; }); stylesSelect.change(function() { $('#style-select-' + $(this).val()).click(); }); stylesDiv.hide(); stylesDiv.after( $('<div style="float:right;margin-bottom:10px"></div>') .text(_('Style: ')) .append(stylesSelect) ); });
/* * style-select.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js * * Changes the stylesheet chooser links to a <select> * * Released under the MIT license * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/style-select.js'; * */ onready(function(){ var stylesDiv = $('div.styles'); var stylesSelect = $('<select></select>'); var i = 1; stylesDiv.children().each(function() { stylesSelect.append( $('<option></option>') .text(this.innerText.replace(/(^\[|\]$)/g, '')) .val(i) ); $(this).attr('id', 'style-select-' + i); i++; }); stylesSelect.change(function() { $('#style-select-' + $(this).val()).click(); }); stylesDiv.hide(); stylesDiv.after( $('<div style="float:right;margin-bottom:10px"></div>') .text(_('Style: ')) .append(stylesSelect) ); });
Change method name to be more explicit
$(function() { var $tabs = $('#search-results-tabs'), $searchForm = $('.js-search-hash'); if($tabs.length > 0){ $tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true }); } function getDefaultSearchTabIndex(){ var tabIds = $('.nav-tabs a').map(function(i, el){ return $(el).attr('href').split('#').pop(); }), $defaultTab = $('input[name=tab]'), selectedTab = $.inArray($defaultTab.val(), tabIds); return selectedTab > -1 ? selectedTab : 0; } if($searchForm.length){ $tabs.on('tabChanged', updateSearchForm); } function updateSearchForm(e, hash){ if(typeof hash !== 'undefined'){ var $defaultTab = $('input[name=tab]'); if($defaultTab.length === 0){ $defaultTab = $('<input type="hidden" name="tab">'); $searchForm.prepend($defaultTab); } $defaultTab.val(hash); } } });
$(function() { var $tabs = $('#search-results-tabs'), $searchForm = $('.js-search-hash'); if($tabs.length > 0){ $tabs.tabs({ 'defaultTab' : getDefaultSearchTab(), scrollOnload: true }); } function getDefaultSearchTab(){ var tabIds = $('.nav-tabs a').map(function(i, el){ return $(el).attr('href').split('#').pop(); }), $defaultTab = $('input[name=tab]'), selectedTab = $.inArray($defaultTab.val(), tabIds); return selectedTab > -1 ? selectedTab : 0; } if($searchForm.length){ $tabs.on('tabChanged', updateSearchForm); } function updateSearchForm(e, hash){ if(typeof hash !== 'undefined'){ var $defaultTab = $('input[name=tab]'); if($defaultTab.length === 0){ $defaultTab = $('<input type="hidden" name="tab">'); $searchForm.prepend($defaultTab); } $defaultTab.val(hash); } } });
Add forced alias in config
<?php /** * HiDev plugin for license generation. * * @link https://github.com/hiqdev/hidev-license * @package hidev-license * @license BSD-3-Clause * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/) */ return [ 'controllerMap' => [ 'LICENSE' => [ 'class' => \hidev\license\console\LicenseController::class, ], ], 'components' => [ 'license' => [ 'class' => \hidev\license\components\License::class, ], 'view' => [ 'theme' => [ 'pathMap' => [ '@hidev/views' => ['@hidev/license/views'], ], ], ], ], 'aliases' => [ '@hidev/license' => dirname(__DIR__) . '/src', ], ];
<?php /** * HiDev plugin for license generation. * * @link https://github.com/hiqdev/hidev-license * @package hidev-license * @license BSD-3-Clause * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/) */ return [ 'controllerMap' => [ 'LICENSE' => [ 'class' => \hidev\license\console\LicenseController::class, ], ], 'components' => [ 'license' => [ 'class' => \hidev\license\components\License::class, ], 'view' => [ 'theme' => [ 'pathMap' => [ '@hidev/views' => ['@hidev/license/views'], ], ], ], ], ];
Rename promise to resolver, which is what it is anyway
/** * @license Copyright (c) 2010-2011 Brian Cavalier * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject * to the MIT License at: http://www.opensource.org/licenses/mit-license.php. */ /** * sizzle.js * Adds querySelectorAll functionality to wire using John Resig's Sizzle library. * Sizzle must be wrapped in an AMD define(). Kris Zyp has a version of this at * http://github.com/kriszyp/sizzle * * @author John Hann (@unscriptable) */ define(['sizzle', 'wire/domReady'], function(sizzle, domReady) { function resolveQuery(resolver, name, refObj /*, wire */) { domReady(function() { var result = sizzle(name); resolver.resolve(typeof refObj.i == 'number' && refObj.i < result.length ? result[refObj.i] : result); }); } /** * The plugin instance. Can be the same for all wiring runs */ var plugin = { resolvers: { 'dom.query': resolveQuery } }; return { wire$plugin: function(/*ready, destroyed, options*/) { return plugin; } }; });
/** * @license Copyright (c) 2010-2011 Brian Cavalier * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject * to the MIT License at: http://www.opensource.org/licenses/mit-license.php. */ /** * sizzle.js * Adds querySelectorAll functionality to wire using John Resig's Sizzle library. * Sizzle must be wrapped in an AMD define(). Kris Zyp has a version of this at * http://github.com/kriszyp/sizzle * * @author John Hann (@unscriptable) */ define(['sizzle', 'wire/domReady'], function(sizzle, domReady) { function resolveQuery(promise, name, refObj /*, wire */) { domReady(function() { var result = sizzle(name); promise.resolve(typeof refObj.i == 'number' && refObj.i < result.length ? result[refObj.i] : result); }); } /** * The plugin instance. Can be the same for all wiring runs */ var plugin = { resolvers: { 'dom.query': resolveQuery } }; return { wire$plugin: function(/*ready, destroyed, options*/) { return plugin; } }; });
Fix an issue - Edit excel data set page is using flat file's help document[60395].
/******************************************************************************* * Copyright (c) 2012 Megha Nidhi Dahal. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Megha Nidhi Dahal - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.birt.report.data.oda.excel.ui.util; public interface IHelpConstants { public static final String PREFIX = "org.eclipse.datatools.oda.cshelp" + "."; //$NON-NLS-1$ //$NON-NLS-2$ public static final String CONEXT_ID_DATASOURCE_EXCEL = PREFIX + "Wizard_ExcelDatasource_ID";//$NON-NLS-1$ public static final String CONEXT_ID_DATASET_EXCEL = PREFIX + "Dialog_SelectExcelColumn_ID";//$NON-NLS-1$ }
/******************************************************************************* * Copyright (c) 2012 Megha Nidhi Dahal. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Megha Nidhi Dahal - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.birt.report.data.oda.excel.ui.util; public interface IHelpConstants { public static final String PREFIX = "org.eclipse.datatools.oda.cshelp" + "."; //$NON-NLS-1$ //$NON-NLS-2$ public static final String CONEXT_ID_DATASOURCE_EXCEL = PREFIX + "Wizard_ExcelDatasource_ID";//$NON-NLS-1$ public static final String CONEXT_ID_DATASET_EXCEL = PREFIX + "Dialog_SelectTableColumn_ID";//$NON-NLS-1$ }
Add router navigation Externalise main component to a separate file
let React = require('react-native'); let FreshSetup = require('./src/FreshSetup'); let { AppRegistry, NavigatorIOS, StatusBarIOS, StyleSheet, } = React; class Meowth extends React.Component { componentWillMount() { StatusBarIOS.setStyle('light-content'); } render() { return ( <NavigatorIOS style={styles.container} initialRoute={{ component: FreshSetup, title: 'Welcome', backButtonTitle: 'Back', passProps: { pageId: 'welcome', } }} barTintColor="#084265" tintColor="#ffffff" titleTextColor="#ffffff" /> ); } } var styles = StyleSheet.create({ container: { flex: 1, }, }); AppRegistry.registerComponent('meowth', () => Meowth);
let React = require('react-native'); let { AppRegistry, StyleSheet, Text, View, StatusBarIOS } = React; class Meowth extends React.Component { componentWillMount() { StatusBarIOS.setStyle('light-content'); } render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to Meowth </Text> <Text style={styles.instructions}> Subtitle </Text> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#084265', }, welcome: { color: '#F5FCFF', fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#CCCCCC', marginBottom: 5, }, }); AppRegistry.registerComponent('meowth', () => Meowth);
Rename odometer to one word
/** * */ package org.traccar; import org.traccar.helper.DistanceCalculator; import org.traccar.helper.Log; import org.traccar.model.Position; /** * <p> * Odometer handler * </p> * * @author Amila Silva * */ public class ODOMeterHandler extends BaseDataHandler { public ODOMeterHandler() { Log.debug("System based odometer calculation enabled for all devices"); } private Position getLastPosition(long deviceId) { if (Context.getConnectionManager() != null) { return Context.getConnectionManager().getLastPosition(deviceId); } return null; } private Position calculateDistance(Position position) { Position last = getLastPosition(position.getDeviceId()); if (last != null) { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; double odoMeter = distance + last.getOdoMeter(); // Log.debug("::: Device Course : " + position.getDeviceId() // + ", Distance :" + distance + "m, Odometer :" + odoMeter // + " m"); position.setOdoMeter(odoMeter); } return position; } @Override protected Position handlePosition(Position position) { return calculateDistance(position); } }
/** * */ package org.traccar; import org.traccar.helper.DistanceCalculator; import org.traccar.helper.Log; import org.traccar.model.Position; /** * <p> * ODO Meter handler * </p> * * @author Amila Silva * */ public class ODOMeterHandler extends BaseDataHandler { public ODOMeterHandler() { Log.debug("System based ODO meter calculation enabled for all devices"); } private Position getLastPosition(long deviceId) { if (Context.getConnectionManager() != null) { return Context.getConnectionManager().getLastPosition(deviceId); } return null; } private Position calculateDistance(Position position) { Position last = getLastPosition(position.getDeviceId()); if (last != null) { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; double odoMeter = distance + last.getOdoMeter(); // Log.debug("::: Device Course : " + position.getDeviceId() // + ", Distance :" + distance + "m, Odometer :" + odoMeter // + " m"); position.setOdoMeter(odoMeter); } return position; } @Override protected Position handlePosition(Position position) { return calculateDistance(position); } }
Use boost 1.71.0 for conan https://github.com/conan-io/conan-center-index/issues/214#issuecomment-564074114
from conans import ConanFile, CMake from conans.tools import load import re def get_version(): try: content = load("CMakeLists.txt") version = re.search(r"^\s*project\(resource_pool\s+VERSION\s+([^\s]+)", content, re.M).group(1) return version.strip() except Exception: return None class ResourcePool(ConanFile): name = 'resource_pool' version = get_version() license = 'MIT' url = 'https://github.com/elsid/resource_pool' description = 'Conan package for elsid resource pool' exports_sources = 'include/*', 'CMakeLists.txt', 'resource_poolConfig.cmake', 'LICENCE', 'AUTHORS' generators = 'cmake_paths' requires = 'boost/1.71.0@conan/stable' def _configure_cmake(self): cmake = CMake(self) cmake.configure() return cmake def build(self): cmake = self._configure_cmake() cmake.build() def package(self): cmake = self._configure_cmake() cmake.install() def package_id(self): self.info.header_only() def package_info(self): self.cpp_info.libs = ['resource_pool']
from conans import ConanFile, CMake from conans.tools import load import re def get_version(): try: content = load("CMakeLists.txt") version = re.search(r"^\s*project\(resource_pool\s+VERSION\s+([^\s]+)", content, re.M).group(1) return version.strip() except Exception: return None class ResourcePool(ConanFile): name = 'resource_pool' version = get_version() license = 'MIT' url = 'https://github.com/elsid/resource_pool' description = 'Conan package for elsid resource pool' exports_sources = 'include/*', 'CMakeLists.txt', 'resource_poolConfig.cmake', 'LICENCE', 'AUTHORS' generators = 'cmake_paths' requires = 'boost/1.70.0@conan/stable' def _configure_cmake(self): cmake = CMake(self) cmake.configure() return cmake def build(self): cmake = self._configure_cmake() cmake.build() def package(self): cmake = self._configure_cmake() cmake.install() def package_id(self): self.info.header_only() def package_info(self): self.cpp_info.libs = ['resource_pool']
Fix docs on test name truncation
'use strict'; var path = require('path'); var fs = require('fs'); var MAX_NAME_LENGTH = 40; function uniqueFile(file) { var testPath = file; var counter = null; while (fs.existsSync(testPath + '.png')) { counter = (counter || 0) + 1; testPath = file + counter; } return testPath + '.png'; } function getFile(directory, title) { var name = title // 1. Replace all special characters with `_` .replace(/[^\w]/g, '_') // 2. Collapse consecutive underscores .replace(/_{2,}/g, '_') // 3. Apply character limit so filenames don't get out of hand .substr(0, MAX_NAME_LENGTH); var filePath = path.join(directory, name); return uniqueFile(filePath); } function writeFile(directory, title, data, encoding) { var filename = getFile(directory, title); fs.writeFileSync(filename, data, encoding || 'base64'); return filename; } module.exports = writeFile;
'use strict'; var path = require('path'); var fs = require('fs'); function uniqueFile(file) { var testPath = file; var counter = null; while (fs.existsSync(testPath + '.png')) { counter = (counter || 0) + 1; testPath = file + counter; } return testPath + '.png'; } function getFile(directory, title) { // Take the test title and remove all special characters; limit to 20 characters var name = title.replace(/[^\w]/g, '_').replace(/_{2,}/g, '_').substr(0, 40); var filePath = path.join(directory, name); return uniqueFile(filePath); } function writeFile(directory, title, data, encoding) { var filename = getFile(directory, title); fs.writeFileSync(filename, data, encoding || 'base64'); return filename; } module.exports = writeFile;
Fix GTFS trip ordering (api)
const db = require('../db.js'); const cache = require('../utils/cache.js'); async function getTrips(id, coachOnly) { return await cache.use('mnt-trips', id, () => db.query(` SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.type, FALSE AS live, 'mnt' AS provider FROM stops AS stop JOIN stop_times ON stop_id = id JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id JOIN services AS service ON service.id = trip.service_id WHERE stop.id = ? AND route.type IS NOT NULL AND time > CURTIME() AND ( ( CURDATE() BETWEEN start AND end AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = 1 AND service_id NOT IN ( SELECT service_id FROM service_exceptions WHERE type = 0 AND date = CURDATE() ) ) OR service_id IN ( SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE() ) ) ${coachOnly ? "AND route.type LIKE 'coach%'" : ''} ORDER BY time LIMIT ${coachOnly ? '5' : '15'} `, [ id ])); } module.exports = { getTrips };
const db = require('../db.js'); const cache = require('../utils/cache.js'); async function getTrips(id, coachOnly) { return await cache.use('mnt-trips', id, () => db.query(` SELECT TIME_TO_SEC(time) AS time, TIME_TO_SEC(time) - TIME_TO_SEC(NOW()) as countdown, route.name, trip.destination, route.type, FALSE AS live, 'mnt' AS provider FROM stops AS stop JOIN stop_times ON stop_id = id JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id JOIN services AS service ON service.id = trip.service_id WHERE stop.id = ? AND route.type IS NOT NULL AND time > CURTIME() AND ( ( CURDATE() BETWEEN start AND end AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = 1 AND service_id NOT IN ( SELECT service_id FROM service_exceptions WHERE type = 0 AND date = CURDATE() ) ) OR service_id IN ( SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE() ) ) ${coachOnly ? "AND route.type LIKE 'coach%'" : ''} LIMIT ${coachOnly ? '5' : '15'} `, [ id ])); } module.exports = { getTrips };
Fix eslint & jscs errors (ignore generated files in test folders)
'use strict'; const gulp = require('gulp'); const tools = require('./src'); const globalSourceFiles = require('./src/utils/global-source-files'); const unmockedModulePathPatterns = [ 'node_modules/.*', 'utils/helper-tests.js' ]; tools.setGlobalConfiguration({ sourceFiles: globalSourceFiles.concat('!**/dist/**') }); tools.initialize(gulp, { checkDependencies: true, checkFileNames: defaults => { defaults.paramCase.push('!src/tasks/check-file-names/__tests__/**'); return defaults; }, eslint: { rules: { 'global-require': 0 } }, jest: { testPathPattern: /.*-(test|spec)\.js$/, unmockedModulePathPatterns }, jscs: true, jsdoc: true, nsp: true, retire: true }); tools.tasks.jest.register(gulp, 'test-unit', { unmockedModulePathPatterns, testPathPattern: /.*-spec\.js$/ }); gulp.task('default', ['pre-release']);
'use strict'; const gulp = require('gulp'); const tools = require('./src'); const unmockedModulePathPatterns = [ 'node_modules/.*', 'utils/helper-tests.js' ]; tools.initialize(gulp, { checkDependencies: true, checkFileNames: defaults => { defaults.paramCase.push('!src/tasks/check-file-names/__tests__/**'); return defaults; }, eslint: { rules: { 'global-require': 0, 'import/no-unresolved': 0 } }, jest: { testPathPattern: /.*-(test|spec)\.js$/, unmockedModulePathPatterns }, jscs: true, jsdoc: true, nsp: true, retire: true }); tools.tasks.jest.register(gulp, 'test-unit', { unmockedModulePathPatterns, testPathPattern: /.*-spec\.js$/ }); gulp.task('default', ['pre-release']);
Modify to avoid excessive logger initialization
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import dataproperty import logbook import pytablereader logger = logbook.Logger("SimpleSQLie") logger.disable() def set_logger(is_enable): if is_enable != logger.disabled: return if is_enable: logger.enable() else: logger.disable() dataproperty.set_logger(is_enable) pytablereader.set_logger(is_enable) def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level dataproperty.set_log_level(log_level) pytablereader.set_log_level(log_level)
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook logger = logbook.Logger("SimpleSQLie") logger.disable() def set_logger(is_enable): if is_enable: logger.enable() else: logger.disable() def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level
Change XMLWriter.Node to an ES6 class This was still using the old way without syntactic sugar.
/* global jasmineImporter */ /* exported Node */ const {GLib} = imports.gi; const Utils = jasmineImporter.utils; var Node = class Node { constructor(name) { this.name = name; this.attrs = {}; this.children = []; this.text = ''; } toString() { return `<?xml version="1.0" encoding="UTF-8"?>\n${_prettyprint(this)}`; } }; function _attrsToString(attrs) { return Object.keys(attrs).map(key => { const value = attrs[key].toString(); return ` ${key}="${GLib.markup_escape_text(value, -1)}"`; }).join(''); } function _prettyprint(node) { if (node.children.length === 0 && node.text.length === 0) return `<${node.name}${_attrsToString(node.attrs)}/>\n`; const elementTop = `<${node.name}${_attrsToString(node.attrs)}>\n`; const elementBottom = `</${node.name}>\n`; const children = node.children.map(_prettyprint).join(''); let text = GLib.markup_escape_text(node.text, -1).trim(); if (text.length !== 0) text += '\n'; return elementTop + Utils.indent(children, 2) + Utils.indent(text, 2) + elementBottom; }
/* global jasmineImporter */ const {GLib} = imports.gi; const Utils = jasmineImporter.utils; function Node(name) { this.name = name; this.attrs = {}; this.children = []; this.text = ''; } function _attrsToString(attrs) { return Object.keys(attrs).map(key => { const value = attrs[key].toString(); return ` ${key}="${GLib.markup_escape_text(value, -1)}"`; }).join(''); } function _prettyprint(node) { if (node.children.length === 0 && node.text.length === 0) return `<${node.name}${_attrsToString(node.attrs)}/>\n`; const elementTop = `<${node.name}${_attrsToString(node.attrs)}>\n`; const elementBottom = `</${node.name}>\n`; const children = node.children.map(_prettyprint).join(''); let text = GLib.markup_escape_text(node.text, -1).trim(); if (text.length !== 0) text += '\n'; return elementTop + Utils.indent(children, 2) + Utils.indent(text, 2) + elementBottom; } Node.prototype.toString = function () { return `<?xml version="1.0" encoding="UTF-8"?>\n${_prettyprint(this)}`; };
Fix json schema in admin controllers
// json-schema for params on usergroup `create` and `update` methods. 'use strict'; module.exports = { short_name: { type: 'string', required: true, minLength: 1 }, parent_group: { type: [ 'string', 'null' ], required: true }, settings: { type: 'object', required: true, patternProperties: { '.*': { anyOf: [ { type: 'null' }, { type: 'object', additionalProperties: false, properties: { value: { required: true }, force: { type: 'boolean', required: true } } } ] } } } };
// json-schema for params on usergroup `create` and `update` methods. 'use strict'; module.exports = { short_name: { type: 'string', required: true, minLength: 1 }, parent_group: { type: [ 'string', 'null' ], required: true }, settings: { type: 'object', required: true, patternProperties: { '.*': { type: [ 'object', 'null' ], required: true, additionalProperties: false, properties: { value: { required: true }, force: { type: 'boolean', required: true } } } } } };
Move lazy-openclose component to GGRC.Component
/*! Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file> Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> Created By: ivan@reciprocitylabs.com Maintained By: ivan@reciprocitylabs.com */ (function (can, $) { 'use strict'; GGRC.Components('lazyOpenClose', { tag: 'lazy-openclose', scope: { show: false }, content: '<content/>', init: function () { this._control.element.closest('.tree-item').find('.openclose') .bind('click', function () { this.scope.attr('show', true); }.bind(this)); } }); })(window.can, window.can.$);
/*! Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file> Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> Created By: ivan@reciprocitylabs.com Maintained By: ivan@reciprocitylabs.com */ (function (can, $) { 'use strict'; can.Component.extend({ tag: 'lazy-openclose', scope: { show: false }, content: '<content/>', init: function () { this._control.element.closest('.tree-item').find('.openclose') .bind('click', function () { this.scope.attr('show', true); }.bind(this)); } }); })(window.can, window.can.$);
Add testURL to jest config
// 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 prettyFormat from 'pretty-format' import {CONFIGS_DIR, PACKAGE_DIR} from '../../paths' import {getSettings} from '../toolbox' import {join} from 'path' let {debugConfigs, debugToolbox} = getSettings() const CONFIG = { rootDir: join(PACKAGE_DIR, 'src'), testRegex: '__tests__', testPathIgnorePatterns: ['node_modules', '__fixture__', '__fixtures__'], testURL: 'http://localhost', transform: { '^.+\\.(jsx?)$': join(CONFIGS_DIR, 'jest', 'babel-transform.js'), }, verbose: true, } if (debugConfigs || debugToolbox) console.log('Jest config: ', prettyFormat(CONFIG)) module.exports = CONFIG
// 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 prettyFormat from 'pretty-format' import {CONFIGS_DIR, PACKAGE_DIR} from '../../paths' import {getSettings} from '../toolbox' import {join} from 'path' let {debugConfigs, debugToolbox} = getSettings() const CONFIG = { rootDir: join(PACKAGE_DIR, 'src'), testRegex: '__tests__', testPathIgnorePatterns: ['node_modules', '__fixture__', '__fixtures__'], transform: { '^.+\\.(jsx?)$': join(CONFIGS_DIR, 'jest', 'babel-transform.js'), }, verbose: true, } if (debugConfigs || debugToolbox) console.log('Jest config: ', prettyFormat(CONFIG)) module.exports = CONFIG
Add back the development marker
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals # This file is automatically generated, do not edit it __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "warehouse" __summary__ = "Next Generation Python Package Repository" __uri__ = "https://github.com/dstufft/warehouse" __version__ = "13.10.10.dev0" __build__ = "<development>" __author__ = "Donald Stufft" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
# Copyright 2013 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals # This file is automatically generated, do not edit it __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "warehouse" __summary__ = "Next Generation Python Package Repository" __uri__ = "https://github.com/dstufft/warehouse" __version__ = "13.10.10" __build__ = "<development>" __author__ = "Donald Stufft" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2013 Donald Stufft"
Fix test mod for latest mappings
/* * Copyright 2016 FabricMC * * 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 net.fabricmc.test.mixin; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.menu.GuiMainMenu; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = GuiMainMenu.class, remap = false) public abstract class MixinGuiMain extends GuiScreen { @Inject(method = "drawScreen(IIF)V", at = @At("RETURN")) public void draw(int a1, int a2, float a3, CallbackInfo info) { this.fontRenderer.drawString("Fabric Test Mod", 2, this.height - 30, -1); } }
/* * Copyright 2016 FabricMC * * 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 net.fabricmc.test.mixin; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.impl.GuiMainMenu; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = GuiMainMenu.class, remap = false) public abstract class MixinGuiMain extends GuiScreen { @Inject(method = "drawScreen(IIF)V", at = @At("RETURN")) public void draw(int a1, int a2, float a3, CallbackInfo info) { this.fontRenderer.drawString("Fabric Test Mod", 2, this.height - 30, -1); } }
Use filtering parameter at ProductPrivateHost API
package funcs import ( "fmt" "github.com/sacloud/usacloud/command" "github.com/sacloud/usacloud/command/params" ) func PrivateHostCreate(ctx command.Context, params *params.CreatePrivateHostParam) error { client := ctx.GetAPIClient() api := client.GetPrivateHostAPI() p := api.New() // set params p.SetName(params.Name) p.SetDescription(params.Description) p.SetTags(params.Tags) p.SetIconByID(params.IconId) // set plan(There have only one plan now) plans, err := client.Product.GetProductPrivateHostAPI().FilterBy("Class", "dynamic").Find() if err != nil || len(plans.PrivateHostPlans) == 0 { return fmt.Errorf("PrivateHostCreate is failed: can't find any private-host plan %s", err) } p.SetPrivateHostPlanByID(plans.PrivateHostPlans[0].ID) // call Create(id) res, err := api.Create(p) if err != nil { return fmt.Errorf("PrivateHostCreate is failed: %s", err) } return ctx.GetOutput().Print(res) }
package funcs import ( "fmt" "github.com/sacloud/usacloud/command" "github.com/sacloud/usacloud/command/params" ) func PrivateHostCreate(ctx command.Context, params *params.CreatePrivateHostParam) error { client := ctx.GetAPIClient() api := client.GetPrivateHostAPI() p := api.New() // set params p.SetName(params.Name) p.SetDescription(params.Description) p.SetTags(params.Tags) p.SetIconByID(params.IconId) // set plan(There have only one plan now) plans, err := client.Product.GetProductPrivateHostAPI().Find() if err != nil || len(plans.PrivateHostPlans) == 0 { return fmt.Errorf("PrivateHostCreate is failed: can't find any private-host plan %s", err) } p.SetPrivateHostPlanByID(plans.PrivateHostPlans[0].ID) // call Create(id) res, err := api.Create(p) if err != nil { return fmt.Errorf("PrivateHostCreate is failed: %s", err) } return ctx.GetOutput().Print(res) }
Update GitHub API query for latest version
const { GraphQLClient } = require("graphql-request"); const { writeFileSync, existsSync, mkdirSync } = require("fs"); async function fetchMembers(organisation) { const token = process.env.GH_TOKEN; if (!token) { console.error("'GH_TOKEN' not set. Could not fetch nteract members."); return []; } const client = new GraphQLClient("https://api.github.com/graphql", { headers: { Authorization: `Bearer ${token}` } }); const query = `{ organization(login: ${organisation}) { membersWithRole(first: 100) { totalCount nodes { name login websiteUrl avatarUrl url } } } }`; try { const data = await client.request(query); return data.organization.membersWithRole.nodes; } catch (e) { console.error(e); return []; } } async function main() { const members = await fetchMembers("nteract"); if (!existsSync("generated")) mkdirSync("generated"); writeFileSync("./generated/nteract-members.json", JSON.stringify(members)); } main();
const { GraphQLClient } = require("graphql-request"); const { writeFileSync, existsSync, mkdirSync } = require("fs"); async function fetchMembers(organisation) { const token = process.env.GH_TOKEN; if (!token) { console.error("'GH_TOKEN' not set. Could not fetch nteract members."); return []; } const client = new GraphQLClient("https://api.github.com/graphql", { headers: { Authorization: `Bearer ${token}` } }); const query = `{ organization(login: ${organisation}) { members(first: 100) { totalCount nodes { name login websiteUrl avatarUrl url } } } }`; try { const data = await client.request(query); if (data.organization.members.totalCount > 100) { console.error( "100+ members in the organization. That's too much for one GraphQL call." ); } return data.organization.members.nodes; } catch (e) { console.error(e); return []; } } async function main() { const members = await fetchMembers("nteract"); if (!existsSync("generated")) mkdirSync("generated"); writeFileSync("./generated/nteract-members.json", JSON.stringify(members)); } main();
admin_blog: Add date field to edit form.
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_blog.models import BlogEntry class BlogEntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BlogEntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Blogientry', 'title', 'text', 'date', 'public', ButtonHolder ( Submit('submit', 'Tallenna') ) ) ) class Meta: model = BlogEntry fields = ('title','text','public','date')
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_blog.models import BlogEntry class BlogEntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BlogEntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Blogientry', 'title', 'text', 'public', ButtonHolder ( Submit('submit', 'Tallenna') ) ) ) class Meta: model = BlogEntry fields = ('title','text','public')
Add an interface to change loading encoding for File/URL loaders
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None @encoding.setter def encoding(self, codec_name): self.__loader.encoding = codec_name def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
Fix typo when using sys.stderr.write
# -*- coding: utf-8 -*- # Copyright 2015 OpenMarket Ltd # # 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. if __name__ == "__main__": import sys from homeserver import HomeServerConfig action = sys.argv[1] if action == "read": key = sys.argv[2] config = HomeServerConfig.load_config("", sys.argv[3:]) print getattr(config, key) sys.exit(0) else: sys.stderr.write("Unknown command %r\n" % (action,)) sys.exit(1)
# -*- coding: utf-8 -*- # Copyright 2015 OpenMarket Ltd # # 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. if __name__ == "__main__": import sys from homeserver import HomeServerConfig action = sys.argv[1] if action == "read": key = sys.argv[2] config = HomeServerConfig.load_config("", sys.argv[3:]) print getattr(config, key) sys.exit(0) else: sys.stderr.write("Unknown command %r", action) sys.exit(1)
Fix webpack builds on windows
var webpack = require('webpack'); var poststylus = require('poststylus'); var path = require('path') module.exports = { devtool: 'source-map', entry: path.resolve(__dirname, 'src'), output: { path: 'public/builds/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel', include: path.resolve(__dirname, 'src'), query: { presets: ['es2015'], plugins: ['mjsx'] }, }, { test: /\.styl/, loader: 'style!css!stylus', }, { test: /\.html/, loader: 'html' } ], }, stylus: { use: [ function (stylus) { stylus.import(path.resolve(__dirname, 'src/stylus/variables')); }, poststylus([ 'autoprefixer' ]) ] }, plugins: [ new webpack.ProvidePlugin({ m: 'mithril' }) ] }
var webpack = require('webpack'); var poststylus = require('poststylus'); module.exports = { devtool: 'source-map', entry: __dirname + '/src', output: { path: 'public/builds/', filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel', include: __dirname + '/src', query: { presets: ['es2015'], plugins: ['mjsx'] }, }, { test: /\.styl/, loader: 'style!css!stylus', }, { test: /\.html/, loader: 'html' } ], }, stylus: { use: [ function (stylus) { stylus.import(__dirname + '/src/stylus/variables'); }, poststylus([ 'autoprefixer' ]) ] }, plugins: [ new webpack.ProvidePlugin({ m: 'mithril' }) ] }
Remove hook that is obsolete with openapi validation
const { authenticate } = require('@feathersjs/authentication'); const { iff, isProvider, disallow } = require('feathers-hooks-common'); const { populateCurrentSchool } = require('../../../hooks'); const fillDefaultValues = require('./fillDefaultValues'); const restrictToSchoolSystems = require('../../ldap/hooks/restrictToSchoolSystems'); module.exports = { before: { all: [authenticate('jwt')], get: [], create: [ // only allow external calls (the service needs a user) iff(!isProvider('external'), disallow()), populateCurrentSchool, fillDefaultValues, ], patch: [ // only allow external calls (the service needs a user) iff(!isProvider('external'), disallow()), populateCurrentSchool, restrictToSchoolSystems, fillDefaultValues, ], update: [disallow()], remove: [disallow()], }, after: { all: [], }, };
const { authenticate } = require('@feathersjs/authentication'); const { iff, keepQuery, isProvider, disallow } = require('feathers-hooks-common'); const { populateCurrentSchool } = require('../../../hooks'); const fillDefaultValues = require('./fillDefaultValues'); const restrictToSchoolSystems = require('../../ldap/hooks/restrictToSchoolSystems'); module.exports = { before: { all: [authenticate('jwt')], get: [iff(isProvider('external'), keepQuery())], create: [ // only allow external calls (the service needs a user) iff(!isProvider('external'), disallow()), keepQuery('activate', 'verifyOnly'), populateCurrentSchool, fillDefaultValues, ], patch: [ // only allow external calls (the service needs a user) iff(!isProvider('external'), disallow()), keepQuery('activate', 'verifyOnly'), populateCurrentSchool, restrictToSchoolSystems, fillDefaultValues, ], update: [disallow()], remove: [disallow()], }, after: { all: [], }, };
Fix iterarting over NodeList in Firefox
/* * Copyright 2016 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. */ module.exports = function findGroupedPlatonThreadUrlElements() { var groupedElements = {}; function addThreadUrlAndElement(threadUrl, elem) { if (!(threadUrl in groupedElements)) { groupedElements[threadUrl] = [elem]; } else if (groupedElements[threadUrl].indexOf(threadUrl) < 0) { groupedElements[threadUrl].push(elem); } } var linksToCommentThreads = document.querySelectorAll('a[href$="#platon-comment-thread"]'); Array.prototype.forEach.call(linksToCommentThreads, function (linkElem) { addThreadUrlAndElement(linkElem.pathname, linkElem); }); var elemsWithThreadIds = document.querySelectorAll('*[data-platon-thread-url]'); Array.prototype.forEach.call(elemsWithThreadIds, function (elem) { addThreadUrlAndElement(elem.getAttribute('data-platon-thread-url'), elem); }); return groupedElements; };
/* * Copyright 2016 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. */ module.exports = function findGroupedPlatonThreadUrlElements() { var groupedElements = {}; function addThreadUrlAndElement(threadUrl, elem) { if (!(threadUrl in groupedElements)) { groupedElements[threadUrl] = [elem]; } else if (groupedElements[threadUrl].indexOf(threadUrl) < 0) { groupedElements[threadUrl].push(elem); } } var linksToCommentThreads = document.querySelectorAll('a[href$="#platon-comment-thread"]'); linksToCommentThreads.forEach(function (linkElem) { addThreadUrlAndElement(linkElem.pathname, linkElem); }); var elemsWithThreadIds = document.querySelectorAll('*[data-platon-thread-url]'); elemsWithThreadIds.forEach(function (elem) { addThreadUrlAndElement(elem.getAttribute('data-platon-thread-url'), elem); }); return groupedElements; };
Add missing parentheses to print()
# Copyright 2016 The Kubernetes 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. import sys # Kubernetes branch to get the OpenAPI spec from. KUBERNETES_BRANCH = "release-1.5" # Spec version will be set in downloaded spec and all # generated code will refer to it. SPEC_VERSION = "v1.5.0-snapshot" # client version for packaging and releasing. It can # be different than SPEC_VERSION. CLIENT_VERSION = "1.0.0-snapshot" # Name of the release package PACKAGE_NAME = "kubernetes" # If called directly, return the constant value given # its name. Useful in bash scripts. if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: python constant.py CONSTANT_NAME") sys.exit(1) if sys.argv[1] in globals(): print(globals()[sys.argv[1]]) else: print("Cannot find constant %s" % sys.argv[1]) sys.exit(1)
# Copyright 2016 The Kubernetes 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. import sys # Kubernetes branch to get the OpenAPI spec from. KUBERNETES_BRANCH = "release-1.5" # Spec version will be set in downloaded spec and all # generated code will refer to it. SPEC_VERSION = "v1.5.0-snapshot" # client version for packaging and releasing. It can # be different than SPEC_VERSION. CLIENT_VERSION = "1.0.0-snapshot" # Name of the release package PACKAGE_NAME = "kubernetes" # If called directly, return the constant value given # its name. Useful in bash scripts. if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: python constant.py CONSTANT_NAME") sys.exit(1) if sys.argv[1] in globals(): print globals()[sys.argv[1]] else: print "Cannot find constant %s" % sys.argv[1] sys.exit(1)
Rename property names to follow JMS standard for identifiers.
/* * Copyright 2016 Erik Wramner. * * 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 name.wramner.jmstools.messages; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; /** * A message provider can create JMS messages enriched with a checksum property that can be checked on the other side. * <p> * Note that according to the JMS standard property names must follow the same rules as Java identifiers. * * @author Erik Wramner */ public interface MessageProvider { static final String UNIQUE_MESSAGE_ID_PROPERTY_NAME = "EWJMSToolsUniqueMessageId"; static final String CHECKSUM_PROPERTY_NAME = "EWJMSToolsPayloadChecksumMD5"; static final String LENGTH_PROPERTY_NAME = "EWJMSToolsPayloadLength"; /** * Create message with checksum and length properties. * * @param session The JMS session. * @return message. * @throws JMSException on JMS errors. */ Message createMessageWithPayloadAndChecksumProperty(Session session) throws JMSException; }
/* * Copyright 2016 Erik Wramner. * * 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 name.wramner.jmstools.messages; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; /** * A message provider can create JMS messages enriched with a checksum property that can be checked on the other side. * * @author Erik Wramner */ public interface MessageProvider { static final String UNIQUE_MESSAGE_ID_PROPERTY_NAME = "Unique-Message-Id"; static final String CHECKSUM_PROPERTY_NAME = "Payload-Checksum-MD5"; static final String LENGTH_PROPERTY_NAME = "Payload-Length"; /** * Create message with checksum and length properties. * * @param session The JMS session. * @return message. * @throws JMSException on JMS errors. */ Message createMessageWithPayloadAndChecksumProperty(Session session) throws JMSException; }
Remove "throws IOException" when "close()" doesn't actually throw it.
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.NativeBytes; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LongArrayDirectReferenceTest { @Test public void getSetValues() { int length = 1024 + 8; try (NativeBytes bytes = NativeBytes.nativeBytes(length + 8)) { LongArrayDirectReference.write(bytes, 128); LongArrayDirectReference array = new LongArrayDirectReference(); array.bytesStore(bytes, 0, length); assertEquals(128, array.getCapacity()); for (int i = 0; i < 128; i++) array.setValueAt(i, i + 1); for (int i = 0; i < 128; i++) assertEquals(i + 1, array.getValueAt(i)); } } }
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.NativeBytes; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals; public class LongArrayDirectReferenceTest { @Test public void getSetValues() throws Exception { int length = 1024 + 8; try (NativeBytes bytes = NativeBytes.nativeBytes(length + 8)) { LongArrayDirectReference.write(bytes, 128); LongArrayDirectReference array = new LongArrayDirectReference(); array.bytesStore(bytes, 0, length); assertEquals(128, array.getCapacity()); for (int i = 0; i < 128; i++) array.setValueAt(i, i + 1); for (int i = 0; i < 128; i++) assertEquals(i + 1, array.getValueAt(i)); } } }
Fix annotations in MediaReadyState util For some reason, the new compiler in the master branch let this by, but the old compiler in the v2.5.x branch complained when I cherry-picked the utility. Change-Id: I1e688f72594b74ed7d2a7c2801eb179b8ec13e8c
/** @license * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.util.MediaReadyState'); goog.require('shaka.util.EventManager'); shaka.util.MediaReadyState = class { /** * @param {!HTMLMediaElement} mediaElement * @param {number} readyState * @param {shaka.util.EventManager} eventManager * @param {function()} callback */ static waitForReadyState(mediaElement, readyState, eventManager, callback) { if (readyState == HTMLMediaElement.HAVE_NOTHING || mediaElement.readyState >= readyState) { callback(); } else { const MediaReadyState = shaka.util.MediaReadyState; const eventName = MediaReadyState.READY_STATES_TO_EVENT_NAMES_.get(readyState); eventManager.listenOnce(mediaElement, eventName, callback); } } }; /** * @const {!Map.<number, string>} * @private */ shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_ = new Map([ [HTMLMediaElement.HAVE_METADATA, 'loadedmetadata'], [HTMLMediaElement.HAVE_CURRENT_DATA, 'loadeddata'], [HTMLMediaElement.HAVE_FUTURE_DATA, 'canplay'], [HTMLMediaElement.HAVE_ENOUGH_DATA, 'canplaythrough'], ]);
/** @license * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.util.MediaReadyState'); shaka.util.MediaReadyState = class { /* * @param {!HTMLMediaElement} mediaElement * @param {HTMLMediaElement.ReadyState} readyState * @param {!function()} callback */ static waitForReadyState(mediaElement, readyState, eventManager, callback) { if (readyState == HTMLMediaElement.HAVE_NOTHING || mediaElement.readyState >= readyState) { callback(); } else { const MediaReadyState = shaka.util.MediaReadyState; const eventName = MediaReadyState.READY_STATES_TO_EVENT_NAMES_.get(readyState); eventManager.listenOnce(mediaElement, eventName, callback); } } }; /** * @const {!Map.<number, string>} * @private */ shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_ = new Map([ [HTMLMediaElement.HAVE_METADATA, 'loadedmetadata'], [HTMLMediaElement.HAVE_CURRENT_DATA, 'loadeddata'], [HTMLMediaElement.HAVE_FUTURE_DATA, 'canplay'], [HTMLMediaElement.HAVE_ENOUGH_DATA, 'canplaythrough'], ]);
Fix timer in @bench to be reset for each benched function call
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" @wraps(f) def wrapped(*args, **kwargs): timer = Timer(tick_now=False) timer.start() f(*args, **kwargs) timer.stop() res = [call_signature(f, *args, **kwargs), timer.get_times()['real']] # TODO penser a quel temps garder return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call.""" call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()]) @bench def lala(a, b, c="default c", d="default d"): print("lala est appelee") if __name__ == '__main__': print(lala("cest a", "cest b", d="change d"))
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" timer = Timer(tick_now=False) @wraps(f) def wrapped(*args, **kwargs): timer.start() f(*args, **kwargs) timer.stop() res = [call_signature(f, *args, **kwargs), timer.get_times()['real']] # TODO penser a quel temps garder return res return wrapped def call_signature(f, *args, **kwargs): """Return a string representation of a function call.""" call_args = getcallargs(f, *args, **kwargs) return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()]) @bench def lala(a, b, c="default c", d="default d"): print("lala est appelee") if __name__ == '__main__': print(lala("cest a", "cest b", d="change d"))
Add support for creating Satisfaction Ratings As documented at https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all }; // ====================================== Posting SatisfactionRatings SatisfactionRatings.prototype.create = function (ticketID, satisfactionRating, cb) { this.request('POST', ['tickets', ticketId, 'satisfaction_rating'], satisfactionRating, cb); };
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all };
Fix typo in test class
package de.fu_berlin.cdv.chasingpictures.activity; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import java.util.List; import de.fu_berlin.cdv.chasingpictures.DebugUtilities; import de.fu_berlin.cdv.chasingpictures.api.Picture; import de.fu_berlin.cdv.chasingpictures.api.Place; /** * @author Simon Kalt */ public class SlideshowTest extends ActivityInstrumentationTestCase2<Slideshow> { public SlideshowTest() { super(Slideshow.class); } public void setUp() throws Exception { super.setUp(); Place placeWithPictures = DebugUtilities.getPlaceWithPictures(); if (placeWithPictures != null) { List<Picture> pictures = placeWithPictures.getPictures(); // Set up activity intent Intent intent = Slideshow.createIntent(getInstrumentation().getContext(), pictures); setActivityIntent(intent); } } public void testIntentDataReceived() throws Exception { List<Picture> pictures = getActivity().pictures; assertFalse("Received no pictures from Intent", pictures == null || pictures.isEmpty()); } }
package de.fu_berlin.cdv.chasingpictures.activity; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import java.util.List; import de.fu_berlin.cdv.chasingpictures.DebugUtilities; import de.fu_berlin.cdv.chasingpictures.api.Picture; import de.fu_berlin.cdv.chasingpictures.api.Place; /** * @author Simon Kalt */ public class SlideshowTest extends ActivityInstrumentationTestCase2<Slideshow> { public SlideshowTest() { super(Slideshow.class); } public void setUp() throws Exception { super.setUp(); Place placeWithPictures = DebuggUtilities.getPlaceWithPictures(); if (placeWithPictures != null) { List<Picture> pictures = placeWithPictures.getPictures(); // Set up activity intent Intent intent = Slideshow.createIntent(getInstrumentation().getContext(), pictures); setActivityIntent(intent); } } public void testIntentDataReceived() throws Exception { List<Picture> pictures = getActivity().pictures; assertFalse("Received no pictures from Intent", pictures == null || pictures.isEmpty()); } }
Use HTTPS for base URL to THREDDS server Last week OIT made csdms.colorado.edu only accessible by HTTPS, which caused the HTTP URL for the THREDDS server to fail.
import os from pymt.printers.nc.read import field_fromfile _BASE_URL_FOR_TEST_FILES = ('https://csdms.colorado.edu/thredds/fileServer' '/benchmark/ugrid/') _TMP_DIR = 'tmp' def setup(): import tempfile globals().update({ '_TMP_DIR': tempfile.mkdtemp(dir='.') }) def teardown(): from shutil import rmtree rmtree(_TMP_DIR) def fetch_data_file(filename): import urllib2 remote_file = urllib2.urlopen(_BASE_URL_FOR_TEST_FILES + filename) local_file = os.path.join(_TMP_DIR, filename) with open(local_file, 'w') as netcdf_file: netcdf_file.write(remote_file.read()) return local_file def test_unstructured_2d(): field = field_fromfile(fetch_data_file('unstructured.2d.nc'), fmt='NETCDF4') def test_rectilinear_1d(): field = field_fromfile(fetch_data_file('rectilinear.1d.nc'), fmt='NETCDF4') def test_rectilinear_2d(): field = field_fromfile(fetch_data_file('rectilinear.2d.nc'), fmt='NETCDF4') def test_rectilinear_3d(): field = field_fromfile(fetch_data_file('rectilinear.3d.nc'), fmt='NETCDF4')
import os from pymt.printers.nc.read import field_fromfile _BASE_URL_FOR_TEST_FILES = ('http://csdms.colorado.edu/thredds/fileServer' '/benchmark/ugrid/') _TMP_DIR = 'tmp' def setup(): import tempfile globals().update({ '_TMP_DIR': tempfile.mkdtemp(dir='.') }) def teardown(): from shutil import rmtree rmtree(_TMP_DIR) def fetch_data_file(filename): import urllib2 remote_file = urllib2.urlopen(_BASE_URL_FOR_TEST_FILES + filename) local_file = os.path.join(_TMP_DIR, filename) with open(local_file, 'w') as netcdf_file: netcdf_file.write(remote_file.read()) return local_file def test_unstructured_2d(): field = field_fromfile(fetch_data_file('unstructured.2d.nc'), fmt='NETCDF4') def test_rectilinear_1d(): field = field_fromfile(fetch_data_file('rectilinear.1d.nc'), fmt='NETCDF4') def test_rectilinear_2d(): field = field_fromfile(fetch_data_file('rectilinear.2d.nc'), fmt='NETCDF4') def test_rectilinear_3d(): field = field_fromfile(fetch_data_file('rectilinear.3d.nc'), fmt='NETCDF4')
Update Speed Dial API implementation to set attributes independent of Chromium call to update attributes.
var SpeeddialContext = function() { this.properties = {}; global.opr.speeddial.get(function(speeddialProperties) { this.properties.url = speeddialProperties.url; this.properties.title = speeddialProperties.title; // Set WinTabs feature to LOADED deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true; }.bind(this)); }; SpeeddialContext.prototype.constructor = SpeeddialContext; SpeeddialContext.prototype.__defineGetter__('url', function() { return this.properties.url || ""; }); // read SpeeddialContext.prototype.__defineSetter__('url', function(val) { this.properties.url = val; global.opr.speeddial.update({ 'url': val }, function() {}); }); // write SpeeddialContext.prototype.__defineGetter__('title', function() { return this.properties.title || ""; }); // read SpeeddialContext.prototype.__defineSetter__('title', function(val) { this.properties.title = val; global.opr.speeddial.update({ 'title': val }, function() {}); }); // write
var SpeeddialContext = function() { this.properties = {}; global.opr.speeddial.get(function(speeddialProperties) { this.properties.url = speeddialProperties.url; this.properties.title = speeddialProperties.title; // Set WinTabs feature to LOADED deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true; }.bind(this)); }; SpeeddialContext.prototype.constructor = SpeeddialContext; SpeeddialContext.prototype.__defineGetter__('url', function() { return this.properties.url || ""; }); // read SpeeddialContext.prototype.__defineSetter__('url', function(val) { global.opr.speeddial.update({ 'url': val }, function(speeddialProperties) { this.properties.url = speeddialProperties.url; }.bind(this)); }); // write SpeeddialContext.prototype.__defineGetter__('title', function() { return this.properties.title || ""; }); // read SpeeddialContext.prototype.__defineSetter__('title', function(val) { global.opr.speeddial.update({ 'title': val }, function(speeddialProperties) { this.properties.title = speeddialProperties.title; }.bind(this)); }); // write
Fix path resolving in part.url
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) sys.path.append(path) import konstrukteur.Konstrukteur import jasy.asset.Manager @share def build(profile, regenerate = False): """ Build static website """ def getPartUrl(part, type): folder = "" if type == "css": folder = profile.getCssFolder() #outputPath = folder outputPath = os.path.relpath("%s/%s" % (profile.getDestinationPath(), folder), profile.getWorkingPath()) filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type)) return filename profile.addCommand("part.url", getPartUrl, "url") for permutation in profile.permutate(): konstrukteur.Konstrukteur.build(regenerate, profile)
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) sys.path.append(path) import konstrukteur.Konstrukteur import jasy.asset.Manager @share def build(profile, regenerate = False): """ Build static website """ def getPartUrl(part, type): folder = "" if type == "css": folder = profile.getCssFolder() outputPath = folder #os.path.join(profile.getDestinationPath(), folder) filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type)) return filename profile.addCommand("part.url", getPartUrl, "url") for permutation in profile.permutate(): konstrukteur.Konstrukteur.build(regenerate, profile)
Add tox to test extras
from __future__ import unicode_literals from codecs import open as codecs_open from setuptools import setup, find_packages # Get the long description from the relevant file with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='geog', version='0.0.1', description="Numpy-based vectorized geospatial functions", long_description=long_description, classifiers=[], keywords='', author="Jacob Wasserman", author_email='jwasserman@gmail.com', url='https://github.com/jwass/geog', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'numpy', ], extras_require={ 'test': ['pytest', 'tox'], }, )
from __future__ import unicode_literals from codecs import open as codecs_open from setuptools import setup, find_packages # Get the long description from the relevant file with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='geog', version='0.0.1', description="Numpy-based vectorized geospatial functions", long_description=long_description, classifiers=[], keywords='', author="Jacob Wasserman", author_email='jwasserman@gmail.com', url='https://github.com/jwass/geog', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'numpy', ], extras_require={ 'test': ['pytest'], }, )
Fix how .ts files are served by karma.
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', 'angular-cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-remap-istanbul'), require('angular-cli/plugins/karma') ], files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['angular-cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, remapIstanbulReporter: { reports: { html: 'coverage', lcovonly: './coverage/coverage.lcov' } }, angularCli: { config: './angular-cli.json', environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'karma-remap-istanbul'] : ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', 'angular-cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-remap-istanbul'), require('angular-cli/plugins/karma') ], files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['angular-cli'] }, remapIstanbulReporter: { reports: { html: 'coverage', lcovonly: './coverage/coverage.lcov' } }, angularCli: { config: './angular-cli.json', environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'karma-remap-istanbul'] : ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
Split compiler and execution steps
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def compiler(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('C++ Transpilation', ast.transpile_children()) utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() return ast def run(source): ast = compiler(source) with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
import os from thinglang import utils from thinglang.execution.execution import ExecutionEngine from thinglang.lexer.lexer import lexer from thinglang.parser.analyzer import Analyzer from thinglang.parser.parser import parse from thinglang.parser.simplifier import Simplifier BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'include') def collect_includes(): files = [os.path.join(BASE_DIR, path) for path in os.listdir(BASE_DIR)] return '\n' + '\n'.join(open(f).read() for f in files) def run(source): if not source: raise ValueError('Source cannot be empty') source = (source + collect_includes()).strip().replace(' ' * 4, '\t') utils.print_header('Source', source) lexical_groups = list(lexer(source)) ast = parse(lexical_groups) Simplifier(ast).run() utils.print_header('C++ Transpilation', ast.transpile_children()) utils.print_header('Parsed AST', ast.tree()) Analyzer(ast).run() with ExecutionEngine(ast) as engine: engine.execute() return engine.results()
Use PHP_SAPI instead of php_sapi_name()
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')) || PHP_SAPI === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')) || php_sapi_name() === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
Use myria constant for master worker id
package edu.washington.escience.myria.parallel; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.TupleBatch; import edu.washington.escience.myria.operator.Operator; /** * The producer part of the Collect Exchange operator. * * The producer actively pushes the tuples generated by the child operator to the paired CollectConsumer. * */ public class CollectProducer extends GenericShuffleProducer { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * @param child the child who provides data for this producer to distribute. * @param operatorID destination operator the data goes * @param collectConsumerWorkerID destination worker the data goes. * */ public CollectProducer(final Operator child, final ExchangePairID operatorID, final int collectConsumerWorkerID) { super(child, new ExchangePairID[] { operatorID }, new int[][] { { MyriaConstants.MASTER_ID } }, new int[] { collectConsumerWorkerID }, new FixValuePartitionFunction(0), true); } @Override protected TupleBatch[] getTupleBatchPartitions(final TupleBatch tup) { return new TupleBatch[] { tup }; } }
package edu.washington.escience.myria.parallel; import edu.washington.escience.myria.TupleBatch; import edu.washington.escience.myria.operator.Operator; /** * The producer part of the Collect Exchange operator. * * The producer actively pushes the tuples generated by the child operator to the paired CollectConsumer. * */ public class CollectProducer extends GenericShuffleProducer { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * @param child the child who provides data for this producer to distribute. * @param operatorID destination operator the data goes * @param collectConsumerWorkerID destination worker the data goes. * */ public CollectProducer(final Operator child, final ExchangePairID operatorID, final int collectConsumerWorkerID) { super(child, new ExchangePairID[] { operatorID }, new int[][] { { 0 } }, new int[] { collectConsumerWorkerID }, new FixValuePartitionFunction(0), true); } @Override protected TupleBatch[] getTupleBatchPartitions(final TupleBatch tup) { return new TupleBatch[] { tup }; } }
Swap order to make more sense.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropFileIdFromReactions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('reactions', function (Blueprint $table) { $table->dropColumn('file_id'); $table->dropUnique('file_drupal_ns_taxonomy_unique'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('reactions', function (Blueprint $table) { $table->integer('file_id')->index()->comment('The reportback_file.fid that this kudos applies to.'); $table->unique(['file_id', 'drupal_id', 'northstar_id', 'taxonomy_id'], 'file_drupal_ns_taxonomy_unique'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropFileIdFromReactions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('reactions', function (Blueprint $table) { $table->dropColumn('file_id'); $table->dropUnique('file_drupal_ns_taxonomy_unique'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('reactions', function (Blueprint $table) { $table->unique(['file_id', 'drupal_id', 'northstar_id', 'taxonomy_id'], 'file_drupal_ns_taxonomy_unique'); $table->integer('file_id')->index()->comment('The reportback_file.fid that this kudos applies to.'); }); } }
Clean up the template tags module a bit.
from django import template from ..models import Message register = template.Library() class MessagesForPageNode(template.Node): def __init__(self, url, varname): self.url = template.Variable(url) self.varname = varname def render(self, context): try: url = self.url.resolve(context) except template.VariableDoesNotExist: return '' context[self.varname] = Message.objects.match(url) return '' @register.tag def get_messages_for_page(parser, token): bits = token.split_contents() if len(bits) != 4 or bits[2] != 'as': raise template.TemplateSyntaxError("%s syntax must be '%s [url] as [varname]" % (bits[0], bits[0])) return MessagesForPageNode(bits[1], bits[3])
from django import template from soapbox.models import Message register = template.Library() class MessagesForPageNode(template.Node): def __init__(self, url, varname): self.url = template.Variable(url) self.varname = varname def render(self, context): try: url = self.url.resolve(context) except template.VariableDoesNotExist: return '' context[self.varname] = Message.objects.match(url) return '' def get_messages_for_page(parser, token): bits = token.split_contents() if len(bits) != 4 or bits[2] != 'as': raise template.TemplateSyntaxError("%s syntax must be '{% %s [url] as [varname] %}" % (bits[0], bits[0])) return MessagesForPageNode(bits[1], bits[3])
Use shell attribute of magics class
import ast from snoop import snoop from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): filename = self.shell.compile.cache(cell) code = self.shell.compile(cell, filename, 'exec') tracer = snoop() tracer.variable_whitelist = set() for node in ast.walk(ast.parse(cell)): if isinstance(node, ast.Name): tracer.variable_whitelist.add(node.id) tracer.target_codes.add(code) with tracer: self.shell.ex(code)
import ast from snoop import snoop from IPython import get_ipython from IPython.core.magic import Magics, cell_magic, magics_class @magics_class class SnoopMagics(Magics): @cell_magic def snoop(self, _line, cell): shell = get_ipython() filename = shell.compile.cache(cell) code = shell.compile(cell, filename, 'exec') tracer = snoop() tracer.variable_whitelist = set() for node in ast.walk(ast.parse(cell)): if isinstance(node, ast.Name): tracer.variable_whitelist.add(node.id) tracer.target_codes.add(code) with tracer: shell.ex(code)
Use django json encoder for models manger params
from __future__ import absolute_import, unicode_literals import json import uuid from django.core.serializers.json import DjangoJSONEncoder from django.db.models.manager import BaseManager from django.db.models.query import QuerySet from corehq.toggles import ICDS_COMPARE_QUERIES_AGAINST_CITUS, NAMESPACE_OTHER class CitusComparisonQuerySet(QuerySet): def _fetch_all(self): from custom.icds_reports.tasks import run_citus_experiment_raw_sql if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER): query, params = self.query.sql_with_params() params = json.loads(json.dumps(params, cls=DjangoJSONEncoder)) run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__) super(CitusComparisonQuerySet, self)._fetch_all() class CitusComparisonManager(BaseManager.from_queryset(CitusComparisonQuerySet)): pass
from __future__ import absolute_import, unicode_literals import uuid from django.db.models.manager import BaseManager from django.db.models.query import QuerySet from corehq.toggles import ICDS_COMPARE_QUERIES_AGAINST_CITUS, NAMESPACE_OTHER class CitusComparisonQuerySet(QuerySet): def _fetch_all(self): from custom.icds_reports.tasks import run_citus_experiment_raw_sql if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER): query, params = self.query.sql_with_params() run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__) super(CitusComparisonQuerySet, self)._fetch_all() class CitusComparisonManager(BaseManager.from_queryset(CitusComparisonQuerySet)): pass
Add backBtn styling, fix indentation
/** * * @flow */ 'use strict'; import {StyleSheet} from 'react-native'; const GlobalStyles = { contentWrapper: { paddingLeft: 5, paddingRight: 5, }, sectionHeader: { fontSize: 20, marginTop: 10, }, thumbnail: { height: 45, width: 45, borderRadius: 22, // why dafuq is 22 circular?? }, buttonContainer: { padding:10, paddingTop: 11, height:45, overflow:'hidden', borderRadius:4, backgroundColor: '#ededed' }, separator: { flex: 1, height: StyleSheet.hairlineWidth, backgroundColor: '#8E8E8E', }, backBtn: { title: "Back", layout: "icon", icon: "ios-arrow-back", } }; module.exports = GlobalStyles;
/** * * @flow */ 'use strict'; import {StyleSheet} from 'react-native'; const GlobalStyles = { contentWrapper: { paddingLeft: 5, paddingRight: 5, }, sectionHeader: { fontSize: 20, marginTop: 10, }, thumbnail: { height: 45, width: 45, borderRadius: 22, // why dafuq is 22 circular?? }, buttonContainer: { padding:10, paddingTop: 11, height:45, overflow:'hidden', borderRadius:4, backgroundColor: '#ededed' }, separator: { flex: 1, height: StyleSheet.hairlineWidth, backgroundColor: '#8E8E8E', }, }; module.exports = GlobalStyles;
Allow repository information to be passed as arguments
package svnwatch import ( "encoding/xml" "fmt" "os" "os/exec" "strconv" shellwords "github.com/mattn/go-shellwords" "github.com/pkg/errors" ) type Command struct { XMLName xml.Name `xml:"command"` ArgumentType *string `xml:"pass-type,attr,omitempty"` Command string `xml:",chardata"` } func (c Command) Execute(repo Repository) error { pieces, err := shellwords.Parse(c.Command) if err != nil { return errors.Wrapf(err, "failed to parse %s", c.Command) } cmd := exec.Command(pieces[0], pieces[1:]...) cmd.Env = os.Environ() if c.ArgumentType == nil || *c.ArgumentType == "normal" { cmd.Args = append(cmd.Args, repo.URL, strconv.Itoa(repo.Revision)) } else if *c.ArgumentType == "env" { cmd.Env = append( os.Environ(), fmt.Sprintf("SVN_URL=%s", repo.URL), fmt.Sprintf("SVN_REVISION=%d", repo.Revision), ) } else { return fmt.Errorf("invalid argument type %s for %s", *c.ArgumentType, c.Command) } if err := cmd.Run(); err != nil { return errors.Wrapf(err, "failed to execute %s", c.Command) } return nil }
package svnwatch import ( "encoding/xml" "fmt" "os" "os/exec" shellwords "github.com/mattn/go-shellwords" "github.com/pkg/errors" ) type Command struct { XMLName xml.Name `xml:"command"` Command string `xml:",chardata"` } func (c Command) Execute(repo Repository) error { pieces, err := shellwords.Parse(c.Command) if err != nil { return errors.Wrapf(err, "failed to parse %s", c.Command) } cmd := exec.Command(pieces[0], pieces[1:]...) cmd.Env = os.Environ() cmd.Env = append( os.Environ(), fmt.Sprintf("SVN_URL=%s", repo.URL), fmt.Sprintf("SVN_REVISION=%d", repo.Revision), ) if err := cmd.Run(); err != nil { return errors.Wrapf(err, "failed to execute %s", c.Command) } return nil }
Remove the plottable typings todo as it is currently a good solution Change: 130777731
/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ var gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ var gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', // TODO(danmane): add plottable to the typings registry after updating it // and remove this. 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
[fix][minor] Set Project Gantt Chart dates same as Project dates
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt // show tasks cur_frm.cscript.refresh = function(doc) { if(!doc.__islocal) { cur_frm.add_custom_button(__("Gantt Chart"), function() { frappe.route_options = {"project": doc.name, "start": doc.project_start_date, "end": doc.completion_date}; frappe.set_route("Gantt", "Task"); }, "icon-tasks", true); cur_frm.add_custom_button(__("Tasks"), function() { frappe.route_options = {"project": doc.name} frappe.set_route("List", "Task"); }, "icon-list", true); } } cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) { return{ query: "erpnext.controllers.queries.customer_query" } }
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt // show tasks cur_frm.cscript.refresh = function(doc) { if(!doc.__islocal) { cur_frm.add_custom_button(__("Gantt Chart"), function() { frappe.route_options = {"project": doc.name} frappe.set_route("Gantt", "Task"); }, "icon-tasks", true); cur_frm.add_custom_button(__("Tasks"), function() { frappe.route_options = {"project": doc.name} frappe.set_route("List", "Task"); }, "icon-list", true); } } cur_frm.fields_dict.customer.get_query = function(doc,cdt,cdn) { return{ query: "erpnext.controllers.queries.customer_query" } }
Fix browser-compability issues with scrolling and submitting
$(function() { var socket = io.connect('/'); var poemContainer = $('#poem-edit-header'); var poemId = poemContainer.data('poem-id'); var linesContainer = $('#lines'); var lineTextInput = poemContainer.find('.line-text'); socket.on('line-created-for-poem-' + poemId, function(poemLine) { $('<div/>', { 'class': 'line', 'text': poemLine.text }).appendTo(linesContainer); $(document).scrollTop($(document).height()); lineTextInput.focus(); }); poemContainer.find('.newline-form').submit(function() { var lineData = { poem_id: poemId, text: lineTextInput.val() }; $.post('/line', lineData); lineTextInput.val(''); }); });
$(function() { var socket = io.connect('/'); var poemContainer = $('#poem-edit-header'); var poemId = poemContainer.data('poem-id'); var linesContainer = $('#lines'); socket.on('line-created-for-poem-' + poemId, function(poemLine) { $('<div/>', { 'class': 'line', 'text': poemLine.text }).appendTo(linesContainer); $(document).scrollTop($(document).attr('height')); }); poemContainer.find('.newline-form').submit(function() { var lineTextInput = $(this).find('.line-text'); var lineData = { poem_id: poemId, text: lineTextInput.val() }; $.post('/line', lineData); lineTextInput.val(''); }); });
Fix formatting to follow PEP8
from enum import Enum from app import db class AwardCategory(Enum): Champions = 0 Research = 1 Presentation = 2 Innovative_Solution = 3 Mechanical_Design = 4 Programming = 5 Strategy_and_Innovation = 6 Teamwork = 7 Inspiration = 8 Gracious_Professionalism = 9 Robot_Performance = 10 @property def friendly_name(self): return self._name_.replace("_", " ") + " Award" class AwardWinner(db.Model): __tablename__ = 'award_winners' id = db.Column(db.Integer, primary_key=True) team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True) category_id = db.Column(db.Integer) place = db.Column(db.Integer) def __init__(self, team_id=None, category_id=0, place=0): self.team_id = team_id self.category_id = category_id self.place = place @property def friendly_award_name(self): if self.place == 0: place_text = "1st" elif self.place == 1: place_text = "2nd" else: place_text = "3rd" return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
from enum import Enum from app import db class AwardCategory(Enum): Champions = 0 Research = 1 Presentation = 2 Innovative_Solution = 3 Mechanical_Design = 4 Programming = 5 Strategy_and_Innovation = 6 Teamwork = 7 Inspiration = 8 Gracious_Professionalism = 9 Robot_Performance = 10 @property def friendly_name(self): return self._name_.replace("_", " ") + " Award" class AwardWinner(db.Model): __tablename__ = 'award_winners' id = db.Column(db.Integer, primary_key=True) team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True) category_id = db.Column(db.Integer) place = db.Column(db.Integer) def __init__(self, team_id=None, category_id=0, place=0): self.team_id = team_id self.category_id = category_id self.place = place @property def friendly_award_name(self): if self.place==0: place_text = "1st" elif self.place==1: place_text = "2nd" else: place_text = "3rd" return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
Set the required versions of required packages
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wininst upload -r pypi') sys.exit() with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='django-rest-surveys', version='0.1.0', description='A RESTful backend for giving surveys.', long_description=readme, author='Designlab', author_email='hello@trydesignlab.com', url='https://github.com/danxshap/django-rest-surveys', packages=['rest_surveys'], package_data={'': ['LICENSE']}, package_dir={'rest_surveys': 'rest_surveys'}, install_requires=['Django>=1.7', 'djangorestframework>=3.0', 'django-inline-ordering'], license=license, )
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wininst upload -r pypi') sys.exit() with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='django-rest-surveys', version='0.1.0', description='A RESTful backend for giving surveys.', long_description=readme, author='Designlab', author_email='hello@trydesignlab.com', url='https://github.com/danxshap/django-rest-surveys', packages=['rest_surveys'], package_data={'': ['LICENSE']}, package_dir={'rest_surveys': 'rest_surveys'}, install_requires=['Django', 'django-inline-ordering'], license=license, )
Revert "Include Arguments in O.collection" This reverts commit 730f520fa12421e379baa49fa980b157bb003d9f.
var _ = require('_'), overload = require('overload'); // Configure overload to throw type errors overload.prototype.err = function() { throw new TypeError(); }; var _isD = function(val) { return val instanceof D; }; var _isCollection = function(val) { return _isD(val) || _.isArray(val) || _.isNodeList(val); }; overload.defineTypes({ 'D': function(val) { return val && _isD(val); }, 'nodeList': function(val) { return val && _.isNodeList(val); }, 'window': function(val) { return val && val.window === window; }, 'document': function(val) { return val && val === document; }, 'selector': function(val) { return val && (_.isString(val) || _.isFunction(val) || _.isElement(val) || _isCollection(val)); }, 'collection': function(val) { return val && _isCollection(val); } }); module.exports = overload.O;
var _ = require('_'), overload = require('overload'); // Configure overload to throw type errors overload.prototype.err = function() { throw new TypeError(); }; var _isD = function(val) { return val instanceof D; }; var _isCollection = function(val) { return _isD(val) || _.isArray(val) || _.isNodeList(val) || _.isArguments(val); }; overload.defineTypes({ 'D': function(val) { return val && _isD(val); }, 'nodeList': function(val) { return val && _.isNodeList(val); }, 'window': function(val) { return val && val.window === window; }, 'document': function(val) { return val && val === document; }, 'selector': function(val) { return val && (_.isString(val) || _.isFunction(val) || _.isElement(val) || _isCollection(val)); }, 'collection': function(val) { return val && _isCollection(val); } }); module.exports = overload.O;
Change delimiter in flatten function
const fs = require('fs'); const flat = require('flat'); function fixParagraphStructure(originalJSONPath, translatedJSONPath) { const originalJSONFile = fs.readFileSync(originalJSONPath); const originalJSON = flat.flatten(JSON.parse(originalJSONFile), { delimiter: '/' }); const translJSONFile = fs.readFileSync(translatedJSONPath); const translJSON = flat.flatten(JSON.parse(translJSONFile), { delimiter: '/' }); const newTranslatedObj = {}; for (var key in originalJSON) { if (key in translJSON) { newTranslatedObj[key] = translJSON[key]; } else { let root = key.slice(0, key.length - 2); if (root.endsWith('description') && root + '/0' in translJSON) { newTranslatedObj[key] = ''; } else { newTranslatedObj[key] = originalJSON[key]; } } } fs.writeFileSync( translatedJSONPath, JSON.stringify( flat.unflatten(newTranslatedObj, { delimiter: '/' }), undefined, 2 ) ); }
const fs = require('fs'); const flat = require('flat'); function fixParagraphStructure(originalJSONPath, translatedJSONPath) { const originalJSONFile = fs.readFileSync(originalJSONPath); const originalJSON = flat.flatten(JSON.parse(originalJSONFile)); const translJSONFile = fs.readFileSync(translatedJSONPath); const translJSON = flat.flatten(JSON.parse(translJSONFile)); const newTranslatedObj = {}; for (var key in originalJSON) { if (key in translJSON) { newTranslatedObj[key] = translJSON[key]; } else { let root = key.slice(0, key.length - 2); if (root.endsWith('description') && root + '.0' in translJSON) { newTranslatedObj[key] = ''; } else { newTranslatedObj[key] = originalJSON[key]; } } } fs.writeFileSync( translatedJSONPath, JSON.stringify(flat.unflatten(newTranslatedObj), undefined, 2) ); }
Fix example code compilation error Signed-off-by: Edward Wilde <0bbf1c8dffb4cb8ad44cb8eb16480f0eb8bfec44@gmail.com>
package examples import ( "fmt" "github.com/ewilde/go-runscope" ) var accessToken = "{your token}" // See https://www.runscope.com/applications var teamUUID = "{your team uuid}" // See https://www.runscope.com/teams var client = runscope.NewClient(runscope.APIURL, accessToken) func createBucket() *runscope.Bucket { var bucket = &runscope.Bucket{ Name: "My first bucket", Team: &runscope.Team{ ID: teamUUID, }, } bucket, err := client.CreateBucket(bucket) if err != nil { runscope.DebugF(1, "[ERROR] error creating bucket: %s", err) } fmt.Printf("Bucket created successfully: %s", bucket.String()) return bucket } func readBucket() { bucket, err := client.ReadBucket("htqee6p4dhvc") if err != nil { runscope.DebugF(1, "[ERROR] error creating bucket: %s", err) } fmt.Printf("Bucket read successfully: %s", bucket.String()) } func deleteBucket() { err := client.DeleteBucket("htqee6p4dhvc") if err != nil { runscope.DebugF(1, "[ERROR] error creating bucket: %s", err) } }
package examples import ( "fmt" "github.com/ewilde/go-runscope" "log" ) var accessToken = "{your token}" // See https://www.runscope.com/applications var teamUUID = "{your team uuid}" // See https://www.runscope.com/teams var client = runscope.NewClient(runscope.APIURL, accessToken) func createBucket() *runscope.Bucket { var bucket = &runscope.Bucket{ Name: "My first bucket", Team: &runscope.Team{ ID: teamUUID, }, } bucket, err := client.CreateBucket(bucket) if err != nil { DebugF(1, "[ERROR] error creating bucket: %s", err) } fmt.Printf("Bucket created successfully: %s", bucket.String()) return bucket } func readBucket() { bucket, err := client.ReadBucket("htqee6p4dhvc") if err != nil { DebugF(1, "[ERROR] error creating bucket: %s", err) } fmt.Printf("Bucket read successfully: %s", bucket.String()) } func deleteBucket() { err := client.DeleteBucket("htqee6p4dhvc") if err != nil { DebugF(1, "[ERROR] error creating bucket: %s", err) } }
Fix import path of Spinning usage
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Spinning from 'grommet/components/icons/Spinning'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; export default class SpinningDoc extends Component { render () { return ( <DocsArticle title='Spinning'> <section> <p>An indeterminate spinning/busy icon. This should be used sparingly. If at all possible, use Meter with % to indicate progress. For content loading situations, Meter, Chart, and Distribution already have visuals for when the data has not arrived yet. In general, there should not be more than one Spinning icon on the screen at a time.</p> <Spinning /> </section> <section> <h2>Usage</h2> <Code preamble={ `import Spinning from 'grommet/components/icons/Spinning';`}> <Spinning /> </Code> </section> </DocsArticle> ); } };
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Spinning from 'grommet/components/icons/Spinning'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; export default class SpinningDoc extends Component { render () { return ( <DocsArticle title='Spinning'> <section> <p>An indeterminate spinning/busy icon. This should be used sparingly. If at all possible, use Meter with % to indicate progress. For content loading situations, Meter, Chart, and Distribution already have visuals for when the data has not arrived yet. In general, there should not be more than one Spinning icon on the screen at a time.</p> <Spinning /> </section> <section> <h2>Usage</h2> <Code preamble={ `import Spinning from 'grommet/components/Spinning';`}> <Spinning /> </Code> </section> </DocsArticle> ); } };
Add aiohttp.web.Application into type aliases
""" Copyright (c) 2017 Genome Research Ltd. Authors: * Simon Beal <sb48@sanger.ac.uk> * Christopher Harrison <ch12@sanger.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from aiohttp.web import Application # aiohttp web server application from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
""" Copyright (c) 2017 Genome Research Ltd. Authors: * Simon Beal <sb48@sanger.ac.uk> * Christopher Harrison <ch12@sanger.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
:bug: Fix chaining of initialise method
<?php namespace Harp\Timestamps; use Harp\Harp\AbstractModel; /** * @author Ivan Kerin <ikerin@gmail.com> * @copyright 2014, Clippings Ltd. * @license http://spdx.org/licenses/BSD-3-Clause */ trait TimestampsRepoTrait { public function getCurrentDate() { return date('Y-m-d H:i:s'); } public function initializeTimestamps() { $self = $this; return $this ->addEventBeforeSave(function (AbstractModel $model) use ($self) { $model->updatedAt = $self->getCurrentDate(); }) ->addEventBeforeInsert(function (AbstractModel $model) use ($self) { $model->createdAt = $self->getCurrentDate(); }); } }
<?php namespace Harp\Timestamps; use Harp\Harp\AbstractModel; /** * @author Ivan Kerin <ikerin@gmail.com> * @copyright 2014, Clippings Ltd. * @license http://spdx.org/licenses/BSD-3-Clause */ trait TimestampsRepoTrait { public function getCurrentDate() { return date('Y-m-d H:i:s'); } public function initializeTimestamps() { $self = $this; $this ->addEventBeforeSave(function (AbstractModel $model) use ($self) { $model->updatedAt = $self->getCurrentDate(); }) ->addEventBeforeInsert(function (AbstractModel $model) use ($self) { $model->createdAt = $self->getCurrentDate(); }); } }
Change enhanced-resolve to promisified version
'use strict' const fs = require('fs'); const { promisify } = require('util'); const parsePackageString = require('npm-package-arg'); const enhancedResolve = require('enhanced-resolve'); const InstallationUtils = require('./utils/installation-utils'); const getEcmaVersionAST = require('./get-ecma-version-ast.js'); const resolve = promisify(enhancedResolve.create({ mainFields: ['module', 'browser', 'main'], })); function isEcmaVersionModern(ecmaVersion) { return ecmaVersion > 5; } async function getEntryPointEcmaVersion(context, packageName) { const resolvedPath = await resolve(context, packageName); const code = fs.readFileSync(resolvedPath, 'utf8'); // TODO (ISSUE#5) Implement recursive getEntryPointEcmaVersion return getEcmaVersion(code); } async function getPackageEcmaVersion(packageString) { const parsedPackage = parsePackageString(packageString); const installPath = await InstallationUtils.getInstallPath(); await InstallationUtils.installPackage(parsedPackage.name, installPath); const ecmaVersion = await getEntryPointEcmaVersion(installPath, parsedPackage.name); await InstallationUtils.cleanupPath(installPath); return ecmaVersion; } function getEcmaVersion(code) { return getEcmaVersionAST(code); } module.exports = { getEcmaVersion, getPackageEcmaVersion, getEntryPointEcmaVersion, isEcmaVersionModern };
'use strict' const fs = require('fs'); const parsePackageString = require('npm-package-arg'); const enhancedResolve = require('enhanced-resolve'); const InstallationUtils = require('./utils/installation-utils'); const getEcmaVersionAST = require('./get-ecma-version-ast.js'); const resolve = enhancedResolve.create.sync({ modules: ['node_modules'], mainFields: ['browser', 'module', 'main', 'style'], }); function isEcmaVersionModern(ecmaVersion) { return ecmaVersion > 5; } async function getEntryPointEcmaVersion(context, packageName) { const resolvedPath = resolve(context, packageName); const code = fs.readFileSync(resolvedPath, 'utf8'); // TODO (ISSUE#5) Implement recursive getEntryPointEcmaVersion return getEcmaVersion(code); } async function getPackageEcmaVersion(packageString) { const parsedPackage = parsePackageString(packageString); const installPath = await InstallationUtils.getInstallPath(); await InstallationUtils.installPackage(parsedPackage.name, installPath); const ecmaVersion = getEntryPointEcmaVersion(installPath, parsedPackage.name); InstallationUtils.cleanupPath(installPath); return ecmaVersion; } function getEcmaVersion(code) { return getEcmaVersionAST(code); } module.exports = { getEcmaVersion, getPackageEcmaVersion, getEntryPointEcmaVersion, isEcmaVersionModern };
Support Request url in fetch interceptor
import queryString from 'query-string'; import parseUrl from 'parse-url'; import { baseInterceptor } from './baseInterceptor'; import { Response as KakapoResponse } from '../Response'; import { nativeFetch } from '../helpers/nativeServices'; export const name = 'fetch'; export const reference = nativeFetch; const fakeResponse = (response = {}, headers = {}) => { const responseStr = JSON.stringify(response); return new window.Response(responseStr, { headers }); }; export const fakeService = config => baseInterceptor(config, (helpers, url, options = {}) => { url = url instanceof Request ? url.url : url; const body = options.body || ''; const method = options.method || 'GET'; const headers = options.headers || {}; const handler = helpers.getHandler(url, method); const params = helpers.getParams(url, method); if (!handler) { return reference(url, options); } const query = queryString.parse(parseUrl(url).search); const response = handler({ params, query, body, headers }); if (!(response instanceof KakapoResponse)) { return new Promise((resolve) => setTimeout( () => resolve(fakeResponse(response)), config.requestDelay )); } const result = fakeResponse(response.body, response.headers); return new Promise((resolve, reject) => setTimeout( () => { if (response.error) { return reject(result); } return resolve(result); }, config.requestDelay )); });
import queryString from 'query-string'; import parseUrl from 'parse-url'; import { baseInterceptor } from './baseInterceptor'; import { Response as KakapoResponse } from '../Response'; import { nativeFetch } from '../helpers/nativeServices'; export const name = 'fetch'; export const reference = nativeFetch; const fakeResponse = (response = {}, headers = {}) => { const responseStr = JSON.stringify(response); return new window.Response(responseStr, { headers }); }; export const fakeService = config => baseInterceptor(config, (helpers, url, options = {}) => { const body = options.body || ''; const method = options.method || 'GET'; const headers = options.headers || {}; const handler = helpers.getHandler(url, method); const params = helpers.getParams(url, method); if (!handler) { return reference(url, options); } const query = queryString.parse(parseUrl(url).search); const response = handler({ params, query, body, headers }); if (!(response instanceof KakapoResponse)) { return new Promise((resolve) => setTimeout( () => resolve(fakeResponse(response)), config.requestDelay )); } const result = fakeResponse(response.body, response.headers); return new Promise((resolve, reject) => setTimeout( () => { if (response.error) { return reject(result); } return resolve(result); }, config.requestDelay )); });
Use GET request arguments to determine the news source.
import requests from flask import Flask, render_template, request app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") sources = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } def create_link(source): if source in sources.keys(): return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}" @app.route("/") def index(): query = request.args.get("source") if query is None or query.lower() not in sources.keys(): source = "bbc" else: source = query.lower() r = requests.get(create_link(source)) return render_template("index.html", articles=r.json().get("articles"), source=source) if __name__ == "__main__": app.run()
import requests from flask import Flask, render_template app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("appconfig.py") sources = { "bbc": "bbc-news", "cnn": "cnn", "hackernews": "hacker-news" } def create_link(source): if source in sources.keys(): return f"https://newsapi.org/v1/articles?source={sources[source]}&sortBy=top&apiKey={app.config['API_KEY']}" @app.route("/") @app.route("/<source>") def index(source="bbc"): r = requests.get(create_link(source)) return render_template("index.html", articles=r.json().get("articles"), source=source) if __name__ == "__main__": app.run()