text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add newline at end of file
<?php namespace Kevinrob\GuzzleCache\Storage; use Kevinrob\GuzzleCache\CacheEntry; /** * This cache class is backed by a PHP Array. */ class VolatileRuntimeStorage implements CacheStorageInterface { /** * @var CacheEntry[] */ protected $cache = []; /** * @param string $key * * @return CacheEntry|null the data or false */ public function fetch($key) { if (isset($this->cache[$key])) { return $this->cache[$key]; } return; } /** * @param string $key * @param CacheEntry $data * * @return bool */ public function save($key, CacheEntry $data) { $this->cache[$key] = $data; return true; } }
<?php namespace Kevinrob\GuzzleCache\Storage; use Kevinrob\GuzzleCache\CacheEntry; /** * This cache class is backed by a PHP Array. */ class VolatileRuntimeStorage implements CacheStorageInterface { /** * @var CacheEntry[] */ protected $cache = []; /** * @param string $key * * @return CacheEntry|null the data or false */ public function fetch($key) { if (isset($this->cache[$key])) { return $this->cache[$key]; } return; } /** * @param string $key * @param CacheEntry $data * * @return bool */ public function save($key, CacheEntry $data) { $this->cache[$key] = $data; return true; } }
Make Pylint ignore some unused imports Ignore them because they are required for the bot to work
# pylint: disable=unused-import from . import util from . import irc # pylint: enable=unused-import sysver = "".join(__import__("sys").version.split("\n")) gitver = __import__("subprocess").check_output(['git', 'rev-parse', '--short', 'HEAD']).decode().split()[0] version = "A zIRC bot v{0}@{1}, running on Python {2}".format("0.1", gitver, sysver)
from . import util from . import irc sysver = "".join(__import__("sys").version.split("\n")) gitver = __import__("subprocess").check_output(['git', 'rev-parse', '--short', 'HEAD']).decode().split()[0] version = "A zIRC bot v{0}@{1}, running on Python {2}".format("0.1", gitver, sysver)
Set column width by 'resize'.
import Ember from 'ember'; import RegisterTableComponentMixin from 'ember-table/mixins/register-table-component'; export default Ember.View.extend(RegisterTableComponentMixin, { templateName: 'column-sort-indicator', classNames: ['column-sort-indicator', 'sort-indicator-icon'], classNameBindings: ['sortIndicatorStyles'], tagName: 'span', column: null, sortOrder: Ember.computed(function () { var sortingColumns = this.get('tableComponent.sortingColumns'); if (sortingColumns && sortingColumns.get('isMultipleColumns')) { var index = sortingColumns.findOrder(this.get('column')); return index > 0 ? index : ""; } return ""; }).property('tableComponent.sortingColumns._columns'), sortIndicatorStyles: Ember.computed(function () { var sortIndicatorClassMap = { 'asc': 'sort-indicator-icon-up', 'desc': 'sort-indicator-icon-down' }; return sortIndicatorClassMap[this.get('column.sortDirect')] || ''; }).property('column.sortDirect'), width: 18, columnSortDirectionDidChange: Ember.observer('column.sortDirect', function () { var sortIndicatorWidth = this.get('column.sortDirect') ? this.get('width') : 0; this.set('column.sortIndicatorWidth', sortIndicatorWidth); var columnMinWidth = this.get('column.minWidth'); if (columnMinWidth > this.get('column.width')) { this.get('column').resize(columnMinWidth); } }) });
import Ember from 'ember'; import RegisterTableComponentMixin from 'ember-table/mixins/register-table-component'; export default Ember.View.extend(RegisterTableComponentMixin, { templateName: 'column-sort-indicator', classNames: ['column-sort-indicator', 'sort-indicator-icon'], classNameBindings: ['sortIndicatorStyles'], tagName: 'span', column: null, sortOrder: Ember.computed(function () { var sortingColumns = this.get('tableComponent.sortingColumns'); if (sortingColumns && sortingColumns.get('isMultipleColumns')) { var index = sortingColumns.findOrder(this.get('column')); return index > 0 ? index : ""; } return ""; }).property('tableComponent.sortingColumns._columns'), sortIndicatorStyles: Ember.computed(function () { var sortIndicatorClassMap = { 'asc': 'sort-indicator-icon-up', 'desc': 'sort-indicator-icon-down' }; return sortIndicatorClassMap[this.get('column.sortDirect')] || ''; }).property('column.sortDirect'), width: 18, columnSortDirectionDidChange: Ember.observer('column.sortDirect', function () { var sortIndicatorWidth = this.get('column.sortDirect') ? this.get('width') : 0; this.set('column.sortIndicatorWidth', sortIndicatorWidth); var columnMinWidth = this.get('column.minWidth'); if (columnMinWidth > this.get('column.width')) { this.set('column.width', columnMinWidth); } }) });
Create new local $source variable This was done to make clear what we're doing.
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; stream_is_local($file) && ($file = realpath($file)); foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); if (0 !== strpos($file, $prefix)) { continue; } $source = substr($file, strlen($prefix)); $paths[$filter] = $this->cacheManager->cacheImage('', $source, $filter, $force); } return $paths; } }
<?php namespace Avalanche\Bundle\ImagineBundle\Imagine; use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager; class CacheReloader { private $sourceRoot; private $cacheManager; private $filterManager; public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager) { $this->sourceRoot = $sourceRoot; $this->cacheManager = $cacheManager; $this->filterManager = $filterManager; } public function reloadFor($file, $force = false) { $paths = []; stream_is_local($file) && ($file = realpath($file)); foreach ($this->filterManager->getFilterNames() as $filter) { $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot); stream_is_local($prefix) && ($prefix = realpath($prefix)); if (0 !== strpos($file, $prefix)) { continue; } $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force); } return $paths; } }
Hide restart on start page
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; import { withRouter } from 'react-router'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); this.props.history.push('/'); } shouldDisplayRestart() { return window.location.pathname == "/" ? "hide" : ""; } render() { return ( <div className={this.shouldDisplayRestart() + " navbar"}> <a className="restart" onClick={this.restart.bind(this)}><span className="back-icon"><MdBack></MdBack></span> Byrja av nýggjum</a> </div> ); } } const RestartWithRouter = withRouter(Restart); const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(RestartWithRouter);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; import { withRouter } from 'react-router'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); this.props.history.push('/'); } render() { return ( <div className="navbar"> <a className="restart" onClick={this.restart.bind(this)}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); } } const RestartWithRouter = withRouter(Restart); const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(RestartWithRouter);
Add back the Browse button for unauthorized users
import Inferno from 'inferno' import Component from 'inferno-component' import { connect } from 'mobx-connect/inferno' import { Link } from '../../../shared/router' import Menu from '../Common/Menu' @connect class App extends Component { render() { const { account } = this.context.store return <div> {account.isLoggedIn() ? <LoggedInMenu/> : <LoggedOutMenu/>} {this.props.children} </div> } } function LoggedInMenu() { return <Menu> <Link to="/">Browse</Link> <Link to="/about">About</Link> <Link to="/logout">Logout</Link> </Menu> } function LoggedOutMenu() { return <Menu> <Link to="/">Browse</Link> <Link to="/about">About</Link> <Link to="/register">Register</Link> <Link to="/login">Login</Link> </Menu> } export default App
import Inferno from 'inferno' import Component from 'inferno-component' import { connect } from 'mobx-connect/inferno' import { Link } from '../../../shared/router' import Menu from '../Common/Menu' @connect class App extends Component { render() { const { account } = this.context.store return <div> {account.isLoggedIn() ? <LoggedInMenu/> : <LoggedOutMenu/>} {this.props.children} </div> } } function LoggedInMenu() { return <Menu> <Link to="/">Browse</Link> <Link to="/about">About</Link> <Link to="/logout">Logout</Link> </Menu> } function LoggedOutMenu() { return <Menu> <Link to="/about">About</Link> <Link to="/register">Register</Link> <Link to="/login">Login</Link> </Menu> } export default App
Prepare for deploy in deploy script.
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): prepare_deploy() with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
from fabric.api import * from fabric.colors import * env.colorize_errors = True env.hosts = ['sanaprotocolbuilder.me'] env.user = 'root' env.project_root = '/opt/sana.protocol_builder' def prepare_deploy(): local('python sana_builder/manage.py syncdb') local('python sana_builder/manage.py test') local('git push') def deploy(): with cd(env.project_root), prefix('workon sana_protocol_builder'): print(green('Pulling latest revision...')) run('git pull') print(green('Installing dependencies...')) run('pip install -qr requirements.txt') print(green('Migrating database...')) run('python sana_builder/manage.py syncdb') print(green('Restarting gunicorn...')) run('supervisorctl restart gunicorn')
Add version for removing image
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(versions, reverse=True)[4:] for version in obsolete_versions: yield '{}:v{}'.format(image_name, version) def parse_images(lines): images = defaultdict(list) for line in lines: try: image_name, version = line.split(' ') version_num = int(version.replace('v', '')) images[image_name].append(version_num) except ValueError: pass return images def remove_image(image_name): subprocess.check_call(['docker', 'rm', image_name]) def all_images(): output = subprocess \ .check_output(['./docker_image_versions.sh'], shell=True) \ .decode('utf-8') lines = output.split('\n') return parse_images(lines) if __name__ == '__main__': images = all_images() for image_name in find_obsolete_images(images): remove_image(image_name)
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(versions, reverse=True)[4:] for version in obsolete_versions: yield '{}:{}'.format(image_name, version) def parse_images(lines): images = defaultdict(list) for line in lines: try: image_name, version = line.split(' ') version_num = int(version.replace('v', '')) images[image_name].append(version_num) except ValueError: pass return images def remove_image(image_name): subprocess.check_call(['docker', 'rm', image_name]) def all_images(): output = subprocess \ .check_output(['./docker_image_versions.sh'], shell=True) \ .decode('utf-8') lines = output.split('\n') return parse_images(lines) if __name__ == '__main__': images = all_images() for image_name in find_obsolete_images(images): remove_image(image_name)
Add back to index link
import React from 'react'; import connect from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost } from '../actions'; class PostsShow extends React.Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; if (!post) { return ( <div>Loading ...</div> ); } return ( <div> <Link to="/">Back to Index</Link> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost })(PostsShow);
import React from 'react'; import connect from 'react-redux'; import { fetchPost } from '../actions'; class PostsShow extends React.Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; if (!post) { return ( <div>Loading ...</div> ); } return ( <div> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ) } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost })(PostsShow);
Fix doc version 0.7 link
function insert_version_links() { var labels = ['dev', '0.7.0', '0.6', '0.5', '0.4', '0.3']; for (i = 0; i < labels.length; i++){ open_list = '<li>' if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') { if ((DOCUMENTATION_OPTIONS['VERSION'] == labels[i]) || (DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) { open_list = '<li id="current">' } } document.write(open_list); document.write('<a href="URL">skimage VERSION</a> </li>\n' .replace('VERSION', labels[i]) .replace('URL', 'http://skimage.org/docs/' + labels[i])); } }
function insert_version_links() { var labels = ['dev', '0.7', '0.6', '0.5', '0.4', '0.3']; for (i = 0; i < labels.length; i++){ open_list = '<li>' if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') { if ((DOCUMENTATION_OPTIONS['VERSION'] == labels[i]) || (DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) { open_list = '<li id="current">' } } document.write(open_list); document.write('<a href="URL">skimage VERSION</a> </li>\n' .replace('VERSION', labels[i]) .replace('URL', 'http://skimage.org/docs/' + labels[i])); } }
Change incremental action graph experiment back to 90/10 Summary: 50/50 was a bit too aggressive. Will incrementally increase this. Reviewed By: bobyangyf fbshipit-source-id: 02330da
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.config; import com.facebook.buck.util.randomizedtrial.WithProbability; /** * Incremental action graph mode with A/B experiment support. * * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two * runs in a row with the feature enabled to show any effect. */ public enum IncrementalActionGraphMode implements WithProbability { ENABLED(0.1), DISABLED(0.9), EXPERIMENT(0.0), ; public static final IncrementalActionGraphMode DEFAULT = DISABLED; private final double probability; IncrementalActionGraphMode(double probability) { this.probability = probability; } @Override public double getProbability() { return probability; } }
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.config; import com.facebook.buck.util.randomizedtrial.WithProbability; /** * Incremental action graph mode with A/B experiment support. * * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two * runs in a row with the feature enabled to show any effect. */ public enum IncrementalActionGraphMode implements WithProbability { ENABLED(0.5), DISABLED(0.5), EXPERIMENT(0.0), ; public static final IncrementalActionGraphMode DEFAULT = DISABLED; private final double probability; IncrementalActionGraphMode(double probability) { this.probability = probability; } @Override public double getProbability() { return probability; } }
Use correct create annotation permission This has the limitation of hiding the input field in the case where a user has permissions to e.g. flag but not comment, but I suspect those cases are rare and we can address them later if needed.
import React, { Component, PropTypes } from 'react'; import Annotation from './Annotation'; import AddAnnotation from './AddAnnotation'; import Can, { can } from '../Can'; class Annotations extends Component { render() { const props = this.props; return ( <div> <ul className="annotations-list"> {props.annotations.map(function(annotation) { return ( <li><Annotation annotation={annotation.node} annotated={props.annotated} annotatedType={props.annotatedType} /></li> ); })} </ul> {props.annotatedType === 'Media' ? ( // TODO: remove to support Source as well <Can permissions={props.annotated.permissions} permission='create Comment'> <AddAnnotation annotated={props.annotated} annotatedType={props.annotatedType} types={props.types} /> </Can> ) : <AddAnnotation annotated={props.annotated} annotatedType={props.annotatedType} types={props.types} />} </div> ); } } export default Annotations;
import React, { Component, PropTypes } from 'react'; import Annotation from './Annotation'; import AddAnnotation from './AddAnnotation'; import Can, { can } from '../Can'; class Annotations extends Component { render() { const props = this.props; return ( <div> <ul className="annotations-list"> {props.annotations.map(function(annotation) { return ( <li><Annotation annotation={annotation.node} annotated={props.annotated} annotatedType={props.annotatedType} /></li> ); })} </ul> {props.annotatedType === 'Media' ? ( // TODO: remove to support Source as well <Can permissions={props.annotated.permissions} permission={`update ${props.annotatedType}`}> <AddAnnotation annotated={props.annotated} annotatedType={props.annotatedType} types={props.types} /> </Can> ) : <AddAnnotation annotated={props.annotated} annotatedType={props.annotatedType} types={props.types} />} </div> ); } } export default Annotations;
Add IllegalValueException and convert String to int
package seedu.emeraldo.logic.commands; import seedu.emeraldo.commons.exceptions.IllegalValueException; public class EditCommand extends Command{ public static final String COMMAND_WORD = "edit"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the task identified by the index number used in the last tasks listing.\n" + "Parameters: INDEX (must be a positive integer) and \"TASK_DESCRIPTION\"\n" + "Example: " + COMMAND_WORD + " 1" + "CS2103T Week 8 Tutorial"; public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited task: %1$s"; public final int targetIndex; public final String field; public EditCommand(String targetIndex, String field) throws IllegalValueException { this.targetIndex = Integer.parseInt(targetIndex); this.field = field; } @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
package seedu.emeraldo.logic.commands; public class EditCommand extends Command{ public static final String COMMAND_WORD = "edit"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the task identified by the index number used in the last tasks listing.\n" + "Parameters: INDEX (must be a positive integer) and \"TASK_DESCRIPTION\"\n" + "Example: " + COMMAND_WORD + " 1" + "CS2103T Week 8 Tutorial"; public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited task: %1$s"; public final int targetIndex; public final String field; public EditCommand(int targetIndex, String field) { this.targetIndex = targetIndex; this.field = field; } @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
Update algoliasearch requirement to >=1.7.1 (Unreachable host algolia error fix)
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import os import sys if sys.version < '3': execfile(os.path.join('icebergsdk', 'version.py')) else: exec(open("icebergsdk/version.py").read()) install_requires = [] install_requires.append('requests >= 2.3.0') install_requires.append('algoliasearch>=1.7.1') install_requires.append('python-dateutil>=2.4.0') install_requires.append('pytz') setup( name='icebergsdk', version=VERSION, description='Iceberg Marketplace API Client for Python', author='Iceberg', author_email='florian@izberg-marketplace.com', url='https://github.com/Iceberg-Marketplace/Iceberg-API-PYTHON', packages = ["icebergsdk", 'icebergsdk.resources', 'icebergsdk.mixins', 'icebergsdk.utils'], install_requires = install_requires, keywords = ['iceberg', 'modizy', 'marketplace', 'saas'], classifiers = [ "Development Status :: 2 - Pre-Alpha", 'Intended Audience :: Developers', "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import os import sys if sys.version < '3': execfile(os.path.join('icebergsdk', 'version.py')) else: exec(open("icebergsdk/version.py").read()) install_requires = [] install_requires.append('requests >= 2.3.0') install_requires.append('algoliasearch==1.5.9') install_requires.append('python-dateutil>=2.4.0') install_requires.append('pytz') setup( name='icebergsdk', version=VERSION, description='Iceberg Marketplace API Client for Python', author='Iceberg', author_email='florian@izberg-marketplace.com', url='https://github.com/Iceberg-Marketplace/Iceberg-API-PYTHON', packages = ["icebergsdk", 'icebergsdk.resources', 'icebergsdk.mixins', 'icebergsdk.utils'], install_requires = install_requires, keywords = ['iceberg', 'modizy', 'marketplace', 'saas'], classifiers = [ "Development Status :: 2 - Pre-Alpha", 'Intended Audience :: Developers', "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
feat(lib): Add missing top level properties
import Joi from 'joi' import moduleSchema from './properties/module' export const schema = Joi.object({ amd: Joi.any(), bail: Joi.any(), cache: Joi.any(), context: Joi.any(), debug: Joi.any(), devServer: Joi.any(), devtool: Joi.any(), entry: Joi.any(), externals: Joi.any(), loader: Joi.any(), module: moduleSchema, node: Joi.any(), output: Joi.any(), plugins: Joi.any(), profile: Joi.any(), recordsInputPath: Joi.any(), recordsOutputPath: Joi.any(), recordsPath: Joi.any(), resolve: Joi.any(), resolveLoader: Joi.any(), stats: Joi.any(), target: Joi.any(), // Plugins postcss: Joi.any(), eslint: Joi.any(), tslint: Joi.any(), metadata: Joi.any(), })//.unknown() export default function validate(config, schema_ = schema) { const options = { abortEarly: false, } try { Joi.assert(config, schema_, options) } catch (err) { return err } return null }
import Joi from 'joi' import moduleSchema from './properties/module' export const schema = Joi.object({ module: moduleSchema, resolve: Joi.any(), output: Joi.any(), entry: Joi.any(), plugins: Joi.any(), devtool: Joi.any(), externals: Joi.any(), node: Joi.any(), stats: Joi.any(), context: Joi.any(), debug: Joi.any(), devServer: Joi.any(), // Plugins postcss: Joi.any(), eslint: Joi.any(), tslint: Joi.any(), metadata: Joi.any(), })//.unknown() export default function validate(config, schema_ = schema) { const options = { abortEarly: false, } try { Joi.assert(config, schema_, options) } catch (err) { return err } return null }
Support Windows color with ANSICON
<?php namespace mageekguy\atoum; use mageekguy\atoum ; class cli { private static $isTerminal = null; public function __construct(atoum\adapter $adapter = null) { if ($adapter === null) { $adapter = new atoum\adapter(); } if (self::$isTerminal === null) { self::$isTerminal = $adapter->defined('PHP_WINDOWS_VERSION_BUILD') ? (Boolean) $adapter->getenv('ANSICON') : ($adapter->defined('STDOUT') === true && $adapter->function_exists('posix_isatty') === true && $adapter->posix_isatty($adapter->constant('STDOUT')) === true); } } public function setAdapter(atoum\adapter $adapter) { $this->adapter = $adapter; return $this; } public function getAdapter() { return $this->adapter; } public function isTerminal() { return self::$isTerminal; } public static function forceTerminal() { self::$isTerminal = true; } } ?>
<?php namespace mageekguy\atoum; use mageekguy\atoum ; class cli { private static $isTerminal = null; public function __construct(atoum\adapter $adapter = null) { if ($adapter === null) { $adapter = new atoum\adapter(); } if (self::$isTerminal === null) { self::$isTerminal = ($adapter->defined('STDOUT') === true && $adapter->function_exists('posix_isatty') === true && $adapter->posix_isatty($adapter->constant('STDOUT')) === true); } } public function setAdapter(atoum\adapter $adapter) { $this->adapter = $adapter; return $this; } public function getAdapter() { return $this->adapter; } public function isTerminal() { return self::$isTerminal; } public static function forceTerminal() { self::$isTerminal = true; } } ?>
:zap: Add Clock settings to the list of settings
import React, { Component } from 'react'; import Layout from 'react-toolbox/lib/layout/Layout'; import Panel from 'react-toolbox/lib/layout/Panel'; import { Settings as BackgroundSettings } from '@modules/background'; import { Settings as ClockSettings } from '@modules/clock'; class Settings extends Component { render() { return ( <Layout> <Panel> <div style={{ flex: 1, overflowY: 'auto', padding: '1.8rem' }}> <section> <BackgroundSettings /> </section> <section> <ClockSettings /> </section> </div> </Panel> </Layout> ); } } export default Settings
import React, { Component } from 'react'; import Layout from 'react-toolbox/lib/layout/Layout'; import Panel from 'react-toolbox/lib/layout/Panel'; import { Settings as BackgroundSettings } from '@modules/background'; class Settings extends Component { render() { return ( <Layout> <Panel> <div style={{ flex: 1, overflowY: 'auto', padding: '1.8rem' }}> <section> <BackgroundSettings /> </section> </div> </Panel> </Layout> ); } } export default Settings
Set CI_ENVIRONMENT before return false if uri is /index.php
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with serve.php to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. */ // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $path = __DIR__.'/public/'.ltrim($uri,'/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. require_once __DIR__.'/public/index.php';
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with serve.php to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. */ $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $path = __DIR__.'/public/'.ltrim($uri,'/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; require_once __DIR__.'/public/index.php';
fix: Save position on zero start
import _ from 'lodash' export function saveCursorPosition ({ target }) { if (target.selectionStart !== void 0) { return target.selectionStart } if (document.selection) { // IE support target.focus() // To get cursor position, get empty selection range const selectionRange = document.selection.createRange() // Move selection start to 0 position selectionRange.moveStart('character', -target.value.length) // The cursor position is selection length return selectionRange.text.length } return 0 } export function restoreCursorPosition (target, cursorPosition) { if (!target || _.isNil(cursorPosition)) { return } if ((target.type === 'text' || target.type === 'textarea') && target === document.activeElement) { if (target.setSelectionRange) { target.setSelectionRange(cursorPosition, cursorPosition) } else if (target.createTextRange) { const range = target.createTextRange() range.collapse(true) range.moveStart('character', cursorPosition) range.moveEnd('character', cursorPosition) range.select() } } }
import _ from 'lodash' export function saveCursorPosition ({ target }) { if (target.selectionStart) { return target.selectionStart } if (document.selection) { // IE support target.focus() // To get cursor position, get empty selection range const selectionRange = document.selection.createRange() // Move selection start to 0 position selectionRange.moveStart('character', -target.value.length) // The cursor position is selection length return selectionRange.text.length } return 0 } export function restoreCursorPosition (target, cursorPosition) { if (!target || _.isNil(cursorPosition)) { return } if ((target.type === 'text' || target.type === 'textarea') && target === document.activeElement) { if (target.setSelectionRange) { target.setSelectionRange(cursorPosition, cursorPosition) } else if (target.createTextRange) { const range = target.createTextRange() range.collapse(true) range.moveStart('character', cursorPosition) range.moveEnd('character', cursorPosition) range.select() } } }
Add back quotes that are needed due to hyphens.
// FIXME add map for noconflict - cf requirejs docs requirejs.config({ baseUrl: "js/vendor", paths: { "app": "..", "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min", "angular": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular", "angular-route": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-route", "angular-animate": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-animate", "perfect-scrollbar": "perfect-scrollbar.min", "angular-perfect-scrollbar": "angular-perfect-scrollbar" }, shim: { "angular-route": { deps: ['angular'] }, "angular-animate": { deps: ['angular'] }, "perfect-scrollbar": { deps: ['jquery'] }, "angular-perfect-scrollbar": { deps: ['perfect-scrollbar', 'angular'] } } }); // Load the main app module to start the app requirejs(["app/main"]);
// FIXME add map for noconflict - cf requirejs docs requirejs.config({ baseUrl: "js/vendor", paths: { app: "..", jquery: "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min", angular: "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular", angular-route: "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-route", angular-animate: "//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular-animate", perfect-scrollbar: "perfect-scrollbar.min", angular-perfect-scrollbar: "angular-perfect-scrollbar" }, shim: { angular-route: { deps: ['angular'] }, angular-animate: { deps: ['angular'] }, perfect-scrollbar: { deps: ['jquery'] }, angular-perfect-scrollbar: { deps: ['perfect-scrollbar', 'angular'] } } }); // Load the main app module to start the app requirejs(["app/main"]);
Add avddlen property to Collection
from collections import defaultdict class Collection(object): DOC_FROM = ["question_body", "best_answer_body"] def __init__(self): ''' Compute the following statistics df: document frequency cf: collection frequency dn: total number of documents cn: total number of words ''' self.df = defaultdict(int) self.cf = defaultdict(int) self.dn = 0 self.cn = 0 def add(self, wordsets): ''' Add a question ''' for label in self.DOC_FROM: for w in set(wordsets[label].keys()): self.df[w] += 1 self.cf[w] += wordsets[label][w] self.cn += wordsets[label][w] self.dn += 1 @property def avgdlen(self): return float(self.cn) / self.dn
from collections import defaultdict class Collection(object): DOC_FROM = ["question_body", "best_answer_body"] def __init__(self): ''' Compute the following statistics df: document frequency cf: collection frequency dn: total number of documents cn: total number of words ''' self.df = defaultdict(int) self.cf = defaultdict(int) self.dn = 0 self.cn = 0 def add(self, wordsets): ''' Add a question ''' for label in self.DOC_FROM: for w in set(wordsets[label].keys()): self.df[w] += 1 self.cf[w] += wordsets[label][w] self.cn += wordsets[label][w] self.dn += 1
Update iceConnectionState.connected to trigger the connected state, instead of connecting
var humps = require('humps'); var STATUS_CONNECTING = 'connecting', STATUS_CONNECTED = 'connected', STATUS_DISCONNECTED = 'disconnected', STATUS_ERROR = 'error', STATUS_CLOSED = 'closed', STATUS_UNKNOWN = 'unknown'; var statusMappings = { 'new': STATUS_CONNECTING, 'checking': STATUS_CONNECTING, 'connected': STATUS_CONNECTED, 'completed': STATUS_CONNECTED, 'failed': STATUS_ERROR, 'disconnected': STATUS_DISCONNECTED, 'closed': STATUS_CLOSED }; exports.connectionId = function(source, target) { return (source < target ? source + ':' + target : target + ':' + source); } exports.toStatus = function(iceConnectionState) { if (!iceConnectionState) return STATUS_UNKNOWN; var status = statusMappings[iceConnectionState.toLowerCase()]; return status || STATUS_UNKNOWN; } exports.standardizeKey = function(prefix, key) { if (!key) return key; var normalized = key; if (key.indexOf(prefix) === 0) { normalized = key.replace(prefix, ''); } return humps.camelize(normalized); } exports.SIGNALLER_EVENTS = ['init', 'open', 'connected', 'disconnected', 'error'];
var humps = require('humps'); var STATUS_CONNECTING = 'connecting', STATUS_CONNECTED = 'connected', STATUS_DISCONNECTED = 'disconnected', STATUS_ERROR = 'error', STATUS_CLOSED = 'closed', STATUS_UNKNOWN = 'unknown'; var statusMappings = { 'new': STATUS_CONNECTING, 'checking': STATUS_CONNECTING, 'connected': STATUS_CONNECTING, 'completed': STATUS_CONNECTED, 'failed': STATUS_ERROR, 'disconnected': STATUS_DISCONNECTED, 'closed': STATUS_CLOSED }; exports.connectionId = function(source, target) { return (source < target ? source + ':' + target : target + ':' + source); } exports.toStatus = function(iceConnectionState) { if (!iceConnectionState) return STATUS_UNKNOWN; var status = statusMappings[iceConnectionState.toLowerCase()]; return status || STATUS_UNKNOWN; } exports.standardizeKey = function(prefix, key) { if (!key) return key; var normalized = key; if (key.indexOf(prefix) === 0) { normalized = key.replace(prefix, ''); } return humps.camelize(normalized); } exports.SIGNALLER_EVENTS = ['init', 'open', 'connected', 'disconnected', 'error'];
Update simple demo for latest Coquette.
;(function(exports) { var Game = function(canvasId, width, height, autoFocus) { var coq = new Coquette(this, canvasId, width, height, "#000", autoFocus); coq.entities.create(Person, { pos:{ x:250, y:40 }, color:"#099" }); // paramour coq.entities.create(Person, { pos:{ x:256, y:110 }, color:"#f07", // player update: function() { if (coq.inputter.down(coq.inputter.UP_ARROW)) { this.pos.y -= 0.4; } }, collision: function(other) { other.pos.y = this.pos.y; // follow the player } }); }; var Person = function(_, settings) { for (var i in settings) { this[i] = settings[i]; } this.size = { x:9, y:9 }; this.draw = function(ctx) { ctx.fillStyle = settings.color; ctx.fillRect(this.pos.x, this.pos.y, this.size.x, this.size.y); }; }; exports.Game = Game; })(this);
;(function(exports) { var Game = function(canvasId, width, height, autoFocus) { var coq = new Coquette(this, canvasId, width, height, "#000", autoFocus); coq.entities.create(Person, { pos:{ x:243, y:40 }, color:"#099" }); // paramour coq.entities.create(Person, { pos:{ x:249, y:110 }, color:"#f07", // player update: function() { if (coq.inputter.state(coq.inputter.UP_ARROW)) { this.pos.y -= 0.4; } }, collision: function(other) { other.pos.y = this.pos.y; // follow the player } }); }; var Person = function(_, settings) { for (var i in settings) { this[i] = settings[i]; } this.size = { x:9, y:9 }; this.draw = function(ctx) { ctx.fillStyle = settings.color; ctx.fillRect(this.pos.x, this.pos.y, this.size.x, this.size.y); }; }; exports.Game = Game; })(this);
fix(transformation): Fix the problem where the file field is empty after asset transformation the sync tool was not able to process assets correctly due to a wrong transformation done the asset closes #68
import { omit, pick } from 'lodash/object' import { find, reduce } from 'lodash/collection' /** * Default transformer methods for each kind of entity. * * In the case of assets it also changes the asset url to the upload property * as the whole upload process needs to be followed again. */ export function contentTypes (contentType) { return contentType } export function entries (entry) { return entry } export function assets (asset) { const transformedAsset = omit(asset, 'sys') transformedAsset.sys = pick(asset.sys, 'id') transformedAsset.fields = pick(asset.fields, 'title', 'description') transformedAsset.fields.file = reduce( asset.fields.file, (newFile, file, locale) => { newFile[locale] = omit(file, 'url', 'details') newFile[locale].upload = 'http:' + file.url return newFile }, {} ) return transformedAsset } export function locales (locale, destinationLocales) { const transformedLocale = pick(locale, 'code', 'name', 'contentManagementApi', 'contentDeliveryApi', 'fallback_code', 'optional') const destinationLocale = find(destinationLocales, {code: locale.code}) if (destinationLocale) { transformedLocale.sys = pick(destinationLocale.sys, 'id') } return transformedLocale }
import { omit, pick } from 'lodash/object' import { find, reduce } from 'lodash/collection' /** * Default transformer methods for each kind of entity. * * In the case of assets it also changes the asset url to the upload property * as the whole upload process needs to be followed again. */ export function contentTypes (contentType) { return contentType } export function entries (entry) { return entry } export function assets (asset) { asset.fields = pick(asset.fields, 'title', 'description') asset.fields.file = reduce( asset.fields.file, (newFile, file, locale) => { newFile[locale] = omit(file, 'url', 'details') newFile[locale].upload = 'https:' + file.url return newFile }, {} ) return asset } export function locales (locale, destinationLocales) { const transformedLocale = pick(locale, 'code', 'name', 'contentManagementApi', 'contentDeliveryApi', 'fallback_code', 'optional') const destinationLocale = find(destinationLocales, {code: locale.code}) if (destinationLocale) { transformedLocale.sys = pick(destinationLocale.sys, 'id') } return transformedLocale }
Use $.ajax instead of $.get $.get doesn't support options
import Ember from 'ember'; import TravisRoute from 'travis/routes/basic'; import config from 'travis/config/environment'; export default TravisRoute.extend({ needsAuth: false, titleToken(model) { var name = model.name || model.login; return name; }, model(params, transition) { var options; options = {}; if (this.get('auth.signedIn')) { options.headers = { Authorization: "token " + (this.auth.token()) }; } let includes = `?include=owner.repositories,repository.default_branch,build.commit,repository.current_build`; let { owner } = transition.params.owner; let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`; return Ember.$.ajax(url, options); } });
import Ember from 'ember'; import TravisRoute from 'travis/routes/basic'; import config from 'travis/config/environment'; export default TravisRoute.extend({ needsAuth: false, titleToken(model) { var name = model.name || model.login; return name; }, model(params, transition) { var options; options = {}; if (this.get('auth.signedIn')) { options.headers = { Authorization: "token " + (this.auth.token()) }; } let includes = `?include=owner.repositories,repository.default_branch,build.commit,repository.current_build`; let { owner } = transition.params.owner; let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`; return Ember.$.get(url, options); } });
Use 0px string instead of number 0 for CSS
define( 'ephox.dragster.detect.Blocker', [ 'ephox.dragster.style.Styles', 'ephox.highway.Merger', 'ephox.sugar.api.Class', 'ephox.sugar.api.Css', 'ephox.sugar.api.Element', 'ephox.sugar.api.Remove' ], function (Styles, Merger, Class, Css, Element, Remove) { return function (options) { var settings = Merger.merge({ 'layerClass': Styles.resolve('blocker') }, options); var div = Element.fromTag('div'); Css.setAll(div, { position: 'fixed', left: '0px', top: '0px', width: '100%', height: '100%' }); Class.add(div, Styles.resolve('blocker')); Class.add(div, settings.layerClass); var element = function () { return div; }; var destroy = function () { Remove.remove(div); }; return { element: element, destroy: destroy }; }; } );
define( 'ephox.dragster.detect.Blocker', [ 'ephox.dragster.style.Styles', 'ephox.highway.Merger', 'ephox.sugar.api.Class', 'ephox.sugar.api.Css', 'ephox.sugar.api.Element', 'ephox.sugar.api.Remove' ], function (Styles, Merger, Class, Css, Element, Remove) { return function (options) { var settings = Merger.merge({ 'layerClass': Styles.resolve('blocker') }, options); var div = Element.fromTag('div'); Css.setAll(div, { position: 'fixed', left: 0, top: 0, width: '100%', height: '100%' }); Class.add(div, Styles.resolve('blocker')); Class.add(div, settings.layerClass); var element = function () { return div; }; var destroy = function () { Remove.remove(div); }; return { element: element, destroy: destroy }; }; } );
Fix a Bad Codemod Import
import { isEmpty } from '@ember/utils'; import { helper } from '@ember/component/helper'; import { htmlSafe } from '@ember/string'; import jquery from 'jquery'; import markdownit from 'markdown-it'; import markdownItAttrs from 'markdown-it-attrs'; function defuckifyHTML(domNodes) { if (!domNodes) { return ''; } else { let container = jquery('<span>'); jquery.each(domNodes, function(_, val) { container.append(val); }); return container.html(); } } function targetLinks(html) { let origin = window.location.origin; let nodes = jquery.parseHTML(html); jquery(`a[href^='mailto'], a[href^='http']:not([href^='${origin}'])`, nodes) .attr('target', '_blank') .attr('rel', 'noopener noreferrer'); return defuckifyHTML(nodes); } export function renderMarkdown([raw]) { const renderer = markdownit({ html: true }); renderer.use(markdownItAttrs); if (isEmpty(raw)) { return ''; } else { let html = renderer.render(raw); html = targetLinks(html); return htmlSafe(html); } } export default helper(renderMarkdown);
import { isEmpty } from '@ember/utils'; import { helper } from '@ember/component/helper'; import { htmlSafe } from '@ember/template'; import jquery from 'jquery'; import markdownit from 'markdown-it'; import markdownItAttrs from 'markdown-it-attrs'; function defuckifyHTML(domNodes) { if (!domNodes) { return ''; } else { let container = jquery('<span>'); jquery.each(domNodes, function(_, val) { container.append(val); }); return container.html(); } } function targetLinks(html) { let origin = window.location.origin; let nodes = jquery.parseHTML(html); jquery(`a[href^='mailto'], a[href^='http']:not([href^='${origin}'])`, nodes) .attr('target', '_blank') .attr('rel', 'noopener noreferrer'); return defuckifyHTML(nodes); } export function renderMarkdown([raw]) { const renderer = markdownit({ html: true }); renderer.use(markdownItAttrs); if (isEmpty(raw)) { return ''; } else { let html = renderer.render(raw); html = targetLinks(html); return htmlSafe(html); } } export default helper(renderMarkdown);
Remove turning parameters into trailing data automatically
/** * Represents an IRC message. * * @param {string|Object|null} prefix Message prefix. (Optional.) * @param {string} command Command name. * @param {Array.<string>} parameters IRC Command parameters. * * @constructor */ export default function Message (prefix, command, parameters) { if (!(this instanceof Message)) return new Message(prefix, command, parameters) if (prefix && typeof prefix.mask === 'function') { prefix = prefix.mask() } /** * Message Prefix. Basically just the sender nickmask. * @member {string} */ this.prefix = prefix /** * Command, i.e. what this message actually means to us! * @member {string} */ this.command = command /** * Parameters given to this command. * @member {Array.<string>} */ this.parameters = parameters } /** * Compiles the message back down into an IRC command string. * * @return {string} IRC command. */ Message.prototype.toString = function () { return (this.prefix ? `:${this.prefix} ` : '') + this.command + (this.parameters.length ? ` ${this.parameters.join(' ')}` : '') }
/** * Represents an IRC message. * * @param {string|Object|null} prefix Message prefix. (Optional.) * @param {string} command Command name. * @param {Array.<string>} parameters IRC Command parameters. * * @constructor */ export default function Message (prefix, command, parameters) { if (!(this instanceof Message)) return new Message(prefix, command, parameters) if (prefix && typeof prefix.mask === 'function') { prefix = prefix.mask() } /** * Message Prefix. Basically just the sender nickmask. * @member {string} */ this.prefix = prefix /** * Command, i.e. what this message actually means to us! * @member {string} */ this.command = command /** * Parameters given to this command. * @member {Array.<string>} */ this.parameters = parameters } /** * Compiles the message back down into an IRC command string. * * @return {string} IRC command. */ Message.prototype.toString = function () { let parameters = this.parameters.slice(0) // prefix last parameter by : so it becomes trailing data if (parameters.length) { let last = parameters[parameters.length - 1] if (last && last.indexOf(' ') !== -1) { parameters[parameters.length - 1] = `:${parameters[parameters.length - 1]}` } } return (this.prefix ? `:${this.prefix} ` : '') + this.command + (parameters.length ? ` ${parameters.join(' ')}` : '') }
Write logs to Application Storage to avoid permission problem on Android 6+
package config; import android.content.Context; import cl_toolkit.Logger; import cl_toolkit.Storage; /** * Run-time data * @author Chris Lewis */ public class Runtime { private static Logger getLogger(Context context) { return new Logger(Storage.getAppStorage(context) + "/" + Build.DEBUG_LOG_NAME, Build.DEBUG_LOG_MAX_SIZE_BYTES); } public static void log(Context context, String TAG, String message, String level) { getLogger(context).log(TAG, message, level); } public static void logStackTrace(Context context, Exception e) { getLogger(context).logStackTrace(e); } public static void startNewSession(Context context) { getLogger(context).startNewSession(); } }
package config; import android.content.Context; import cl_toolkit.Logger; import cl_toolkit.Storage; /** * Run-time data * @author Chris Lewis */ public class Runtime { private static Logger getLogger(Context context) { return new Logger(Storage.getStorage() + "/" + Build.DEBUG_LOG_NAME, Build.DEBUG_LOG_MAX_SIZE_BYTES); } public static void log(Context context, String TAG, String message, String level) { getLogger(context).log(TAG, message, level); } public static void logStackTrace(Context context, Exception e) { getLogger(context).logStackTrace(e); } public static void startNewSession(Context context) { getLogger(context).startNewSession(); } }
Fix icon (SVG was being rendered HUGE in WebStorm)
package org.frawa.elmtest.run; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; import org.elm.ide.icons.ElmIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class ElmTestConfigurationFactory extends ConfigurationFactory { private static final String FACTORY_NAME = "Elm Test configuration factory"; static final Icon RUN_ICON = ElmIcons.INSTANCE.getCOLORFUL(); ElmTestConfigurationFactory(ConfigurationType type) { super(type); } @NotNull @Override public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new ElmTestRunConfiguration(project, this, "Elm Test"); } @Override public String getName() { return FACTORY_NAME; } @Nullable @Override public Icon getIcon() { return RUN_ICON; } }
package org.frawa.elmtest.run; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class ElmTestConfigurationFactory extends ConfigurationFactory { private static final String FACTORY_NAME = "Elm Test configuration factory"; static final Icon RUN_ICON = IconLoader.getIcon("/icons/elm-colorful-original.svg"); ElmTestConfigurationFactory(ConfigurationType type) { super(type); } @NotNull @Override public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new ElmTestRunConfiguration(project, this, "Elm Test"); } @Override public String getName() { return FACTORY_NAME; } @Nullable @Override public Icon getIcon() { return RUN_ICON; } }
Print out help menu when incorrect argument is given
#! /usr/bin/env node /* global require, process */ var program = require('commander'), fs = require('fs'), cwd = process.cwd(), cliPath = cwd + '/node_modules/wee-core/cli.js'; // Register version and init command program .version(require('../package').version) .usage('<command> [options]') .command('init [name]', 'create a new project'); // TODO: Finish init command // Set help as default command if nothing found program .on('*', () => { program.outputHelp(); }); fs.stat(cliPath, function(err) { if (err !== null) { fs.stat('./package.json', function(err) { if (err !== null) { console.log('Wee package.json not found in current directory'); return; } fs.readFile('./package.json', function(err, data) { if (err) { console.log(err); return; } // Check for valid Wee installation var config = JSON.parse(data); if (config.name == 'wee-framework' || config.name == 'wee') { console.log('Run "npm install" to install Wee core'); } else { console.log('The package.json is not compatible with Wee'); } }); }); return; } // Register all other commands from specific project require(cliPath)(cwd, program); // Process cli input and execute command program.parse(process.argv); });
#! /usr/bin/env node /* global require, process */ var program = require('commander'), fs = require('fs'), cwd = process.cwd(), cliPath = cwd + '/node_modules/wee-core/cli.js'; // Register version and init command program .version(require('../package').version) .usage('<command> [options]') .command('init [name]', 'create a new project'); fs.stat(cliPath, function(err) { if (err !== null) { fs.stat('./package.json', function(err) { if (err !== null) { console.log('Wee package.json not found in current directory'); return; } fs.readFile('./package.json', function(err, data) { if (err) { console.log(err); return; } // Check for valid Wee installation var config = JSON.parse(data); if (config.name == 'wee-framework' || config.name == 'wee') { console.log('Run "npm install" to install Wee core'); } else { console.log('The package.json is not compatible with Wee'); } }); }); return; } // Register all other commands from specific project require(cliPath)(cwd, program); // Process cli input and execute command program.parse(process.argv); });
Use 1212 as the default port
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
Add missing package requirement of argparse.
#!/usr/bin/env python from setuptools import setup, find_packages from cron_sentry.version import VERSION setup( name='cron-sentry', version=VERSION, author='Yipit Coders', author_email='coders@yipit.com', description='Cron-Sentry is a command-line wrapper that reports unsuccessful runs to Sentry (https://www.getsentry.com)', long_description=open('README.md').read(), license='MIT', classifiers=[ 'Topic :: Utilities', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], url='http://github.com/yipit/cron-sentry', packages=find_packages(), install_requires=['raven', 'argparse'], data_files=[], entry_points={ 'console_scripts': [ # `raven-cron` entry point is for backwards compatibility purposes. # it should get removed in future releases 'raven-cron = cron_sentry.runner:run', 'cron-sentry = cron_sentry.runner:run', ] } )
#!/usr/bin/env python from setuptools import setup, find_packages from cron_sentry.version import VERSION setup( name='cron-sentry', version=VERSION, author='Yipit Coders', author_email='coders@yipit.com', description='Cron-Sentry is a command-line wrapper that reports unsuccessful runs to Sentry (https://www.getsentry.com)', long_description=open('README.md').read(), license='MIT', classifiers=[ 'Topic :: Utilities', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], url='http://github.com/yipit/cron-sentry', packages=find_packages(), install_requires=['raven'], data_files=[], entry_points={ 'console_scripts': [ # `raven-cron` entry point is for backwards compatibility purposes. # it should get removed in future releases 'raven-cron = cron_sentry.runner:run', 'cron-sentry = cron_sentry.runner:run', ] } )
Comment as to why there is a test for an interface
<?php namespace com\xcitestudios\Generic\Test\Data\Manipulation\Interfaces; class SerializationInterfaceTest extends \PHPUnit_Framework_TestCase { /** * While testing an interface is pointless, it was a way of giving an example of how * to implement the interface and ensure the example remains valid! */ public function testSerialization() { $testObject = new \stdClass(); $testObject->a = 5; $testObject->b = 's'; $obj = new SerializationInterfaceTestClass(); $obj->setFloatA(1.1); $obj->setIntA(5); $obj->setObjA($testObject); $obj->setStringA('stringy'); $string = $obj->serialize(); $this->assertInternalType('string', $string); $newObj = new SerializationInterfaceTestClass(); $newObj->deserialize($string); $this->assertEquals($obj->getFloatA(), $newObj->getFloatA()); $this->assertEquals($obj->getIntA(), $newObj->getIntA()); $this->assertEquals($obj->getStringA(), $newObj->getStringA()); $this->assertEquals($obj->getObjA(), $newObj->getObjA()); } }
<?php namespace com\xcitestudios\Generic\Test\Data\Manipulation\Interfaces; class SerializationInterfaceTest extends \PHPUnit_Framework_TestCase { public function testSerialization() { $testObject = new \stdClass(); $testObject->a = 5; $testObject->b = 's'; $obj = new SerializationInterfaceTestClass(); $obj->setFloatA(1.1); $obj->setIntA(5); $obj->setObjA($testObject); $obj->setStringA('stringy'); $string = $obj->serialize(); $this->assertInternalType('string', $string); $newObj = new SerializationInterfaceTestClass(); $newObj->deserialize($string); $this->assertEquals($obj->getFloatA(), $newObj->getFloatA()); $this->assertEquals($obj->getIntA(), $newObj->getIntA()); $this->assertEquals($obj->getStringA(), $newObj->getStringA()); $this->assertEquals($obj->getObjA(), $newObj->getObjA()); } }
Add quotes around the npm_execpath [fixes #19]
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((('"' + process.env.npm_execpath + '"') || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((process.env.npm_execpath || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
Modify the version numbering guideline.
"""The top-level Quantitative Imaging Pipeline module.""" __version__ = '4.5.3' """ The one-based major.minor.patch version. The version numbering scheme loosely follows http://semver.org/. The major version is incremented when a significant feature set is introduced. The minor version is incremented when there is a functionality change. The patch version is incremented when there is a refactoring or bug fix. All major, minor and patch version numbers begin at 1. """ def project(name=None): """ Gets or sets the current XNAT project name. The default project name is ``QIN``. :param name: the XNAT project name to set, or None to get the current project name :return: the current XNAT project name """ if name: project.name = name elif not hasattr(project, 'name'): project.name = None return project.name or 'QIN'
"""The top-level Quantitative Imaging Pipeline module.""" __version__ = '4.5.3' """ The one-based major.minor.patch version. The version numbering scheme loosely follows http://semver.org/. The major version is incremented when there is an incompatible public API change. The minor version is incremented when there is a backward-compatible functionality change. The patch version is incremented when there is a backward-compatible refactoring or bug fix. All major, minor and patch version numbers begin at 1. """ def project(name=None): """ Gets or sets the current XNAT project name. The default project name is ``QIN``. :param name: the XNAT project name to set, or None to get the current project name :return: the current XNAT project name """ if name: project.name = name elif not hasattr(project, 'name'): project.name = None return project.name or 'QIN'
Fix the response dest from `msg.from` User to `msg.chat` Chat.
const TelegramBot = require( 'node-telegram-bot-api' ); const CONFIG = require( './src/config' ); const message = require( './src/message' ); const { token, settings, telegram } = CONFIG; const URL = `${ telegram.host }:${ telegram.port }/bot${ token }`; const bot = new TelegramBot( token, settings ); bot.setWebHook( URL ); // /start bot.onText( message.type.start.regexp, ( msg ) => { const id = msg.chat.id; const { resp, options } = message.type.start; bot.sendMessage( id, resp, options ); }); function commonRollHandler( type, msg, match ) { const id = msg.chat.id; const username = msg.from ? msg.from.username : msg.chat.username; try { const { resp, options } = message.getMessageBody( type, username, match[ 2 ]); bot.sendMessage( id, resp, options ); } catch ( err ) { bot.sendMessage( id, message.getErrorMessage( username )); } } // /roll /sroll /droll /random [ 'roll', 'sroll', 'droll', 'random' ].forEach(( type ) => { bot.onText( message.type[ type ].regexp, commonRollHandler.bind( null, type )); });
const TelegramBot = require( 'node-telegram-bot-api' ); const CONFIG = require( './src/config' ); const message = require( './src/message' ); const dice = require( './src/dice' ); const { token, settings, telegram } = CONFIG; const URL = `${ telegram.host }:${ telegram.port }/bot${ token }`; const bot = new TelegramBot( token, settings ); bot.setWebHook( URL ); // /start bot.onText( message.type.start.regexp, ( msg ) => { const fromId = msg.from.id; const { resp, options } = message.type.start; bot.sendMessage( fromId, resp, options ); }); function commonRollHandler( type, msg, match ) { const { id, username } = msg.from; try { const { resp, options } = message.getMessageBody( type, username, match[ 2 ]); bot.sendMessage( id, resp, options ); } catch ( err ) { bot.sendMessage( id, message.getErrorMessage( username )); } } // /roll /sroll /droll /random [ 'roll', 'sroll', 'droll', 'random' ].forEach(( type ) => { bot.onText( message.type[ type ].regexp, commonRollHandler.bind( null, type )); });
Use async patterns for max-xp command.
const {Command} = require('./index.js'); const maxXpOptions = { description: 'Get your top 10 *max-xp* values.', passRecord: true, signatures: ['@BOTNAME max-xp'] }; const unknownTank = { name: 'Unknown vehicle', tier: '-', nation: '-' }; module.exports = new Command(maxXpFn, maxXpOptions, 'max-xp'); async function maxXpFn(msg, record) { const data = await this.wotblitz.tanks.stats(record.account_id, null, null, null, [ 'tank_id', 'all.max_xp' ]); const stats = data[record.account_id].sort((a, b) => b.all.max_xp - a.all.max_xp).slice(0, 10); const vehicles = await this.wotblitz.encyclopedia.vehicles(stats.map(stat => stat.tank_id), null, [ 'name', 'tier', 'nation' ]); const text = stats.map(({tank_id, all: {max_xp}}, i) => { const vehicle = Object.assign({}, unknownTank, vehicles[tank_id]); const position = i + 1; return `${position}, ${max_xp} xp: ${vehicle.name} (${vehicle.nation}, ${vehicle.tier})`; }); const sent = await msg.reply(text.join('\n')); return {sentMsg: sent}; }
const {Command} = require('./index.js'); const maxXpOptions = { description: 'Get your top 10 *max-xp* values.', passRecord: true, signatures: ['@BOTNAME max-xp'] }; const unknownTank = { name: 'Unknown vehicle', tier: '-', nation: '-' }; module.exports = new Command(maxXpFn, maxXpOptions, 'max-xp'); function maxXpFn(msg, record) { return this.wotblitz.tanks.stats(record.account_id, null, null, null, ['tank_id', 'all.max_xp']) .then(data => data[record.account_id]) .then(stats => stats.sort((a, b) => b.all.max_xp - a.all.max_xp).slice(0, 10)) .then(top10 => { return this.wotblitz.encyclopedia.vehicles(top10.map(x => x.tank_id), null, ['name', 'tier', 'nation']) .then(vehicles => top10.map(x => Object.assign(x.all, unknownTank, vehicles[x.tank_id]))); }) .then(data => msg.reply(data.map((d, i) => `${i + 1}, ${d.max_xp} xp: ${d.name} (${d.nation}, ${d.tier})`).join('\n'))) .then(sent => ({sentMsg: sent})); }
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows" This reverts commit d87c71142ba7bcc0d99d84886f3534dea7617b0c.
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins if os.environ.has_key('MAPNIK_INPUT_PLUGINS_DIRECTORY'): settings_dict['input_plugins'] = os.environ['MAPNIK_INPUT_PLUGINS_DIRECTORY'] else: settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() if os.environ.has_key('MAPNIK_FONT_DIRECTORY'): settings_dict['fonts'] = os.environ['MAPNIK_FONT_DIRECTORY'] else: settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
import os settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js') # this goes into a mapnik_settings.js file beside the C++ _mapnik.node settings_template = """ module.exports.paths = { 'fonts': %s, 'input_plugins': %s }; """ def write_mapnik_settings(fonts='undefined',input_plugins='undefined'): global settings_template if '__dirname' in fonts or '__dirname' in input_plugins: settings_template = "var path = require('path');\n" + settings_template open(settings,'w').write(settings_template % (fonts,input_plugins)) if __name__ == '__main__': settings_dict = {} # settings for fonts and input plugins settings_dict['input_plugins'] = '\'%s\'' % os.popen("mapnik-config --input-plugins").readline().strip() settings_dict['fonts'] = '\'%s\'' % os.popen("mapnik-config --fonts").readline().strip() write_mapnik_settings(**settings_dict)
config-perf: Enable port list optimization by default for new install+provision From R1.05 onwards port is created as child of project. This leads to better list performance. Change-Id: Id0acbd1194403c500cdf0ee5851ef6cf5dba1c97 Closes-Bug: #1441924
import string template = string.Template(""" [DEFAULTS] ifmap_server_ip=$__contrail_ifmap_server_ip__ ifmap_server_port=$__contrail_ifmap_server_port__ ifmap_username=$__contrail_ifmap_username__ ifmap_password=$__contrail_ifmap_password__ cassandra_server_list=$__contrail_cassandra_server_list__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ multi_tenancy=$__contrail_multi_tenancy__ log_file=$__contrail_log_file__ log_local=1 log_level=SYS_NOTICE disc_server_ip=$__contrail_disc_server_ip__ disc_server_port=$__contrail_disc_server_port__ zk_server_ip=$__contrail_zookeeper_server_ip__ redis_server_ip=$__contrail_redis_ip__ rabbit_server=$__rabbit_server_ip__ rabbit_port=$__rabbit_server_port__ list_optimization_enabled=True [SECURITY] use_certs=$__contrail_use_certs__ keyfile=$__contrail_keyfile_location__ certfile=$__contrail_certfile_location__ ca_certs=$__contrail_cacertfile_location__ """)
import string template = string.Template(""" [DEFAULTS] ifmap_server_ip=$__contrail_ifmap_server_ip__ ifmap_server_port=$__contrail_ifmap_server_port__ ifmap_username=$__contrail_ifmap_username__ ifmap_password=$__contrail_ifmap_password__ cassandra_server_list=$__contrail_cassandra_server_list__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ multi_tenancy=$__contrail_multi_tenancy__ log_file=$__contrail_log_file__ log_local=1 log_level=SYS_NOTICE disc_server_ip=$__contrail_disc_server_ip__ disc_server_port=$__contrail_disc_server_port__ zk_server_ip=$__contrail_zookeeper_server_ip__ redis_server_ip=$__contrail_redis_ip__ rabbit_server=$__rabbit_server_ip__ rabbit_port=$__rabbit_server_port__ [SECURITY] use_certs=$__contrail_use_certs__ keyfile=$__contrail_keyfile_location__ certfile=$__contrail_certfile_location__ ca_certs=$__contrail_cacertfile_location__ """)
Update support for Meteor 1.2
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); var assets = [ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2' ]; if (api.addAssets) { api.addAssets(assets, 'client'); } else { api.addFiles(assets, 'client', { isAsset: true }); } api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2' ], 'client', { isAsset: true }); api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
Fix issue with symbols vs attribute name disambiguation See if the name is a valid symbol before trying to resolve it as a tuple attribute
package com.facebook.presto.sql.compiler; import com.facebook.presto.sql.tree.Node; import com.facebook.presto.sql.tree.NodeRewriter; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.TreeRewriter; import com.google.common.collect.Iterables; import java.util.List; import java.util.Map; public class NameToSymbolRewriter extends NodeRewriter<Void> { private final TupleDescriptor descriptor; private final Map<Symbol, Type> symbols; public NameToSymbolRewriter(TupleDescriptor descriptor) { this.descriptor = descriptor; this.symbols = descriptor.getSymbols(); } @Override public Node rewriteQualifiedNameReference(QualifiedNameReference node, Void context, TreeRewriter<Void> treeRewriter) { // is this a known symbol? if (!node.getName().getPrefix().isPresent() && symbols.containsKey(Symbol.fromQualifiedName(node.getName()))) { // symbols can't have prefixes return node; } // try to resolve name Symbol symbol = Iterables.getOnlyElement(descriptor.resolve(node.getName())).getSymbol(); return new QualifiedNameReference(symbol.toQualifiedName()); } }
package com.facebook.presto.sql.compiler; import com.facebook.presto.sql.tree.Node; import com.facebook.presto.sql.tree.NodeRewriter; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.TreeRewriter; import com.google.common.collect.Iterables; import java.util.List; import java.util.Map; public class NameToSymbolRewriter extends NodeRewriter<Void> { private final TupleDescriptor descriptor; private final Map<Symbol, Type> symbols; public NameToSymbolRewriter(TupleDescriptor descriptor) { this.descriptor = descriptor; this.symbols = descriptor.getSymbols(); } @Override public Node rewriteQualifiedNameReference(QualifiedNameReference node, Void context, TreeRewriter<Void> treeRewriter) { // try to resolve name List<Field> fields = descriptor.resolve(node.getName()); if (fields.isEmpty() && symbols.containsKey(Symbol.fromQualifiedName(node.getName()))) { // if the name is not a valid field, is it a known symbol? return node; } Symbol symbol = Iterables.getOnlyElement(descriptor.resolve(node.getName())).getSymbol(); return new QualifiedNameReference(symbol.toQualifiedName()); } }
Update cloud summary message header version num
''' Copyright 2011 Will Rogers 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. ''' LOGGER_ID = "apeldb" JOB_MSG_HEADER = "APEL-individual-job-message: v0.3" SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2" NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3" SYNC_MSG_HEADER = "APEL-sync-message: v0.1" CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4' CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4' from apel.db.apeldb import ApelDb, Query, ApelDbException
''' Copyright 2011 Will Rogers 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. ''' LOGGER_ID = "apeldb" JOB_MSG_HEADER = "APEL-individual-job-message: v0.3" SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2" NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3" SYNC_MSG_HEADER = "APEL-sync-message: v0.1" CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4' CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2' from apel.db.apeldb import ApelDb, Query, ApelDbException
Update default test server port to selenium default port to test browser on CI.
package main import ( "fmt" "os" "runtime/debug" "testing" . "github.com/onsi/gomega" "github.com/sclevine/agouti" ) const ( PORT = 4444 ) var ( baseUrl = fmt.Sprintf("http://localhost:%v/admin", PORT) driver *agouti.WebDriver page *agouti.Page ) func TestMain(m *testing.M) { var t *testing.T var err error driver = agouti.Selenium() driver.Start() go Start(PORT) page, err = driver.NewPage(agouti.Browser("chrome")) if err != nil { t.Error("Failed to open page.") } RegisterTestingT(t) test := m.Run() driver.Stop() os.Exit(test) } func StopDriverOnPanic() { var t *testing.T if r := recover(); r != nil { debug.PrintStack() fmt.Println("Recovered in f", r) driver.Stop() t.Fail() } }
package main import ( "fmt" "os" "runtime/debug" "testing" . "github.com/onsi/gomega" "github.com/sclevine/agouti" ) const ( PORT = 9009 ) var ( baseUrl = fmt.Sprintf("http://localhost:%v/admin", PORT) driver *agouti.WebDriver page *agouti.Page ) func TestMain(m *testing.M) { var t *testing.T var err error driver = agouti.Selenium() driver.Start() go Start(PORT) page, err = driver.NewPage(agouti.Browser("chrome")) if err != nil { t.Error("Failed to open page.") } RegisterTestingT(t) test := m.Run() driver.Stop() os.Exit(test) } func StopDriverOnPanic() { var t *testing.T if r := recover(); r != nil { debug.PrintStack() fmt.Println("Recovered in f", r) driver.Stop() t.Fail() } }
Use standart i18n key in meal model
from django.db import models from django.utils.translation import ugettext_lazy as _ class Meal(models.Model): class Meta: verbose_name_plural = _('meals') #Meal information nom = models.CharField(max_length=50, verbose_name=_('name')) description = models.TextFields(verbose_name=_('description')) ingredients = models.ManyToManyField(Ingredient, related_name='related_meals')) class Ingredient(models.Model): class Meta: verbose_name_plural = _('ingredients') #Ingredient information nom = models.CharField(max_length=50, verbose_name=_('name')) class Allergy(models.Model): class Meta: verbose_name_plural = _('allergies') #Allergy information nom = models.CharField(max_length=50, verbose_name=_('name')) description = models.TextFields(verbose_name=_('description')) ingredients = models.ManyToManyField(Ingredient, related_name='related_allergies'))
from django.db import models from django.utils.translation import ugettext_lazy as _ class Meal(models.Model): class Meta: verbose_name_plural = _('Meals') #Meal information nom = models.CharField(max_length=50, verbose_name=_('Name')) description = models.TextFields(verbose_name=_('Description')) ingredients = models.ManyToManyField(Ingredient, related_name='related_meals')) class Ingredient(models.Model): class Meta: verbose_name_plural = _('Ingredients') #Ingredient information nom = models.CharField(max_length=50, verbose_name=_('Name')) class Allergy(models.Model): class Meta: verbose_name_plural = _('Allergies') #Allergy information nom = models.CharField(max_length=50, verbose_name=_('Name')) description = models.TextFields(verbose_name=_('Description')) ingredients = models.ManyToManyField(Ingredient, related_name='related_allergies'))
Remove html coverage reporter, caused test to hang
const path = require('path'); var webpack = require('./webpack.config.js'); webpack.module.preLoaders = [ { test: /\.js$/, include: path.resolve('app/lib/'), loader: 'babel-istanbul', }, ]; module.exports = config => { config.set({ browsers: [ 'PhantomJS' ], autoWatch: false, singleRun: true, failOnEmptyTestSuite: false, files: [ 'app/tests/unit/**/*.spec.js', ], frameworks: [ 'mocha', 'chai', 'sinon', ], reporters: [ 'mocha', 'html', 'coverage', ], preprocessors: { 'app/lib/**/*.js': [ 'webpack', 'babel' ], 'app/tests/**/*.js': [ 'webpack', 'babel' ], }, webpack: webpack, htmlReporter: { outputFile: 'dist/unit-tests/index.html', groupSuites: true, useCompactStyle: true, }, coverageReporter: { dir: 'dist', subdir: 'unit-coverage', reporters: [ { type: 'text', file: 'coverage.txt' }, ], }, }); }
const path = require('path'); var webpack = require('./webpack.config.js'); webpack.module.preLoaders = [ { test: /\.js$/, include: path.resolve('app/lib/'), loader: 'babel-istanbul', }, ]; module.exports = config => { config.set({ browsers: [ 'PhantomJS' ], autoWatch: false, singleRun: true, failOnEmptyTestSuite: false, files: [ 'app/tests/unit/**/*.spec.js', ], frameworks: [ 'mocha', 'chai', 'sinon', ], reporters: [ 'mocha', 'html', 'coverage', ], preprocessors: { 'app/lib/**/*.js': [ 'webpack', 'babel' ], 'app/tests/**/*.js': [ 'webpack', 'babel' ], }, webpack: webpack, htmlReporter: { outputFile: 'dist/unit-tests/index.html', groupSuites: true, useCompactStyle: true, }, coverageReporter: { reporters: [ { type: 'text' }, { type: 'html', dir: 'dist', subdir: 'unit-coverage' }, ], }, }); }
Fix a problem that prevents firefox users from adding a new site.
// ------------------------ // Slug Validation // ------------------------ require(['jquery'], function($) { /* FIXME EVDB check this is the best way to do this and also to match with serverside checks */ var check_allowed_letter = function(ltr){ if( (ltr >= 97 && ltr <= 122) // a-z || (ltr >= 65 && ltr <= 90) // A-Z || (ltr >= 48 && ltr <= 57) // 0-9 || (ltr === 45) // _ ){ return true; } else{ return false; } } $(document).on( { keypress: function(e) { // Return True/False to prevent or allow the key being pressed or add an //error class to display the hint when a disallowed key is pressed return check_allowed_letter(e.which); }, change: function(e) { // Check pasted text var changedText = $(this).val(); var cleanedText = changedText.replace(/[^a-z0-9\-]+/gi, '-').toLowerCase(); $(this).val(cleanedText); } }, 'input[name=slug]' ); });
// ------------------------ // Slug Validation // ------------------------ require(['jquery'], function($) { /* FIXME EVDB check this is the best way to do this and also to match with serverside checks */ var check_allowed_letter = function(ltr){ if( (ltr >= 97 && ltr <= 122) // a-z || (ltr >= 65 && ltr <= 90) // A-Z || (ltr >= 48 && ltr <= 57) // 0-9 || (ltr === 45) // _ ){ return true; } else{ return false; } } $(document).on( { keypress: function(e) { // Return True/False to prevent or allow the key being pressed or add an //error class to display the hint when a disallowed key is pressed return check_allowed_letter(e.keyCode); }, change: function(e) { // Check pasted text var changedText = $(this).val(); var cleanedText = changedText.replace(/[^a-z0-9\-]+/gi, '-').toLowerCase(); $(this).val(cleanedText); } }, 'input[name=slug]' ); });
Agentctl2: Add example command to CLI. Signed-off-by: Andrej Kozemcak <806670a1cb1f0508258ef96648425f1247742d81@pantheon.tech>
package cmd import ( "errors" "fmt" "github.com/ligato/vpp-agent/cmd/agentctl2/utils" "github.com/spf13/cobra" ) // RootCmd represents the base command when called without any subcommands. var putConfig = &cobra.Command{ Use: "put", Aliases: []string{"p"}, Short: "Put configuration file", Long: ` Put configuration file `, Args: cobra.RangeArgs(2, 2), Example: ` Set route configuration for "vpp1": $./agentctl2 -e 172.17.0.3:2379 put /vnf-agent/vpp1/config/vpp/v2/route/vrf/1/dst/10.1.1.3/32/gw/192.168.1.13 '{ "type": 1, "vrf_id": 1, "dst_network": "10.1.1.3/32", "next_hop_addr": "192.168.1.13" }' `, Run: putFunction, } func init() { RootCmd.AddCommand(putConfig) } func putFunction(cmd *cobra.Command, args []string) { key := args[0] json := args[1] fmt.Printf("key: %s, json: %s\n", key, json) db, err := utils.GetDbForAllAgents(globalFlags.Endpoints) if err != nil { utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error())) } utils.WriteData(db.NewTxn(), key, json) }
package cmd import ( "errors" "fmt" "github.com/ligato/vpp-agent/cmd/agentctl2/utils" "github.com/spf13/cobra" ) // RootCmd represents the base command when called without any subcommands. var putConfig = &cobra.Command{ Use: "put", Aliases: []string{"p"}, Short: "Put configuration file", Long: ` Put configuration file `, Args: cobra.MinimumNArgs(2), Run: putFunction, } func init() { RootCmd.AddCommand(putConfig) } func putFunction(cmd *cobra.Command, args []string) { key := args[0] json := args[1] fmt.Printf("key: %s, json: %s\n", key, json) db, err := utils.GetDbForAllAgents(globalFlags.Endpoints) if err != nil { utils.ExitWithError(utils.ExitError, errors.New("Failed to connect to Etcd - "+err.Error())) } utils.WriteData(db.NewTxn(), key, json) }
Fix getting random character from charset If strlen($possible) is for example 36, rand could also return 36. But substr starts with position 0. So we have to subtract 1 from strlen($possible).
<?php /* Plugin Name: Random Keywords Plugin URI: http://yourls.org/ Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK) Version: 1.1 Author: Ozh Author URI: http://ozh.org/ */ /* Release History: * * 1.0 Initial release * 1.1 Added: don't increment sequential keyword counter & save one SQL query * Fixed: plugin now complies to character set defined in config.php */ global $ozh_random_keyword; /* * CONFIG: EDIT THIS */ /* Length of random keyword */ $ozh_random_keyword['length'] = 5; /* * DO NOT EDIT FARTHER */ // Generate a random keyword yourls_add_filter( 'random_keyword', 'ozh_random_keyword' ); function ozh_random_keyword() { global $ozh_random_keyword; $possible = yourls_get_shorturl_charset() ; $str=''; while (strlen($str) < $ozh_random_keyword['length']) { $str .= substr($possible, rand(0,strlen($possible)-1),1); } return $str; } // Don't increment sequential keyword tracker yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' ); function ozh_random_keyword_next_decimal( $next ) { return ( $next - 1 ); }
<?php /* Plugin Name: Random Keywords Plugin URI: http://yourls.org/ Description: Assign random keywords to shorturls, like bitly (sho.rt/hJudjK) Version: 1.1 Author: Ozh Author URI: http://ozh.org/ */ /* Release History: * * 1.0 Initial release * 1.1 Added: don't increment sequential keyword counter & save one SQL query * Fixed: plugin now complies to character set defined in config.php */ global $ozh_random_keyword; /* * CONFIG: EDIT THIS */ /* Length of random keyword */ $ozh_random_keyword['length'] = 5; /* * DO NOT EDIT FARTHER */ // Generate a random keyword yourls_add_filter( 'random_keyword', 'ozh_random_keyword' ); function ozh_random_keyword() { global $ozh_random_keyword; $possible = yourls_get_shorturl_charset() ; $str=''; while (strlen($str) < $ozh_random_keyword['length']) { $str .= substr($possible, rand(0,strlen($possible)),1); } return $str; } // Don't increment sequential keyword tracker yourls_add_filter( 'get_next_decimal', 'ozh_random_keyword_next_decimal' ); function ozh_random_keyword_next_decimal( $next ) { return ( $next - 1 ); }
Add notice in callback example
const request = require('request') function getLuke(cb) { const lukeInfo = { name: 'Luke', } /* Here stars the callback hell. Please notice the if (error) return cb(error) redundant code */ request('https://swapi.co/api/people/1', (error, response, body) => { if (error) return cb(error) const data = JSON.parse(body) const startShipURL = data.starships[0] const vehicleURL = data.vehicles[0] request(startShipURL, (error, response, body) => { if (error) return cb(error) const { name, model, starship_class } = JSON.parse(body) lukeInfo.startShip = { name, model, type: starship_class} request(vehicleURL, (error, response, body) => { if (error) return cb(error) const { name, model, vehicle_class } = JSON.parse(body) lukeInfo.vehicle = { name, model, type: vehicle_class} cb(null, lukeInfo) // <== Pass null in error and result as second arg }) }) }) } describe('Example with Callbacks (Callback Hell)', () => { it('should get Luke details', (done) => { getLuke((error, info) => { if (error) return done(error) console.log(info) done() }); }) })
const request = require('request') function getLuke(cb) { const lukeInfo = { name: 'Luke', } request('https://swapi.co/api/people/1', (error, response, body) => { if (error) return cb(error) const data = JSON.parse(body) const startShipURL = data.starships[0] const vehicleURL = data.vehicles[0] request(startShipURL, (error, response, body) => { if (error) return cb(error) const { name, model, starship_class } = JSON.parse(body) lukeInfo.startShip = { name, model, type: starship_class} request(vehicleURL, (error, response, body) => { if (error) return cb(error) const { name, model, vehicle_class } = JSON.parse(body) lukeInfo.vehicle = { name, model, type: vehicle_class} cb(null, lukeInfo) // <== Pass null in error and result as second arg }) }) }) } describe('Example with Callbacks (Callback Hell)', () => { it('should get Luke details', (done) => { getLuke((error, info) => { if (error) return done(error) console.log(info) done() }); }) })
Set Fastpass Import provider ID to 'Fastpass'
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.wizard; import com.intellij.ide.util.PropertiesComponent; import icons.PantsIcons; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.bsp.project.importing.BspProjectImportProvider; import javax.swing.Icon; import java.util.Optional; public class FastpassProjectImportProvider extends BspProjectImportProvider { static private String label() { return Optional .ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label")) .orElse("Pants (Fastpass)"); } @Override public @Nullable Icon getIcon() { return PantsIcons.Icon; } @NotNull @Override public String getId() { return "Fastpass"; } @Override public @NotNull @Nls(capitalization = Nls.Capitalization.Sentence) String getName() { return label(); } }
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.wizard; import com.intellij.ide.util.PropertiesComponent; import icons.PantsIcons; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.bsp.project.importing.BspProjectImportProvider; import javax.swing.Icon; import java.util.Optional; public class FastpassProjectImportProvider extends BspProjectImportProvider { static private String label() { return Optional .ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label")) .orElse("Pants (Fastpass)"); } @Override public @Nullable Icon getIcon() { return PantsIcons.Icon; } @Override public @NotNull @Nls(capitalization = Nls.Capitalization.Sentence) String getName() { return label(); } }
Print error message when `git log` is not given a SHA * This will be allowed after references are implemented
package main import ( "bytes" "fmt" "io" "log" "os" "github.com/ChimeraCoder/gitgo" ) func main() { args := os.Args module := args[1] switch module { case "cat-file": hash := args[2] result, err := gitgo.CatFile(gitgo.SHA(hash)) if err != nil { log.Fatal(err) } io.Copy(os.Stdout, result) case "log": if len(args) < 3 { fmt.Println("must specify commit name with `log`") os.Exit(1) } hash := gitgo.SHA(args[2]) commits, err := gitgo.Log(hash, "") if err != nil { log.Fatal(err) } b := bytes.NewBuffer(nil) for _, commit := range commits { fmt.Fprintf(b, "commit %s\nAuthor: %s\nDate: %s\n\n %s\n", commit.Name, commit.Author, commit.AuthorDate.Format(gitgo.RFC2822), bytes.Replace(commit.Message, []byte("\n"), []byte("\n "), -1)) } io.Copy(os.Stdout, b) default: log.Fatalf("no such command: %s", module) } }
package main import ( "bytes" "fmt" "io" "log" "os" "github.com/ChimeraCoder/gitgo" ) func main() { args := os.Args module := args[1] switch module { case "cat-file": hash := args[2] result, err := gitgo.CatFile(gitgo.SHA(hash)) if err != nil { log.Fatal(err) } io.Copy(os.Stdout, result) case "log": hash := gitgo.SHA(args[2]) commits, err := gitgo.Log(hash, "") if err != nil { log.Fatal(err) } b := bytes.NewBuffer(nil) for _, commit := range commits { fmt.Fprintf(b, "commit %s\nAuthor: %s\nDate: %s\n\n %s\n", commit.Name, commit.Author, commit.AuthorDate.Format(gitgo.RFC2822), bytes.Replace(commit.Message, []byte("\n"), []byte("\n "), -1)) } io.Copy(os.Stdout, b) default: log.Fatalf("no such command: %s", module) } }
Disable old URL for /room
/* jslint node: true, browser: true */ /* global angular: true */ 'use strict'; // Declare app level module which depends on views, and components var olyMod = angular.module('mcWebRTC', [ 'ngRoute', 'ngResource', 'ngAnimate', //'ui.bootstrap.dropdown', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.popover', 'mgcrea.ngStrap.dropdown', 'mgcrea.ngStrap.alert', 'webcam', 'angularMoment', 'ngEmoticons', 'FBAngular', 'mcWebRTC.filters', 'mcWebRTC.services', 'mcWebRTC.directives', 'mcWebRTC.controllers' ]); olyMod.config(['$routeProvider', /*'$locationProvider',*/ function($routeProvider, $locationProvider) { $routeProvider. when('/', {templateUrl: 'modules/sign-in.html', controller: 'SignInCtrl'}). when('/home', {templateUrl: 'modules/home.html', controller: 'HomeCtrl'}). // when('/room', {templateUrl: 'modules/room.html', controller: 'RoomCtrl'}). otherwise({redirectTo: '/'}); // $locationProvider.html5Mode(true); }]);
/* jslint node: true, browser: true */ /* global angular: true */ 'use strict'; // Declare app level module which depends on views, and components var olyMod = angular.module('mcWebRTC', [ 'ngRoute', 'ngResource', 'ngAnimate', //'ui.bootstrap.dropdown', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.popover', 'mgcrea.ngStrap.dropdown', 'mgcrea.ngStrap.alert', 'webcam', 'angularMoment', 'ngEmoticons', 'FBAngular', 'mcWebRTC.filters', 'mcWebRTC.services', 'mcWebRTC.directives', 'mcWebRTC.controllers' ]); olyMod.config(['$routeProvider', /*'$locationProvider',*/ function($routeProvider, $locationProvider) { $routeProvider. when('/', {templateUrl: 'modules/sign-in.html', controller: 'SignInCtrl'}). when('/room', {templateUrl: 'modules/room.html', controller: 'RoomCtrl'}). when('/home', {templateUrl: 'modules/home.html', controller: 'HomeCtrl'}). otherwise({redirectTo: '/'}); // $locationProvider.html5Mode(true); }]);
Remove outdated test. Add new one for privacy
const request = require('supertest'); const app = require('../app.js'); describe('GET /', () => { it('should return 200 OK', (done) => { request(app) .get('/') .expect(200, done); }); }); describe('GET /login', () => { it('should return 200 OK', (done) => { request(app) .get('/login') .expect(200, done); }); }); describe('GET /signup', () => { it('should return 200 OK', (done) => { request(app) .get('/signup') .expect(200, done); }); }); describe('GET /privacy', () => { it('should return 200 OK', (done) => { request(app) .get('/privacy') .expect(200, done); }); }); describe('GET /contact', () => { it('should return 200 OK', (done) => { request(app) .get('/contact') .expect(200, done); }); }); describe('GET /random-url', () => { it('should return 404', (done) => { request(app) .get('/reset') .expect(404, done); }); });
const request = require('supertest'); const app = require('../app.js'); describe('GET /', () => { it('should return 200 OK', (done) => { request(app) .get('/') .expect(200, done); }); }); describe('GET /login', () => { it('should return 200 OK', (done) => { request(app) .get('/login') .expect(200, done); }); }); describe('GET /signup', () => { it('should return 200 OK', (done) => { request(app) .get('/signup') .expect(200, done); }); }); describe('GET /api', () => { it('should return 200 OK', (done) => { request(app) .get('/api') .expect(200, done); }); }); describe('GET /contact', () => { it('should return 200 OK', (done) => { request(app) .get('/contact') .expect(200, done); }); }); describe('GET /random-url', () => { it('should return 404', (done) => { request(app) .get('/reset') .expect(404, done); }); });
Install the script with the library.
#!/usr/bin/env python from distutils.core import setup from avena import avena _classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics', ] with open('README.rst', 'r') as rst_file: _long_description = rst_file.read() _setup_args = { 'author': avena.__author__, 'author_email': avena.__email__, 'classifiers': _classifiers, 'description': avena.__doc__, 'license': avena.__license__, 'long_description': _long_description, 'name': 'Avena', 'url': 'https://bitbucket.org/eliteraspberries/avena', 'version': avena.__version__, } if __name__ == '__main__': setup(packages=['avena'], scripts=['scripts/avena'], **_setup_args)
#!/usr/bin/env python from distutils.core import setup from avena import avena _classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics', ] with open('README.rst', 'r') as rst_file: _long_description = rst_file.read() _setup_args = { 'author': avena.__author__, 'author_email': avena.__email__, 'classifiers': _classifiers, 'description': avena.__doc__, 'license': avena.__license__, 'long_description': _long_description, 'name': 'Avena', 'url': 'https://bitbucket.org/eliteraspberries/avena', 'version': avena.__version__, } if __name__ == '__main__': setup(packages=['avena'], **_setup_args)
Add comment for identity reverse engineering
<?php declare (strict_types = 1); namespace HMLB\DDDBundle\Doctrine\ORM\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\Type; use HMLB\DDD\Entity\Identity; /** * IdentityType. * * @author Hugues Maignol <hugues@hmlb.fr> */ class IdentityType extends Type { const NAME = 'ddd_identity'; public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); } public function convertToPHPValue($value, AbstractPlatform $platform) { if (null === $value) { return; } return new Identity($value); } public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (empty($value)) { return; } if ($value instanceof Identity) { return (string) $value; } throw ConversionException::conversionFailed($value, self::NAME); } public function requiresSQLCommentHint(AbstractPlatform $platform) { return true; } public function getName() { return self::NAME; } }
<?php declare (strict_types = 1); namespace HMLB\DDDBundle\Doctrine\ORM\DBAL\Types; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\Type; use Doctrine\DBAL\Platforms\AbstractPlatform; use HMLB\DDD\Entity\Identity; /** * IdentityType. * * @author Hugues Maignol <hugues@hmlb.fr> */ class IdentityType extends Type { const NAME = 'ddd_identity'; public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); } public function convertToPHPValue($value, AbstractPlatform $platform) { if (null === $value) { return; } return new Identity($value); } public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (empty($value)) { return; } if ($value instanceof Identity) { return (string) $value; } throw ConversionException::conversionFailed($value, self::NAME); } public function getName() { return self::NAME; } }
Fix $description to match with $author
<?php /* * Core variables. * * Set up the site. */ // // Meta // $encoding = 'utf-8'; $title = 'Site'; if (isset($slug)) { $title = "$slug &middot; $title"; } $description = "Personal site of Mr. Ghost."; $author = 'Mr. Ghost'; $keywords = 'site, website, web'; $robots = 'noodp,noydir'; $viewport = 'width=device-width, initial-scale=1.0'; $styles = "$root/assets/css/main.css"; $favicon = "$root/favicon.ico"; // // Copyright // $cpowner = $author; $cpyear = 2013; $copyright = '&copy; ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y') : '') . ' ' . $cpowner; ?>
<?php /* * Core variables. * * Set up the site. */ // // Meta // $encoding = 'utf-8'; $title = 'Site'; if (isset($slug)) { $title = "$slug &middot; $title"; } $description = "Personal site."; $author = 'Mr. Ghost'; $keywords = 'site, website, web'; $robots = 'noodp,noydir'; $viewport = 'width=device-width, initial-scale=1.0'; $styles = "$root/assets/css/main.css"; $favicon = "$root/favicon.ico"; // // Copyright // $cpowner = $author; $cpyear = 2013; $copyright = '&copy; ' . $cpyear . (($cpyear != date('Y')) ? '-' . date('Y') : '') . ' ' . $cpowner; ?>
Add dependency on accounts-base API for client
Package.describe({ "summary": "Add feature flagging to Meteor" }); Package.on_use(function (api) { api.use('coffeescript', ['server', 'client']); api.use(['deps','handlebars','jquery'], 'client'); api.use('underscore', 'server'); api.use('accounts-base', ['client']) api.add_files('server/server_flag.coffee', 'server') api.add_files('client/client_flag.coffee', 'client') if (typeof api.export !== 'undefined'){ api.export('FeatureFlag', 'server'); } }); Package.on_test(function(api) { api.use('coffeescript', ['server', 'client']); api.use(['meteor-feature-flag',"tinytest", "test-helpers"]) api.use('underscore', 'server'); api.add_files('test/feature_flag.coffee', 'server') });
Package.describe({ "summary": "Add feature flagging to Meteor" }); Package.on_use(function (api) { api.use('coffeescript', ['server', 'client']); api.use(['deps','handlebars','jquery'], 'client'); api.use('underscore', 'server'); api.add_files('server/server_flag.coffee', 'server') api.add_files('client/client_flag.coffee', 'client') if (typeof api.export !== 'undefined'){ api.export('FeatureFlag', 'server'); } }); Package.on_test(function(api) { api.use('coffeescript', ['server', 'client']); api.use(['meteor-feature-flag',"tinytest", "test-helpers"]) api.use('underscore', 'server'); api.add_files('test/feature_flag.coffee', 'server') });
Validate dynamic interface's range's container, not dynamic interface's range's domain's container.
# encoding: utf-8 from django.core.exceptions import ValidationError import re ERROR_TOO_LONG = 'MAC address is too long' mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$') def validate_mac(mac): if mac == ERROR_TOO_LONG: raise ValidationError(ERROR_TOO_LONG) elif mac == '00:00:00:00:00:00': raise ValidationError('Invalid MAC address—to disable DHCP for this ' 'interface, uncheck "Enable DHCP"') elif not mac_pattern.match(mac): raise ValidationError('Invalid MAC address') def validate_system_static_ctnr(system, static): if system.ctnr not in static.domain.ctnr_set.all(): raise ValidationError("System's container must match static " "interface's domain's containers.") def validate_system_dynamic_ctnr(system, dynamic): if system.ctnr not in dynamic.range.ctnr_set.all(): raise ValidationError("System's container must match dynamic " "interface's range's containers.")
# encoding: utf-8 from django.core.exceptions import ValidationError import re ERROR_TOO_LONG = 'MAC address is too long' mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$') def validate_mac(mac): if mac == ERROR_TOO_LONG: raise ValidationError(ERROR_TOO_LONG) elif mac == '00:00:00:00:00:00': raise ValidationError('Invalid MAC address—to disable DHCP for this ' 'interface, uncheck "Enable DHCP"') elif not mac_pattern.match(mac): raise ValidationError('Invalid MAC address') def validate_system_static_ctnr(system, static): if system.ctnr not in static.domain.ctnr_set.all(): raise ValidationError("System's container must match static " "interface's domain's containers.") def validate_system_dynamic_ctnr(system, dynamic): if system.ctnr not in dynamic.range.domain.ctnr_set.all(): raise ValidationError("System's container must match dynamic " "interface's range's domain's containers.")
wappalyzer: Tweak UnitTest to collect all failing patterns Signed-off-by: kingthorin <83ea41af2b636790c02743e48206546e1fa891e4@users.noreply.github.com>
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2019 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.wappalyzer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; public class WappalyzerAppsJsonParseUnitTest { @Test public void test() throws IOException { // Given List<String> errs = new ArrayList<>(); // When WappalyzerJsonParser parser = new WappalyzerJsonParser((pattern, e) -> errs.add(e.toString())); parser.parseDefaultAppsJson(); // Then assertEquals(Collections.emptyList(), errs); } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2019 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.wappalyzer; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import org.junit.jupiter.api.Test; public class WappalyzerAppsJsonParseUnitTest { @Test public void test() throws IOException { // When - there's a parse exception, fail WappalyzerJsonParser parser = new WappalyzerJsonParser( (pattern, e) -> fail("Regular expression with errors: " + e)); parser.parseDefaultAppsJson(); } }
Fix broken Helsinki OIDC provider links
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso/openid/token/' authorize_url = 'https://api.hel.fi/sso/openid/authorize/' profile_url = 'https://api.hel.fi/sso/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView ) from .provider import HelsinkiOIDCProvider class HelsinkiOIDCOAuth2Adapter(OAuth2Adapter): provider_id = HelsinkiOIDCProvider.id access_token_url = 'https://api.hel.fi/sso-test/openid/token/' authorize_url = 'https://api.hel.fi/sso-test/openid/authorize/' profile_url = 'https://api.hel.fi/sso-test/openid/userinfo/' def complete_login(self, request, app, token, **kwargs): headers = {'Authorization': 'Bearer {0}'.format(token.token)} resp = requests.get(self.profile_url, headers=headers) assert resp.status_code == 200 extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(HelsinkiOIDCOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(HelsinkiOIDCOAuth2Adapter)
Fix incorrect type annotation for consume
from typing import List, Callable __all__ = ['consume'] def consume(query_fn: Callable[[int, int], List], limit=1000, start=0, max=100, raise_exception=False): """Yield all rows from a paginated query. >>> import infusionsoft >>> query_fn = lambda page, limit: ( ... infusionsoft.DataService.query('mytable', limit, page, ['Id'])) >>> all_rows = list(consume(query_fn)) :param query_fn: Method which queries Infusionsoft and returns its rows. It is passed two arguments: page number and limit. :param limit: Max number of rows to return on one page :param start: Page number to begin at :param max: Maximum number of pages to consume :param raise_exception: Whether to raise a RuntimeError if maximum number of pages is exceeded. If False, number of rows is silently capped. """ for page in range(start, start + max + 1): rows = query_fn(page, limit) yield from rows if len(rows) < limit: break else: if raise_exception: raise RuntimeError(f'Maximum of {max} pages exceeded')
from typing import List, Callable __all__ = ['consume'] def consume(query_fn: Callable[[int], List], limit=1000, start=0, max=100, raise_exception=False): """Yield all rows from a paginated query. >>> import infusionsoft >>> query_fn = lambda page, limit: ( ... infusionsoft.DataService.query('mytable', limit, page, ['Id'])) >>> all_rows = list(consume(query_fn)) :param query_fn: Method which queries Infusionsoft and returns its rows. It is passed two arguments: page number and limit. :param limit: Max number of rows to return on one page :param start: Page number to begin at :param max: Maximum number of pages to consume :param raise_exception: Whether to raise a RuntimeError if maximum number of pages is exceeded. If False, number of rows is silently capped. """ for page in range(start, start + max + 1): rows = query_fn(page, limit) yield from rows if len(rows) < limit: break else: if raise_exception: raise RuntimeError(f'Maximum of {max} pages exceeded')
Exclude nonapp from contextprocessor of alternate_seo
from django.conf import settings as django_settings from django.core.urlresolvers import resolve, reverse from django.utils.translation import activate, get_language def settings(request): return {'settings': django_settings} def alternate_seo_url(request): alternate_url = dict() path = request.path url_parts = resolve( path ) if not url_parts.app_names: url = path cur_language = get_language() for lang_code, lang_name in django_settings.LANGUAGES : try: activate(lang_code) url = reverse( url_parts.view_name, kwargs=url_parts.kwargs ) alternate_url[lang_code] = django_settings.SITE_URL+url finally: activate(cur_language) return {'alternate':alternate_url}
from django.conf import settings as django_settings from django.core.urlresolvers import resolve, reverse from django.utils.translation import activate, get_language def settings(request): return {'settings': django_settings} def alternate_seo_url(request): alternate_url = dict() path = request.path url_parts = resolve( path ) url = path cur_language = get_language() for lang_code, lang_name in django_settings.LANGUAGES : try: activate(lang_code) url = reverse( url_parts.view_name, kwargs=url_parts.kwargs ) alternate_url[lang_code] = django_settings.SITE_URL+url finally: activate(cur_language) return {'alternate':alternate_url}
Drop `yield from` to keep compat w/ 2.7
import threading import time import pytest import cheroot.server import cheroot.wsgi config = { 'bind_addr': ('127.0.0.1', 54583), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.safe_start).start() # spawn it while not httpserver.ready: # wait until fully initialized and bound time.sleep(0.1) yield httpserver httpserver.stop() # destroy it @pytest.fixture(scope='module') def wsgi_server(): for srv in cheroot_server(cheroot.wsgi.Server): yield srv @pytest.fixture(scope='module') def native_server(): for srv in cheroot_server(cheroot.server.HTTPServer): yield srv
import threading import time import pytest import cheroot.server import cheroot.wsgi config = { 'bind_addr': ('127.0.0.1', 54583), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.safe_start).start() # spawn it while not httpserver.ready: # wait until fully initialized and bound time.sleep(0.1) yield httpserver httpserver.stop() # destroy it @pytest.fixture(scope='module') def wsgi_server(): yield from cheroot_server(cheroot.wsgi.Server) @pytest.fixture(scope='module') def native_server(): yield from cheroot_server(cheroot.server.HTTPServer)
Add support for MX validation in sfValidatorEmail
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfValidatorEmail validates emails. * * @package symfony * @subpackage validator * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id$ */ class sfValidatorEmail extends sfValidatorRegex { const REGEX_EMAIL = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i'; /** * @see sfValidatorRegex */ protected function configure($options = array(), $messages = array()) { parent::configure($options, $messages); $this->setOption('pattern', self::REGEX_EMAIL); $this->addOption('check_domain', false); } protected function doClean($value) { $clean = parent::doClean($value); if ($this->getOption('check_domain') && function_exists('checkdnsrr')) { $tokens = explode('@', $clean); if (!checkdnsrr($tokens[1], 'MX') && !checkdnsrr($tokens[1], 'A')) { throw new sfValidatorError($this, 'invalid', array('value' => $clean)); } } return $clean; } }
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfValidatorEmail validates emails. * * @package symfony * @subpackage validator * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id$ */ class sfValidatorEmail extends sfValidatorRegex { const REGEX_EMAIL = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i'; /** * @see sfValidatorRegex */ protected function configure($options = array(), $messages = array()) { parent::configure($options, $messages); $this->setOption('pattern', self::REGEX_EMAIL); } }
Return summary for the day on success This implements #2
#!/usr/bin/env python from telegram import Telegram from message_checker import MessageHandler from data_updater import DataUpdater # init telegram bot bot = Telegram() ok = bot.init() if not ok: print("ERROR (bot init): {}".format(bot.get_messages())) exit(1) # init message checker msg_checker = MessageHandler() # init data updater du = DataUpdater() ok = du.init() if not ok: print("ERROR (data updater init): {}".format(du.get_error_message())) exit(1) for message in bot.get_messages(): print("Handling message '{}'...".format(message.get_text())) msg_checker.set_message(message.get_text()) ok = msg_checker.check() if not ok: bot.send_reply(msg_checker.get_error_message()) continue res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date()) if res == False: bot.send_reply(du.get_error_message()) continue # success! bot.send_reply("Successfully added {}! Sum for the day is {}." .format(msg_checker.get_num_catch_ups(), res))
#!/usr/bin/env python from telegram import Telegram from message_checker import MessageHandler from data_updater import DataUpdater # init telegram bot bot = Telegram() ok = bot.init() if not ok: print("ERROR (bot init): {}".format(bot.get_messages())) exit(1) # init message checker msg_checker = MessageHandler() # init data updater du = DataUpdater() ok = du.init() if not ok: print("ERROR (data updater init): {}".format(du.get_error_message())) exit(1) for message in bot.get_messages(): print("Handling message '{}'...".format(message.get_text())) msg_checker.set_message(message.get_text()) ok = msg_checker.check() if not ok: bot.send_reply(msg_checker.get_error_message()) continue res = du.add_value(msg_checker.get_num_catch_ups(), message.date()) if res == False: bot.send_reply(du.get_error_message()) continue # success! bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
ext: Remove env check as Mopidy checks deps automatically
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '1.0.4' class BeetsExtension(ext.Extension): dist_name = 'Mopidy-Beets' ext_name = 'beets' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(BeetsExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() return schema def get_backend_classes(self): from .actor import BeetsBackend return [BeetsBackend]
from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError __version__ = '1.0.4' class BeetsExtension(ext.Extension): dist_name = 'Mopidy-Beets' ext_name = 'beets' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(BeetsExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() return schema def validate_environment(self): try: import requests # noqa except ImportError as e: raise ExtensionError('Library requests not found', e) def get_backend_classes(self): from .actor import BeetsBackend return [BeetsBackend]
Remove getSortedAlgorithmList method add sort to getAlgorithmList
package com.chaoticdawgsoftware.algorithms.providerutils; import java.security.Provider; import java.security.Security; import java.util.*; /** * ProviderAlgorithmRetrievingFactory.java * Created by ChaoticDawg on 1/20/17. */ public class ProviderAlgorithmRetrievingFactory { private static Provider[] providers = Security.getProviders(); public static ArrayList<String> getAlgorithmList(String algorithm) { ArrayList<String> AlgorithmList = buildAlgorithmList(algorithm); Collections.sort(AlgorithmList); return AlgorithmList; } private static ArrayList<String> buildAlgorithmList(String algorithm) { Set<String> keyNameSet = new HashSet<>(); for (Provider provider : providers) ProviderKeyListCreator.getKeyList(algorithm, keyNameSet, provider); return new ArrayList<>(keyNameSet); } }
package com.chaoticdawgsoftware.algorithms.providerutils; import java.security.Provider; import java.security.Security; import java.util.*; /** * ProviderAlgorithmRetrievingFactory.java * Created by ChaoticDawg on 1/20/17. */ public class ProviderAlgorithmRetrievingFactory { private static Provider[] providers = Security.getProviders(); public static ArrayList<String> getAlgorithmList(String algorithm) { return getSortedAlgorithmList(buildAlgorithmList(algorithm)); } private static ArrayList<String> buildAlgorithmList(String algorithm) { Set<String> keyNameSet = new HashSet<>(); for (Provider provider : providers) ProviderKeyListCreator.getKeyList(algorithm, keyNameSet, provider); return new ArrayList<>(keyNameSet); } private static ArrayList<String> getSortedAlgorithmList(ArrayList<String> keyList) { Collections.sort(keyList); return keyList; } }
Remove semicolon from javascript object definition
var format = require("util").format; var types = ["ham", "pb&b"]; module.exports = function (tennu) { return { dependencies: [], exports: { help: { sandwhich: "Makes a sandwhich for you." } }, handlers: { "!sandwhich" : function (command) { var requester = command.nickname; var type = types[Math.floor(Math.random() * types.length)]; return format("%s: Have a %s sandwhich.", requester, type); } } }; };
var format = require("util").format; var types = ["ham", "pb&b"]; module.exports = function (tennu) { return { dependencies: [], exports: { help: { sandwhich: "Makes a sandwhich for you." }; }, handlers: { "!sandwhich" : function (command) { var requester = command.nickname; var type = types[Math.floor(Math.random() * types.length)]; return format("%s: Have a %s sandwhich.", requester, type); } } }; };
Make the CPU use lovely decorator syntax for registering opcode implementations.
# # A class which represents the CPU itself, the brain of the virtual # machine. It ties all the systems together and runs the story. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZCpuError(Exception): "General exception for Zcpu class" pass class ZCpu(object): _opcodes = {} def __init__(self, zmem): self._memory = zmem print self._opcodes def _get_handler(self, opcode): return getattr(self, _opcodes[opcode]) def test_opcode(self, zop): """This is a test opcode.""" test_opcode._opcode = 0x20 # This is the "automagic" opcode handler registration system. # After each function that is an opcode handler, we assign the # function object an _opcode attribute, giving the numeric opcode # the function implements. # # Then, the following code iterates back over all items in the # class, and registers all objects with that attribute in the # _opcodes dictionary. # # Then, at runtime, the _get_handler method can be invoked to # retrieve the function implementing a given opcode. Pretty cool # voodoo if you ask me. for k,v in vars().items(): if hasattr(v, "_opcode"): _opcodes[v._opcode] = k
# # A class which represents the CPU itself, the brain of the virtual # machine. It ties all the systems together and runs the story. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZCpuError(Exception): "General exception for Zcpu class" pass class ZCpu(object): def __init__(self, zmem): "" self._memory = zmem self._opcode_handlers = {} # Introspect ourselves, discover all functions that look like # opcode handlers, and add them to our mapper for func in self.__class__.__dict__: print "Considering %s" % func instance_func = getattr(self, func) if instance_func != None: doc_head = instance_func.__doc__.split('\n')[0] print "Potential candidate, docstring is %s" % doc_head if doc_head.startswith("ZOPCODE "): opcode_num = int(doc_head[8:], 16) self._opcode_handlers[opcode_num] = instance_func print self._opcode_handlers def test_opcode(self, zop): """ZOPCODE 0x20 This is a test opcode."""
Add note about the account
'use strict'; /* global XMPP */ /* Note these are connection details for a local dev server :) */ var client = new XMPP.Client({ websocketsURL: "ws://localhost:5280/xmpp-websocket/", jid: 'lloyd@evilprofessor.co.uk', password: 'password' }) client.addListener( 'online', function() { console.log('online') ['astro@spaceboyz.net'].forEach( function(to) { var stanza = new XMPP.Element('message', { to: to, type: 'chat'}) .c('body') .t('Hello from browser') client.send(stanza) } ) } ) client.addListener( 'error', function(e) { console.error(e) } )
'use strict'; /* global XMPP */ var client = new XMPP.Client({ websocketsURL: "ws://localhost:5280/xmpp-websocket/", jid: 'lloyd@evilprofessor.co.uk', password: 'password' }) client.addListener( 'online', function() { console.log('online') ['astro@spaceboyz.net'].forEach( function(to) { var stanza = new XMPP.Element('message', { to: to, type: 'chat'}) .c('body') .t('Hello from browser') client.send(stanza) } ) } ) client.addListener( 'error', function(e) { console.error(e) } )
Add check for --data-path argument
package main import ( log "github.com/sirupsen/logrus" "runtime" "github.com/spf13/pflag" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) var dataFolder string var indexPath string var addr string var forceRebuild bool var baseURL string pflag.StringVar(&dataFolder, "data-path", "", "Path to the pyvideo data folder") pflag.StringVar(&indexPath, "index-path", "search.bleve", "Path to the search index folder") pflag.StringVar(&addr, "http-addr", "127.0.0.1:8080", "Address the HTTP server should listen on for API calls") pflag.BoolVar(&forceRebuild, "force-rebuild", false, "Rebuild the index even if it already exists") pflag.StringVar(&baseURL, "base-url", "http://pyvideo.org", "Base URL of the pyvideo website") pflag.Parse() if dataFolder == "" { log.Fatal("Please specify the path to the pyvideo data folder using --data-path") } idx, err := loadIndex(indexPath, dataFolder, forceRebuild) if err != nil { log.WithError(err).Fatalf("Failed to load index on %s", indexPath) } defer idx.Close() if err := runHTTPD(idx, addr); err != nil { log.WithError(err).Fatalf("Failed to start HTTPD on %s", addr) } }
package main import ( log "github.com/sirupsen/logrus" "runtime" "github.com/spf13/pflag" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) var dataFolder string var indexPath string var addr string var forceRebuild bool var baseURL string pflag.StringVar(&dataFolder, "data-path", "", "Path to the pyvideo data folder") pflag.StringVar(&indexPath, "index-path", "search.bleve", "Path to the search index folder") pflag.StringVar(&addr, "http-addr", "127.0.0.1:8080", "Address the HTTP server should listen on for API calls") pflag.BoolVar(&forceRebuild, "force-rebuild", false, "Rebuild the index even if it already exists") pflag.StringVar(&baseURL, "base-url", "http://pyvideo.org", "Base URL of the pyvideo website") pflag.Parse() idx, err := loadIndex(indexPath, dataFolder, forceRebuild) if err != nil { log.WithError(err).Fatalf("Failed to load index on %s", indexPath) } defer idx.Close() if err := runHTTPD(idx, addr); err != nil { log.WithError(err).Fatalf("Failed to start HTTPD on %s", addr) } }
Fix a lint warned bug
/* * Copyright (C) 2015 Haruki Hasegawa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.h6ah4i.android.example.advrecyclerview.common.utils; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewParent; public class AdapterUtils { public static View findParentViewHolderItemView(View v) { final ViewParent parent = v.getParent(); if (parent instanceof RecyclerView) { // returns the passed instance if the parent is RecyclerView return v; } else if (parent instanceof View) { // check the parent view recursively return findParentViewHolderItemView((View) parent); } else { return null; } } }
/* * Copyright (C) 2015 Haruki Hasegawa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.h6ah4i.android.example.advrecyclerview.common.utils; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewParent; public class AdapterUtils { public static View findParentViewHolderItemView(View v) { final ViewParent parent = v.getParent(); if (parent instanceof RecyclerView) { // returns the passed instance if the parent is RecyclerView return v; } else if (v instanceof View) { // check the parent view recursively return findParentViewHolderItemView((View) parent); } else { return null; } } }
Load stats on startup, don't load nsfw
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('b>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>')) for extension in ('default', 'rpg', 'eddb', 'repl', 'wolfram', 'stats'): try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.INFO) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('b>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>')) for extension in ('default', 'rpg', 'eddb', 'repl', 'wolfram', 'nsfw'): try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.INFO) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
Add st2_auth_token to masked attributes list.
# Licensed to the StackStorm, Inc ('StackStorm') 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. __all__ = [ 'MASKED_ATTRIBUTES_BLACKLIST', 'MASKED_ATTRIBUTE_VALUE' ] # A blacklist of attributes which should be masked in the log messages by default. # Note: If an attribute is an object or a dict, we try to recursively process it and mask the # values. MASKED_ATTRIBUTES_BLACKLIST = [ 'password', 'auth_token', 'token', 'secret', 'credentials', 'st2_auth_token' ] # Value with which the masked attribute values are replaced MASKED_ATTRIBUTE_VALUE = '********'
# Licensed to the StackStorm, Inc ('StackStorm') 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. __all__ = [ 'MASKED_ATTRIBUTES_BLACKLIST', 'MASKED_ATTRIBUTE_VALUE' ] # A blacklist of attributes which should be masked in the log messages by default. # Note: If an attribute is an object or a dict, we try to recursively process it and mask the # values. MASKED_ATTRIBUTES_BLACKLIST = [ 'password', 'auth_token', 'token', 'secret', 'credentials' ] # Value with which the masked attribute values are replaced MASKED_ATTRIBUTE_VALUE = '********'
Use spaces instead of tabs
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.conf.urls import patterns, url from django.views.generic.base import TemplateView import views # exporting metadata search results urlpatterns = patterns('', # export search results url(r'^submit-query/?$', 'nhmmer.views.submit_job', name='nhmmer-submit-job'), # get nhmmer search job status url(r'^job-status/?$', 'nhmmer.views.get_status', name='nhmmer-job-status'), # get nhmmer results url(r'^get-results/?$', views.ResultsView.as_view(), name='nhmmer-job-results'), # user interface url(r'^$', TemplateView.as_view(template_name='nhmmer/sequence-search.html'), name='nhmmer-sequence-search'), )
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.conf.urls import patterns, url from django.views.generic.base import TemplateView import views # exporting metadata search results urlpatterns = patterns('', # export search results url(r'^submit-query/?$', 'nhmmer.views.submit_job', name='nhmmer-submit-job'), # get nhmmer search job status url(r'^job-status/?$', 'nhmmer.views.get_status', name='nhmmer-job-status'), # get nhmmer results url(r'^get-results/?$', views.ResultsView.as_view(), name='nhmmer-job-results'), # user interface url(r'^$', TemplateView.as_view(template_name='nhmmer/sequence-search.html'), name='nhmmer-sequence-search'), )
Improve error catching and throwing Now catching errors from eslint's CLIEngine, for example if an unknown rule is used. Also improved guard for throwing lint errors.
var CLIEngine = require('eslint').CLIEngine; var chalk = require('chalk'); var cli = new CLIEngine({}); var format = ''; module.exports = function (paths, options) { if (options && options.formatter) { format = options.formatter; } describe('eslint', function () { paths.forEach(function (p) { it(`should have no errors in ${p}`, function () { try { var report = cli.executeOnFiles([p]); var formatter = cli.getFormatter(format); } catch (err) { throw new Error(err); } if ( report && report.errorCount > 0 ) { throw new Error( `${chalk.red('Code did not pass lint rules')} ${formatter(report.results)}` ); } }); }); }); };
var CLIEngine = require('eslint').CLIEngine; var chalk = require('chalk'); var cli = new CLIEngine({}); var format = ''; module.exports = function (paths, options) { if (options && options.formatter) { format = options.formatter; } describe('eslint', function () { paths.forEach(function (p) { it(`should have no errors in ${p}`, function () { var report = cli.executeOnFiles([p]); var formatter = cli.getFormatter(format); // console.log(formatter(report.results)); if (report.errorCount !== 0) { throw new Error( `${chalk.red('Code did not pass lint rules')} ${formatter(report.results)}` ); } }); }); }); };
Stop property elements being generated on DecoratedMetaData classes when generating edit views.
package org.skyve.impl.metadata.repository; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * JAXB Adapter for Map<String, String> to/from PropertyMapType. */ public class PropertyMapAdapter extends XmlAdapter<PropertyMapType, Map<String, String>> { @Override public Map<String, String> unmarshal(PropertyMapType v) throws Exception { Map<String, String> result = new TreeMap<>(); for (PropertyMapEntryType property : v.properties) { result.put(property.key, property.value); } return result; } @Override public PropertyMapType marshal(Map<String, String> v) throws Exception { PropertyMapType result = null; if (! v.isEmpty()) { result = new PropertyMapType(); List<PropertyMapEntryType> properties = result.properties; for (Entry<String, String> entry : v.entrySet()) { PropertyMapEntryType property = new PropertyMapEntryType(); property.key = entry.getKey(); property.value = entry.getValue(); properties.add(property); } } return result; } }
package org.skyve.impl.metadata.repository; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * JAXB Adapter for Map<String, String> to/from PropertyMapType. */ public class PropertyMapAdapter extends XmlAdapter<PropertyMapType, Map<String, String>> { @Override public Map<String, String> unmarshal(PropertyMapType v) throws Exception { Map<String, String> result = new TreeMap<>(); for (PropertyMapEntryType property : v.properties) { result.put(property.key, property.value); } return result; } @Override public PropertyMapType marshal(Map<String, String> v) throws Exception { PropertyMapType result = new PropertyMapType(); List<PropertyMapEntryType> properties = result.properties; for (Entry<String, String> entry : v.entrySet()) { PropertyMapEntryType property = new PropertyMapEntryType(); property.key = entry.getKey(); property.value = entry.getValue(); properties.add(property); } return result; } }
Change update_addon_node() to return the Addon node, whether created or found.
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. This also differs from update_xxxxx_nodes by returning the Addon node that is found or created. """ from goldstone.core.models import Addon result, _ = Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") return result
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. """ from goldstone.core.models import Addon Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on")
Make sure we never construct a far ref for a far ref Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
package som.interpreter.actors; import som.vmobjects.SAbstractObject; import som.vmobjects.SClass; import som.vmobjects.SSymbol; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; public final class SFarReference extends SAbstractObject { @CompilationFinal private static SClass farReferenceClass; private final Actor actor; private final Object value; public SFarReference(final Actor actor, final Object value) { this.actor = actor; this.value = value; assert !(value instanceof SFarReference); } public Actor getActor() { return actor; } public Object getValue() { return value; } @Override public SClass getSOMClass() { return farReferenceClass; } @Override public String toString() { return "FarRef[" + value.toString() + ", " + actor.toString() + "]"; } @Override public boolean isValue() { return true; } public static void setSOMClass(final SClass cls) { assert farReferenceClass == null || cls == null; farReferenceClass = cls; } public SPromise eventualSend(final Actor currentActor, final SSymbol selector, final Object[] args) { return actor.eventualSend(currentActor, selector, args); } }
package som.interpreter.actors; import som.vmobjects.SAbstractObject; import som.vmobjects.SClass; import som.vmobjects.SSymbol; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; public final class SFarReference extends SAbstractObject { @CompilationFinal private static SClass farReferenceClass; private final Actor actor; private final Object value; public SFarReference(final Actor actor, final Object value) { this.actor = actor; this.value = value; } public Actor getActor() { return actor; } public Object getValue() { return value; } @Override public SClass getSOMClass() { return farReferenceClass; } @Override public String toString() { return "FarRef[" + value.toString() + ", " + actor.toString() + "]"; } @Override public boolean isValue() { return true; } public static void setSOMClass(final SClass cls) { assert farReferenceClass == null || cls == null; farReferenceClass = cls; } public SPromise eventualSend(final Actor currentActor, final SSymbol selector, final Object[] args) { return actor.eventualSend(currentActor, selector, args); } }
Add operation name to MyProfileQuery (for logging) fbshipit-source-id: 7d48043
import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import Profile from '../components/Profile'; const MyProfileQuery = gql` query MyProfile { viewer { me { id username firstName lastName email profilePhoto appCount isLegacy apps(limit: 15, offset: 0) { id fullName iconUrl name packageName description lastPublishedTime likeCount } likes(limit: 15, offset: 0) { id } } } } `; export default graphql(MyProfileQuery, { props: props => { let { data } = props; let user; if (data.viewer && data.viewer.me) { user = data.viewer.me; } return { ...props, data: { ...data, user, }, }; }, options: { returnPartialData: true, forceFetch: true, }, })(Profile);
import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import Profile from '../components/Profile'; const MyProfileQuery = gql` { viewer { me { id username firstName lastName email profilePhoto appCount isLegacy apps(limit: 15, offset: 0) { id fullName iconUrl name packageName description lastPublishedTime likeCount } likes(limit: 15, offset: 0) { id } } } } ` export default graphql(MyProfileQuery, { props: (props) => { let { data } = props; let user; if (data.viewer && data.viewer.me) { user = data.viewer.me; } return { ...props, data: { ...data, user, }, }; }, options: { returnPartialData: true, forceFetch: true, }, })(Profile);
Debug flags back to false. Can't use it on prod D: This reverts commit 4bf055370da89b13fbe4d1076562183d661904ce.
import os from flask import Flask from flask import render_template from flask import send_from_directory import zip_codes import weather app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/<zip_code>") def forecast(zip_code): if not zip_codes.is_listed(zip_code): return render_template("wrong_zip.html", zip_code=zip_code),404 city = "/".join(zip_codes.city(zip_code)) txt = weather.forecast_txt(zip_code) forecast = weather.parse(txt) print(forecast) return render_template("forecast.html",city=city,forecast=forecast) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('500.html'), 500 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static/img'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') if __name__ == "__main__": app.run(debug=False)
import os from flask import Flask from flask import render_template from flask import send_from_directory import zip_codes import weather app = Flask(__name__) app.debug = True @app.route("/") def index(): return render_template('index.html') @app.route("/<zip_code>") def forecast(zip_code): if not zip_codes.is_listed(zip_code): return render_template("wrong_zip.html", zip_code=zip_code),404 city = "/".join(zip_codes.city(zip_code)) txt = weather.forecast_txt(zip_code) forecast = weather.parse(txt) print(forecast) return render_template("forecast.html",city=city,forecast=forecast) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('500.html'), 500 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static/img'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') if __name__ == "__main__": app.run(debug=True)
Remove unnecessary stripCredits() function from Course
module.exports = { Course: function Course(subject, number, credits) { this.subject = subject; this.number = number; this.credits = credits; }, /** * Creates a new CourseEquivalency. * * @param keyCourse Course to perform lookups on. Created with only subject * and number, no credits * @param input Array of courses from NVCC * @param output Array of ocurses from `institution` * @param type Equivalency type. Must be a value specified by models.TYPE_* */ CourseEquivalency: function CourseEquivalency(input, output, type) { this.keyCourse = new module.exports.Course(input[0].subject, input[0].number); this.input = input; this.output = output this.type = type; }, EquivalencyContext: function EquivalencyContext(institution, equivalencies) { this.institution = institution; this.equivalencies = equivalencies; }, Institution: function(acronym, fullName) { this.acronym = acronym; this.fullName = fullName; }, // No information about credits given CREDITS_UNKNOWN: -1, // A student should check with the university for further clarificaiton CREDITS_UNCLEAR: -2 };
module.exports = { Course: function Course(subject, number, credits) { this.subject = subject; this.number = number; if (credits !== undefined) this.credits = credits; this.stripCredits = function() { return new Course(subject, number); }; }, /** * Creates a new CourseEquivalency. * * @param keyCourse Course to perform lookups on. Created with only subject * and number, no credits * @param input Array of courses from NVCC * @param output Array of ocurses from `institution` */ CourseEquivalency: function CourseEquivalency(input, output) { this.keyCourse = input[0].stripCredits(); this.input = input; this.output = output; }, EquivalencyContext: function EquivalencyContext(institution, equivalencies) { this.institution = institution; this.equivalencies = equivalencies; }, Institution: function(acronym, fullName) { this.acronym = acronym; this.fullName = fullName; }, // No information about credits given CREDITS_UNKNOWN: -1, // A student should check with the university for further clarificaiton CREDITS_UNCLEAR: -2 };
Add all sorts of mongolab stuff
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // connect to mongo database named "bolt" // mongoose.connect('mongodb://localhost/bolt'); mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp'); // mongoose.connect(process.env.MONGOLAB_URI, function (error) { // if (error) console.error(error); // else console.log('mongo connected'); // }); // MONGOLAB_URI: mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp // Also maybe the MONGOLAB_URI: mongodb://elliotaplant:bolt1738@ds029605.mongolab.com:29605/heroku_l3g4r0kp // API key: kyYsvLVM95SVVl9EKZ-dbfX0LzejuVJf // uesrname: elliotaplant // password: bolt1738 // configure our server with all the middleware and routing require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function() { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // connect to mongo database named "bolt" mongoose.connect('mongodb://localhost/bolt'); mongoose.connect(process.env.MONGOLAB_URI, function (error) { if (error) console.error(error); else console.log('mongo connected'); }); // API key: kyYsvLVM95SVVl9EKZ-dbfX0LzejuVJf // configure our server with all the middleware and routing require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function() { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
Allow newer version of docutils (==0.8.1 changed to >=0.8.1, current version is 0.13.1)
#!/usr/bin/env python2 from setuptools import setup from wok import version setup( name='wok', version=version.encode("utf8"), author='Mike Cooper', author_email='mythmon@gmail.com', url='http://wok.mythmon.com', description='Static site generator', long_description= "Wok is a static website generator. It turns a pile of templates, " "content, and resources (like CSS and images) into a neat stack of " "plain HTML. You run it on your local computer, and it generates a " "directory of web files that you can upload to your web server, or " "serve directly.", download_url="http://wok.mythmon.com/download", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", 'Operating System :: POSIX', 'Programming Language :: Python', ], install_requires=[ 'Jinja2==2.6', 'Markdown==2.6.5', 'PyYAML==3.10', 'Pygments==2.1', 'docutils>=0.8.1', 'awesome-slugify==1.4', 'pytest==2.5.2', ], packages=['wok'], package_data={'wok':['contrib/*']}, scripts=['scripts/wok'], )
#!/usr/bin/env python2 from setuptools import setup from wok import version setup( name='wok', version=version.encode("utf8"), author='Mike Cooper', author_email='mythmon@gmail.com', url='http://wok.mythmon.com', description='Static site generator', long_description= "Wok is a static website generator. It turns a pile of templates, " "content, and resources (like CSS and images) into a neat stack of " "plain HTML. You run it on your local computer, and it generates a " "directory of web files that you can upload to your web server, or " "serve directly.", download_url="http://wok.mythmon.com/download", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", 'Operating System :: POSIX', 'Programming Language :: Python', ], install_requires=[ 'Jinja2==2.6', 'Markdown==2.6.5', 'PyYAML==3.10', 'Pygments==2.1', 'docutils==0.8.1', 'awesome-slugify==1.4', 'pytest==2.5.2', ], packages=['wok'], package_data={'wok':['contrib/*']}, scripts=['scripts/wok'], )
Throw an exception when we hit an impossible condition rather than returning null
package com.bungleton.yarrgs; import com.bungleton.yarrgs.parser.Command; public class Yarrgs { public static <T> T parseInMain (Class<T> argsType, String[] args) { try { return parse(argsType, args); } catch (YarrgParseException e) { System.err.println(e.getUsage() + "\n" + e.getMessage()); System.exit(1); throw new IllegalStateException("Java continued past a System.exit call"); } } public static <T> T parse (Class<T> argsType, String[] args) throws YarrgParseException { T t; try { t = argsType.newInstance(); } catch (Exception e) { throw new YarrgConfigurationException("'" + argsType + "' must have a public no-arg constructor", e); } new Command(t).parse(args); return t; } }
package com.bungleton.yarrgs; import com.bungleton.yarrgs.parser.Command; public class Yarrgs { public static <T> T parseInMain (Class<T> argsType, String[] args) { try { return parse(argsType, args); } catch (YarrgParseException e) { System.err.println(e.getUsage() + "\n" + e.getMessage()); System.exit(1); return null; } } public static <T> T parse (Class<T> argsType, String[] args) throws YarrgParseException { T t; try { t = argsType.newInstance(); } catch (Exception e) { throw new YarrgConfigurationException("'" + argsType + "' must have a public no-arg constructor", e); } new Command(t).parse(args); return t; } }
Fix eslint errors - 5
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now(); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; return { text, start, end, importance, }; } module.exports = parse;
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { query = query; /** * Day, week or month coefficient * @type {Object} */ var dwm = { d: 1, '': 1, w: 7, m: 30 }; var regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; var regexResult = regex.exec(query); var text = query.slice(0, regexResult.index); var start = Date.now(); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } var end = start + 86400000 * regexResult[1] * dwm[regexResult[2]]; var importance = regexResult[6].length + 1; console.log(importance); return { text, start, end, importance }; } module.exports = parse;
Fix execution condition of content script.
// Enable chromereload by uncommenting this line: //import 'chromereload/devonly'; const isValidPage = () => { return document.getElementsByClassName('js-contribution-graph').length > 0; }; const convertRGBToHex = (rgb) => { const ret = eval(rgb.replace(/rgb/,"((").replace(/,/ig,")*256+")).toString(16); return "#" + (("000000" + ret).substring( 6 + ret.length - 6)); }; const colorizeCntributionRect = (selectedLevel) => { const contributionRects = document.getElementsByTagName('rect'); Array.prototype.forEach.call(contributionRects, (rect) => { const highlightColor = '#bb102e'; const currentFillColor = rect.getAttribute('fill'); const originalFillColor = rect.getAttribute('fill-org'); if (selectedLevel === currentFillColor) { rect.setAttribute('fill-org', currentFillColor) rect.setAttribute('fill', highlightColor); } else { if (originalFillColor) { rect.setAttribute('fill', originalFillColor); rect.removeAttribute('fill-org'); } } }); }; if (isValidPage()) { Array.prototype.forEach.call(document.getElementsByClassName('legend')[0].children, (element) => { element.addEventListener('click', () => { colorizeCntributionRect(convertRGBToHex(element.style['background-color'])); }, false); }); }
// Enable chromereload by uncommenting this line: //import 'chromereload/devonly'; const isValidPage = () => { return (() => { const target = document.getElementsByClassName('js-contribution-graph'); return target ? target[0] : null; })() !== null; }; const convertRGBToHex = (rgb) => { const ret = eval(rgb.replace(/rgb/,"((").replace(/,/ig,")*256+")).toString(16); return "#" + (("000000" + ret).substring( 6 + ret.length - 6)); }; const colorizeCntributionRect = (selectedLevel) => { const contributionRects = document.getElementsByTagName('rect'); Array.prototype.forEach.call(contributionRects, (rect) => { const highlightColor = '#bb102e'; const currentFillColor = rect.getAttribute('fill'); const originalFillColor = rect.getAttribute('fill-org'); if (selectedLevel === currentFillColor) { rect.setAttribute('fill-org', currentFillColor) rect.setAttribute('fill', highlightColor); } else { if (originalFillColor) { rect.setAttribute('fill', originalFillColor); rect.removeAttribute('fill-org'); } } }); }; if (isValidPage()) { Array.prototype.forEach.call(document.getElementsByClassName('legend')[0].children, (element) => { element.addEventListener('click', () => { colorizeCntributionRect(convertRGBToHex(element.style['background-color'])); }, false); }); }
Make it easier to see when the example app is listening.
package main import ( // "fmt" "log" "net/http" "github.com/codykrieger/jeeves" ) func main() { j := jeeves.New() j.RegisterSkill(&jeeves.Skill{ Name: "Hello", Endpoint: "/skills/hello", ApplicationID: "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe", Handler: helloHandler, }) log.Println("Listening...") log.Fatal(http.ListenAndServe(":3000", j)) } func helloHandler(skill *jeeves.Skill, req *jeeves.ASKRequest) *jeeves.ASKResponse { resp := jeeves.NewASKResponse(req) if req.IsLaunchRequest() { resp.Body.OutputSpeech = jeeves.NewASKOutputSpeech("Hello there!") } else if req.IsIntentRequest() { } else if req.IsSessionEndedRequest() { } return resp }
package main import ( // "fmt" "log" "net/http" "github.com/codykrieger/jeeves" ) func main() { j := jeeves.New() j.RegisterSkill(&jeeves.Skill{ Name: "Hello", Endpoint: "/skills/hello", ApplicationID: "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe", Handler: helloHandler, }) log.Fatal(http.ListenAndServe(":3000", j)) } func helloHandler(skill *jeeves.Skill, req *jeeves.ASKRequest) *jeeves.ASKResponse { resp := jeeves.NewASKResponse(req) if req.IsLaunchRequest() { resp.Body.OutputSpeech = jeeves.NewASKOutputSpeech("Hello there!") } else if req.IsIntentRequest() { } else if req.IsSessionEndedRequest() { } return resp }
Drop Sort alias for Collect.
// setup transform definition aliases import {definition} from 'vega-dataflow'; definition('Formula', definition('Apply')); export {default as parse} from './src/parse'; export {default as selector} from './src/parsers/event-selector'; export {default as signal} from './src/parsers/signal'; export {default as signalUpdates} from './src/parsers/signal-updates'; export {default as stream} from './src/parsers/stream'; export { MarkRole, FrameRole, ScopeRole, AxisRole, AxisDomainRole, AxisGridRole, AxisLabelRole, AxisTickRole, AxisTitleRole, LegendRole, LegendEntryRole, LegendLabelRole, LegendSymbolRole, LegendTitleRole } from './src/parsers/marks/roles'; export {marktypes, isMarkType} from './src/parsers/marks/marktypes'; export {default as Scope} from './src/Scope'; export {default as DataScope} from './src/DataScope';
// setup transform definition aliases import {definition} from 'vega-dataflow'; definition('Sort', definition('Collect')); definition('Formula', definition('Apply')); export {default as parse} from './src/parse'; export {default as selector} from './src/parsers/event-selector'; export {default as signal} from './src/parsers/signal'; export {default as signalUpdates} from './src/parsers/signal-updates'; export {default as stream} from './src/parsers/stream'; export { MarkRole, FrameRole, ScopeRole, AxisRole, AxisDomainRole, AxisGridRole, AxisLabelRole, AxisTickRole, AxisTitleRole, LegendRole, LegendEntryRole, LegendLabelRole, LegendSymbolRole, LegendTitleRole } from './src/parsers/marks/roles'; export {marktypes, isMarkType} from './src/parsers/marks/marktypes'; export {default as Scope} from './src/Scope'; export {default as DataScope} from './src/DataScope';
Fix namespace and class name
<?php namespace Symfony\Bundle\ChainRoutingBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class ChainRoutingExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('chain_routing.xml'); } }
<?php namespace Symfony\Bundle\ChainRoutingBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class ChainRoutingExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('chain_routing.xml'); } }
Use numatune but use mode preferred
import glob import subprocess from .read import read class Virsh: """Class can be used to execute virsh commands for a given domain""" domain = "" def __init__(self, domain): self.domain = domain @staticmethod def get_domain_list(): pid_files = glob.glob('/var/run/libvirt/qemu/*.pid') domain_list = {} for pid_file in pid_files: # read the pid domain_list[pid_file] = read(pid_file) return domain_list def execute(self, arguments): output = subprocess.check_output(["virsh"] + arguments, stderr=subprocess.STDOUT) return output.decode('utf-8') def migrate_to(self, zone): self.execute(["numatune", self.domain, "--nodeset", str(zone.number), "--mode", "preferred"]) def is_running(self): output = self.execute(["domstate", self.domain]) domstate = output.strip('\n').strip(' ').strip('\n') return domstate == 'running' def get_pid(self): pid = read(self.get_pid_file()) return pid def get_pid_file(self): return '/var/run/libvirt/qemu/' + self.domain + '.pid'
import glob import subprocess from .read import read class Virsh: """Class can be used to execute virsh commands for a given domain""" domain = "" def __init__(self, domain): self.domain = domain @staticmethod def get_domain_list(): pid_files = glob.glob('/var/run/libvirt/qemu/*.pid') domain_list = {} for pid_file in pid_files: # read the pid domain_list[pid_file] = read(pid_file) return domain_list def execute(self, arguments): output = subprocess.check_output(["virsh"] + arguments, stderr=subprocess.STDOUT) return output.decode('utf-8') def migrate_to(self, zone): subprocess.call(["migratepages", self.get_pid, "all", str(zone.number)]) def is_running(self): output = self.execute(["domstate", self.domain]) domstate = output.strip('\n').strip(' ').strip('\n') return domstate == 'running' def get_pid(self): pid = read(self.get_pid_file()) return pid def get_pid_file(self): return '/var/run/libvirt/qemu/' + self.domain + '.pid'
Fix DictStream join precedence (right was overriding left improperly)
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
Fix returned name for date
'use strict' const Record = require('../schemas/Record') const aggregateTopFields = require('../aggregations/aggregateTopFields') const aggregateRecentFields = require('../aggregations/aggregateRecentFields') const aggregateNewFields = require('../aggregations/aggregateNewFields') const sortings = require('../constants/sortings') const createDate = require('../utils/createDate') const get = async (ids, sorting, range, limit, dateDetails) => { const enhance = (entries) => { return entries.map((entry) => ({ id: entry._id.siteReferrer, count: entry.count, created: createDate(dateDetails.userTimeZone, entry.created).userZonedDate })) } const aggregation = (() => { if (sorting === sortings.SORTINGS_TOP) return aggregateTopFields(ids, [ 'siteReferrer' ], range, limit, dateDetails) if (sorting === sortings.SORTINGS_NEW) return aggregateNewFields(ids, [ 'siteReferrer' ], limit) if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentFields(ids, [ 'siteReferrer' ], limit) })() return enhance( await Record.aggregate(aggregation) ) } module.exports = { get }
'use strict' const Record = require('../schemas/Record') const aggregateTopFields = require('../aggregations/aggregateTopFields') const aggregateRecentFields = require('../aggregations/aggregateRecentFields') const aggregateNewFields = require('../aggregations/aggregateNewFields') const sortings = require('../constants/sortings') const createDate = require('../utils/createDate') const get = async (ids, sorting, range, limit, dateDetails) => { const enhance = (entries) => { return entries.map((entry) => ({ id: entry._id.siteReferrer, count: entry.count, date: createDate(dateDetails.userTimeZone, entry.created).userZonedDate })) } const aggregation = (() => { if (sorting === sortings.SORTINGS_TOP) return aggregateTopFields(ids, [ 'siteReferrer' ], range, limit, dateDetails) if (sorting === sortings.SORTINGS_NEW) return aggregateNewFields(ids, [ 'siteReferrer' ], limit) if (sorting === sortings.SORTINGS_RECENT) return aggregateRecentFields(ids, [ 'siteReferrer' ], limit) })() return enhance( await Record.aggregate(aggregation) ) } module.exports = { get }
Create mongo schema and prepare routes generator
/** * Module dependencies. */ var fs = require('fs'); var mongoose = require('mongoose'); /** * Application prototype. */ var res = Resources.prototype; /** * Expose `Resources`. */ exports = module.exports = Resources; /** * Initialize Resources object * * @return {Object} Returns api object * @api public */ function Resources(app) { if (!(this instanceof Resources)) return new Resources(app); this.app = app; // Array for registered resources this.app.resources = this.resources = {}; this.filesRoot = process.cwd() + '/app/resources/'; this.loadFiles(); this.buildModels(); this.buildRoutes(); } res.loadFiles = function() { this.resourceFiles = fs.readdirSync(this.filesRoot); var i = this.resourceFiles.length while (i--) { this.resources[this.resourceFiles[i].split('.')[0]] = { blueprint: require(this.filesRoot + this.resourceFiles[i]) }; } } res.buildModels = function() { var keys = Object.keys(this.resources); var i = keys.length; while (i--) { var name = keys[i]; var resource = this.resources[name]; var schema = new mongoose.Schema(resource.blueprint.schema); resource.model = mongoose.model(name, schema); } } res.buildRoutes = function() { var keys = Object.keys(this.resources); var i = keys.length; while (i--) { var name = keys[i]; var resource = this.resources[name]; console.log("Building routes for "+ name); } }
/** * Module dependencies. */ var fs = require('fs'); var mongoose = require('mongoose'); /** * Application prototype. */ var res = Resources.prototype; /** * Expose `Resources`. */ exports = module.exports = Resources; /** * Initialize Resources object * * @return {Object} Returns api object * @api public */ function Resources(app) { if (!(this instanceof Resources)) return new Resources(app); this.app = app; // Array for registered resources this.app.resources = this.resources = {}; this.filesRoot = process.cwd() + '/app/resources/'; this.loadFiles(); this.buildModels(); } res.loadFiles = function() { this.resourceFiles = fs.readdirSync(this.filesRoot); var i = this.resourceFiles.length while (i--) { this.resources[this.resourceFiles[i].split('.')[0]] = { data: require(this.filesRoot + this.resourceFiles[i]) }; } } res.buildModels = function() { var keys = Object.keys(this.resources); var i = keys.length; while (i--) { var name = keys[i]; var resource = this.resources[name]; var schema = new mongoose.Schema(resource.data); resource.model = mongoose.model(name, schema); } }
Add config to publish command
<?php namespace Pixelpeter\Genderize; use Illuminate\Support\ServiceProvider; class GenderizeServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->mergeConfigFrom(__DIR__ . '/../config/genderize.php', 'genderize'); $this->publishes([ __DIR__ . '/../config/genderize.php' => config_path('genderize.php'), ]); } /** * Register the application services. * * @return void */ public function register() { $app = $this->app; $app->bind('Pixelpeter\Genderize\GenderizeClient', function () { return new GenderizeClient(new \Unirest\Request); }); $app->alias('Pixelpeter\Genderize\GenderizeClient', 'genderize'); } }
<?php namespace Pixelpeter\Genderize; use Illuminate\Support\ServiceProvider; class GenderizeServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->mergeConfigFrom(__DIR__ . '/../config/genderize.php', 'genderize'); } /** * Register the application services. * * @return void */ public function register() { $app = $this->app; $app->bind('Pixelpeter\Genderize\GenderizeClient', function () { return new GenderizeClient(new \Unirest\Request); }); $app->alias('Pixelpeter\Genderize\GenderizeClient', 'genderize'); } }
Update the PyPI version to 7.0.9.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.9', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.8', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Make GO term export part of FTP export
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import luigi from .md5 import Md5Export from .id_mapping import IdExport from .rfam import RfamAnnotationExport from .fasta import FastaExport from .ensembl import EnsemblExport from .go_annotations import GoAnnotationExport class FtpExport(luigi.WrapperTask): def requires(self): yield Md5Export yield IdExport yield RfamAnnotationExport yield FastaExport yield EnsemblExport yield GoAnnotationExport
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import luigi from .md5 import Md5Export from .id_mapping import IdExport from .rfam import RfamAnnotationExport from .fasta import FastaExport from .ensembl import EnsemblExport class FtpExport(luigi.WrapperTask): def requires(self): yield Md5Export yield IdExport yield RfamAnnotationExport yield FastaExport yield EnsemblExport
Bump package version to 0.1.14
from setuptools import setup setup(name='mypytools', version='0.1.14', description='A bundle of tools to make using mypy easier', url='https://github.com/nylas/mypy-tools', license='MIT', install_requires=[ 'click', 'findimports', 'typing', 'watchdog' ], packages=['mypytools', 'mypytools.server'], scripts=[ 'bin/check_mypy_annotations.py', 'bin/mypy_server.py', 'bin/print_mypy_coverage.py', ], zip_safe=False)
from setuptools import setup setup(name='mypytools', version='0.1.13', description='A bundle of tools to make using mypy easier', url='https://github.com/nylas/mypy-tools', license='MIT', install_requires=[ 'click', 'findimports', 'typing', 'watchdog' ], packages=['mypytools', 'mypytools.server'], scripts=[ 'bin/check_mypy_annotations.py', 'bin/mypy_server.py', 'bin/print_mypy_coverage.py', ], zip_safe=False)
Fix gravatar when user has no email
<?= $this->render('//layouts/gravatar', [ 'email' => Yii::$app->user->identity->email, 'size' => 90, ]) ?> <p> <b><?= Yii::$app->user->identity->username ?></b> <?php if (Yii::$app->user->can('support') && isset(Yii::$app->user->identity->seller)) : ?> <?= ' / ' . Yii::$app->user->identity->seller ?> <?php endif ?> <?php if (Yii::$app->user->can('support')) : ?> <small><?= Yii::$app->user->identity->type ?></small> <?php else : ?> <br> <?php endif ?> <?php if (Yii::$app->user->identity->name) : ?> <?= Yii::$app->user->identity->name ?> <?php endif ?> </p>
<?= $this->render('//layouts/gravatar', ['size' => 90]) ?> <p> <b><?= Yii::$app->user->identity->username ?></b> <?php if (Yii::$app->user->can('support') && isset(Yii::$app->user->identity->seller)) : ?> <?= ' / ' . Yii::$app->user->identity->seller ?> <?php endif ?> <?php if (Yii::$app->user->can('support')) : ?> <small><?= Yii::$app->user->identity->type ?></small> <?php else : ?> <br> <?php endif ?> <?php if (Yii::$app->user->identity->name) : ?> <?= Yii::$app->user->identity->name ?> <?php endif ?> </p>