text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add method to retrieve dynamic attributes
<?php namespace PhpAbac\Manager; use PhpAbac\Repository\AttributeRepository; use PhpAbac\Model\AbstractAttribute; use PhpAbac\Model\Attribute; class AttributeManager { /** @var AttributeRepository **/ protected $repository; public function __construct() { $this->repository = new AttributeRepository(); } /** * @param string $name * @param string $table * @param string $column * @param string $criteriaColumn * @return Attribute */ public function create($name, $table, $column, $criteriaColumn) { return $this->repository->createAttribute($name, $table, $column, $criteriaColumn); } /** * @param AbstractAttribute $attribute * @param string $attributeType * @param int $userId * @param int $objectId */ public function retrieveAttribute(AbstractAttribute $attribute, $attributeType, $userId, $objectId) { // The switch is important. // Even if we call the same method for the two first cases, // the given argument isn't the same. switch($attributeType) { case 'user': $this->repository->retrieveAttribute($attribute, $userId); break; case 'object': $this->repository->retrieveAttribute($attribute, $objectId); break; case 'environment': $attribute->setValue(getenv($attribute->getVariableName())); break; } } /** * @param string $slug * @param array $dynamicAttributes * @return mixed * @throws \InvalidArgumentException */ public function getDynamicAttribute($slug, $dynamicAttributes = []) { if(!isset($dynamicAttributes[$slug])) { throw new \InvalidArgumentException('The "'.$slug.'" attribute is dynamic and its value must be given'); } return $dynamicAttributes[$slug]; } }
<?php namespace PhpAbac\Manager; use PhpAbac\Repository\AttributeRepository; use PhpAbac\Model\AbstractAttribute; use PhpAbac\Model\Attribute; use PhpAbac\Model\EnvironmentAttribute; class AttributeManager { /** @var AttributeRepository **/ protected $repository; public function __construct() { $this->repository = new AttributeRepository(); } /** * @param string $name * @param string $table * @param string $column * @param string $criteriaColumn * @return Attribute */ public function create($name, $table, $column, $criteriaColumn) { return $this->repository->createAttribute($name, $table, $column, $criteriaColumn); } /** * @param AbstractAttribute $attribute * @param string $attributeType * @param int $userId * @param int $objectId */ public function retrieveAttribute(AbstractAttribute $attribute, $attributeType, $userId, $objectId) { // The switch is important. // Even if we call the same method for the two first cases, // the given argument isn't the same. switch($attributeType) { case 'user': $this->repository->retrieveAttribute($attribute, $userId); break; case 'object': $this->repository->retrieveAttribute($attribute, $objectId); break; case 'environment': $attribute->setValue(getenv($attribute->getVariableName())); break; } } }
Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <[email protected]>
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock if isinstance(sock, urllib3.contrib.pyopenssl.WrappedSocket): sock = sock.socket sock.shutdown(socket.SHUT_RDWR) sock.close()
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... print event >>> # and cancel from another thread >>> events.close() """ def __init__(self, stream, response): self._stream = stream self._response = response def __iter__(self): return self def __next__(self): try: return next(self._stream) except urllib3.exceptions.ProtocolError: raise StopIteration except socket.error: raise StopIteration next = __next__ def close(self): """ Closes the event streaming. """ if not self._response.raw.closed: # find the underlying socket object # based on api.client._get_raw_response_socket sock_fp = self._response.raw._fp.fp if hasattr(sock_fp, 'raw'): sock_raw = sock_fp.raw if hasattr(sock_raw, 'sock'): sock = sock_raw.sock elif hasattr(sock_raw, '_sock'): sock = sock_raw._sock else: sock = sock_fp._sock sock.shutdown(socket.SHUT_RDWR) sock.close()
Apply phpqa using PSR2 standards
<?php /** * @file * Contains Drupal\AppConsole\Test\Generator\PluginBlockGeneratorTest. */ namespace Drupal\AppConsole\Test\Generator; use Drupal\AppConsole\Generator\PluginBlockGenerator; use Drupal\AppConsole\Test\DataProvider\PluginBlockDataProviderTrait; class PluginBlockGeneratorTest extends GeneratorTest { use PluginBlockDataProviderTrait; /** * PluginBlock generator test * * @param $module * @param $class_name * @param $label * @param $plugin_id * @param $services * @param $inputs * * @dataProvider commandData */ public function testGeneratePluginBlock( $module, $class_name, $label, $plugin_id, $services, $inputs ) { $generator = new PluginBlockGenerator(); $generator->setSkeletonDirs(__DIR__ . '/../../templates'); $generator->setHelpers($this->getHelperSet()); $generator->generate( $module, $class_name, $label, $plugin_id, $services, $inputs ); $this->assertTrue( file_exists($generator->getSite()->getPluginPath($module, 'Block').'/'.$class_name.'.php'), sprintf('%s does not exist', $class_name.'.php') ); } }
<?php /** * @file * Contains Drupal\AppConsole\Test\Generator\PluginBlockGeneratorTest. */ namespace Drupal\AppConsole\Test\Generator; use Drupal\AppConsole\Generator\PluginBlockGenerator; use Drupal\AppConsole\Test\DataProvider\PluginBlockDataProviderTrait; class PluginBlockGeneratorTest extends GeneratorTest { use PluginBlockDataProviderTrait; /** * PluginBlock generator test * * @param $module * @param $class_name * @param $label * @param $plugin_id * @param $services * @param $inputs * * @dataProvider commandData */ public function testGeneratePluginBlock( $module, $class_name, $label, $plugin_id, $services, $inputs ) { $generator = new PluginBlockGenerator(); $generator->setSkeletonDirs(__DIR__ . '/../../templates'); $generator->setHelpers($this->getHelperSet()); $generator->generate( $module, $class_name, $label, $plugin_id, $services, $inputs ); $this->assertTrue( file_exists($generator->getSite()->getPluginPath($module, 'Block').'/'.$class_name.'.php'), sprintf('%s does not exist', $class_name.'.php') ); } }
Allow for higher versions of werkzeug Install fails when a version of `werkzeug` greater than `0.10` is already present in the environment (current version is `0.10.4`)
from setuptools import setup, find_packages setup(name='googleanalytics', description='A wrapper for the Google Analytics API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='https://github.com/debrouwere/google-analytics/', download_url='http://www.github.com/debrouwere/google-analytics/tarball/master', version='0.16.2', license='ISC', packages=find_packages(), keywords='data analytics api wrapper google', scripts=[ 'bin/googleanalytics' ], install_requires=[ 'oauth2client>=1.4.6', 'google-api-python-client==1.4', 'python-dateutil', 'addressable>=1.4.2', 'inspect-it>=0.3.2', 'werkzeug>=0.10', 'keyring==5.3', 'click==3.3', 'pyyaml>=3', ], test_suite='googleanalytics.tests', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup, find_packages setup(name='googleanalytics', description='A wrapper for the Google Analytics API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='https://github.com/debrouwere/google-analytics/', download_url='http://www.github.com/debrouwere/google-analytics/tarball/master', version='0.16.2', license='ISC', packages=find_packages(), keywords='data analytics api wrapper google', scripts=[ 'bin/googleanalytics' ], install_requires=[ 'oauth2client>=1.4.6', 'google-api-python-client==1.4', 'python-dateutil', 'addressable>=1.4.2', 'inspect-it>=0.3.2', 'werkzeug==0.10', 'keyring==5.3', 'click==3.3', 'pyyaml>=3', ], test_suite='googleanalytics.tests', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
Revert "Revert "api key deleted from the list of required parameters""
package org.atlasapi.application.auth; import static com.google.common.base.Preconditions.checkNotNull; import javax.servlet.http.HttpServletRequest; import org.atlasapi.application.Application; import org.atlasapi.application.ApplicationSources; import org.atlasapi.application.ApplicationStore; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher { public static final String API_KEY_QUERY_PARAMETER = "key"; private final ApplicationStore reader; public ApiKeySourcesFetcher(ApplicationStore reader) { this.reader = checkNotNull(reader); } @Override public ImmutableSet<String> getParameterNames() { return ImmutableSet.of(); } @Override public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException { String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER); if (apiKey == null) { apiKey = request.getHeader(API_KEY_QUERY_PARAMETER); } if (apiKey != null) { Optional<Application> app = reader.applicationForKey(apiKey); if (!app.isPresent() || app.get().isRevoked()) { throw new InvalidApiKeyException(apiKey); } return Optional.of(app.get().getSources()); } return Optional.absent(); } }
package org.atlasapi.application.auth; import static com.google.common.base.Preconditions.checkNotNull; import javax.servlet.http.HttpServletRequest; import org.atlasapi.application.Application; import org.atlasapi.application.ApplicationSources; import org.atlasapi.application.ApplicationStore; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher { public static final String API_KEY_QUERY_PARAMETER = "key"; private final ApplicationStore reader; public ApiKeySourcesFetcher(ApplicationStore reader) { this.reader = checkNotNull(reader); } @Override public ImmutableSet<String> getParameterNames() { return ImmutableSet.of(API_KEY_QUERY_PARAMETER); } @Override public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException { String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER); if (apiKey == null) { apiKey = request.getHeader(API_KEY_QUERY_PARAMETER); } if (apiKey != null) { Optional<Application> app = reader.applicationForKey(apiKey); if (!app.isPresent() || app.get().isRevoked()) { throw new InvalidApiKeyException(apiKey); } return Optional.of(app.get().getSources()); } return Optional.absent(); } }
Fix open call for LICENSE.txt Closes #76
#!/usr/bin/env python # -*- coding: utf-8 -*- from pytube import __version__ try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('LICENSE.txt') as readme_file: license = readme_file.read() setup( name="pytube", version=__version__, author="Nick Ficano", author_email="[email protected]", packages=['pytube'], url="https://github.com/nficano/pytube", license=license, scripts=['scripts/pytube'], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS", "Operating System :: Microsoft", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python", "Topic :: Internet", "Topic :: Multimedia :: Video", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Terminals", "Topic :: Utilities", ], description=("A Python library for downloading YouTube videos."), long_description=readme, zip_safe=True, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from pytube import __version__ try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('LICENSE') as readme_file: license = readme_file.read() setup( name="pytube", version=__version__, author="Nick Ficano", author_email="[email protected]", packages=['pytube'], url="https://github.com/nficano/pytube", license=license, scripts=['scripts/pytube'], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS", "Operating System :: Microsoft", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python", "Topic :: Internet", "Topic :: Multimedia :: Video", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Terminals", "Topic :: Utilities", ], description=("A Python library for downloading YouTube videos."), long_description=readme, zip_safe=True, )
Change empy Subsystem wrapper to old style class.
#!/usr/bin/env python """Provide the empy templating engine.""" from __future__ import print_function import os.path import em from . import Engine class SubsystemWrapper(em.Subsystem): """Wrap EmPy's Subsystem class. Allows to open files relative to a base directory. """ def __init__(self, basedir=None, **kwargs): """Initialize Subsystem plus a possible base directory.""" em.Subsystem.__init__(self, **kwargs) self.basedir = basedir def open(self, name, *args, **kwargs): """Open file, possibly relative to a base directory.""" if self.basedir is not None: name = os.path.join(self.basedir, name) return em.Subsystem.open(self, name, *args, **kwargs) class EmpyEngine(Engine): """Empy templating engine.""" handle = 'empy' def __init__(self, template, dirname=None, **kwargs): """Initialize empy template.""" super(EmpyEngine, self).__init__(**kwargs) if dirname is not None: # FIXME: This is a really bad idea, as it works like a global. # Blame EmPy. em.theSubsystem = SubsystemWrapper(basedir=dirname) self.template = template def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" return em.expand(self.template, mapping)
#!/usr/bin/env python """Provide the empy templating engine.""" from __future__ import print_function import os.path import em from . import Engine class SubsystemWrapper(em.Subsystem): """Wrap EmPy's Subsystem class. Allows to open files relative to a base directory. """ def __init__(self, basedir=None, **kwargs): """Initialize Subsystem plus a possible base directory.""" super(SubsystemWrapper, self).__init__(**kwargs) self.basedir = basedir def open(self, name, *args, **kwargs): """Open file, possibly relative to a base directory.""" if self.basedir is not None: name = os.path.join(self.basedir, name) return super(SubsystemWrapper, self).open(name, *args, **kwargs) class EmpyEngine(Engine): """Empy templating engine.""" handle = 'empy' def __init__(self, template, dirname=None, **kwargs): """Initialize empy template.""" super(EmpyEngine, self).__init__(**kwargs) if dirname is not None: # FIXME: This is a really bad idea, as it works like a global. # Blame EmPy. em.theSubsystem = SubsystemWrapper(basedir=dirname) self.template = template def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" return em.expand(self.template, mapping)
Add function to get stats
<?php namespace OrgManager\ApiClient; use GuzzleHttp\Client; class OrgManager { /** @var \GuzzleHttp\Client */ protected $client; /** @var string */ protected $baseUrl; /** * @param \GuzzleHttp\Client $client * @param string $apiToken * @param string $rootUrl */ public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com') { $this->client = $client; $this->apiToken = $apiToken; $this->baseUrl = $rootUrl.'/api'; } /** * * @return array */ public function getRoot() { return $this->get(''); } /** * * @return array */ public function getStats() { return $this->get('/stats'); } /** * @param string $resource * @param array $query * * @return array */ public function get($resource, array $query = []) { $query['api_token'] = $this->apiToken; $results = $this->client ->get("{$this->baseUrl}{$resource}", compact('query')) ->getBody() ->getContents(); return json_decode($results, true); } }
<?php namespace OrgManager\ApiClient; use GuzzleHttp\Client; class OrgManager { /** @var \GuzzleHttp\Client */ protected $client; /** @var string */ protected $baseUrl; /** * @param \GuzzleHttp\Client $client * @param string $apiToken * @param string $rootUrl */ public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com') { $this->client = $client; $this->apiToken = $apiToken; $this->baseUrl = $rootUrl.'/api'; } /** * * @return array */ public function getRoot() { return $this->get(''); } /** * @param string $resource * @param array $query * * @return array */ public function get($resource, array $query = []) { $query['api_token'] = $this->apiToken; $results = $this->client ->get("{$this->baseUrl}{$resource}", compact('query')) ->getBody() ->getContents(); return json_decode($results, true); } }
BUG: Fix typo in variable name.
"""Aligner for texts and their segmentations. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals __all__ = ['AlignmentFailed', 'Aligner'] class AlignmentFailed(Exception): pass class Aligner(object): """Align a text with its tokenization. """ def align(self, text, tokens): """Align text with its tokeniation. Parameters ---------- text : str Text. tokens : list of str Tokenization of ``text``. Returns ------- spans : list of tuple List of (``onset``, ``offset``) pairs, where ``spans[i]`` gives the onseta and offset in characters of ``tokens[i]`` relative to the beginning of ``text`` (0-indexed). """ spans = [] bi = 0 for token in tokens: try: token_len = len(token) token_bi = bi + text[bi:].index(token) token_ei = token_bi + token_len - 1 spans.append([token_bi, token_ei]) bi = token_ei + 1 except ValueError: raise AlignmentFailed(token) return spans
"""Aligner for texts and their segmentations. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals __all__ = ['AlignmentFailed', 'Aligner'] class AlignmentFailed(Exception): pass class Aligner(object): """Align a text with its tokenization. """ def align(self, text, tokens): """Align text with its tokeniation. Parameters ---------- text : str Text. tokens : list of str Tokenization of ``text``. Returns ------- spans : list of tuple List of (``onset``, ``offset``) pairs, where ``spans[i]`` gives the onseta and offset in characters of ``tokens[i]`` relative to the beginning of ``text`` (0-indexed). """ spans = [] bi = 0 for token in tokens: try: token_len = len(token) token_bi = bi + txt[bi:].index(token) token_ei = token_bi + token_len - 1 spans.append([token_bi, token_ei]) bi = token_ei + 1 except ValueError: raise AlignmentFailed(token) return spans
Add email to OrganizationInvitation query
import Relay from 'react-relay'; import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants'; export default class OrganizationInvitationCreate extends Relay.Mutation { static fragments = { organization: () => Relay.QL` fragment on Organization { id } ` } getMutation() { return Relay.QL` mutation { organizationInvitationCreate } `; } getFatQuery() { return Relay.QL` fragment on OrganizationInvitationCreatePayload { invitationEdges { node { role user { name } } } } `; } getOptimisticResponse() { return { organizationInvitationEdge: { node: { role: OrganizationMemberRoleConstants.MEMBER } } }; } getConfigs() { return [{ type: 'RANGE_ADD', parentName: 'organization', parentID: this.props.organization.id, connectionName: 'invitations', edgeName: 'organizationInvitationEdge', rangeBehaviors: () => 'prepend' }]; } getVariables() { return { id: this.props.organizationMember.id, emails: this.props.emails, role: this.props.role }; } }
import Relay from 'react-relay'; import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants'; export default class OrganizationInvitationCreate extends Relay.Mutation { static fragments = { organization: () => Relay.QL` fragment on Organization { id } ` } getMutation() { return Relay.QL` mutation { organizationInvitationCreate } `; } getFatQuery() { return Relay.QL` fragment on OrganizationInvitationCreatePayload { invitationEdges { node { role user { name } } } } `; } getOptimisticResponse() { return { organizationInvitationEdge: { node: { role: OrganizationMemberRoleConstants.MEMBER } } }; } getConfigs() { return [{ type: 'RANGE_ADD', parentName: 'organization', parentID: this.props.organization.id, connectionName: 'invitations', edgeName: 'organizationInvitationEdge', rangeBehaviors: () => 'prepend' }]; } getVariables() { return { id: this.props.organizationMember.id, role: this.props.role }; } }
Rename vars in get_all_exits to make it more clear
#!/usr/bin/python3 class Puzzle: def get_all_exits(self, graph): exits = [] for root_node, connected_nodes in graph.items(): for node in connected_nodes: if 'Exit' in node: exits += node return exits def find_all_paths(self, graph, start, end, path=None): if path is None: path = [] path = path + [start] if start == end: return [path] if start not in graph: return [] paths = [] for node in graph[start]: if node not in path: newpaths = self.find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths def solve(self, graph=None): unique_paths = [] for exit in self.get_all_exits(graph): for start, connected_nodes in graph.items(): unique_paths += self.find_all_paths(graph, start, exit) return unique_paths
#!/usr/bin/python3 class Puzzle: def get_all_exits(self, graph): exits = [] for key, value in graph.items(): for item in value: if 'Exit' in item: exits += item return exits def find_all_paths(self, graph, start, end, path=None): if path is None: path = [] path = path + [start] if start == end: return [path] if start not in graph: return [] paths = [] for node in graph[start]: if node not in path: newpaths = self.find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths def solve(self, graph=None): unique_paths = [] for exit in self.get_all_exits(graph): for start, connected_nodes in graph.items(): unique_paths += self.find_all_paths(graph, start, exit) return unique_paths
Change name back to dredd_hooks
# -*- coding: utf-8 -*- from setuptools import find_packages, setup long_desc = open('README.rst').read() setup( name='dredd_hooks', version='0.1.3', url='https://github.com/apiaryio/dredd-hooks-python/', download_url='http://pypi.python.org/pypi/dredd_hooks', license='MIT License', author='Vilibald Wanča', author_email='[email protected]', maintainer='Apiary', maintainer_email='[email protected]', description='Python Hooks Bridge for Dredd API Testing Framework', long_description=long_desc, zip_safe=True, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Build Tools', ], keywords='HTTP API testing Dredd', platforms='any', packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'dredd-hooks-python = dredd_hooks.__main__:main' ], }, tests_require=['flake8'], test_suite='test', )
# -*- coding: utf-8 -*- from setuptools import find_packages, setup long_desc = open('README.rst').read() setup( name='dredd-hooks-python', version='0.1.3', url='https://github.com/apiaryio/dredd-hooks-python/', download_url='http://pypi.python.org/pypi/dredd_hooks', license='MIT License', author='Vilibald Wanča', author_email='[email protected]', maintainer='Apiary', maintainer_email='[email protected]', description='Python Hooks Bridge for Dredd API Testing Framework', long_description=long_desc, zip_safe=True, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Build Tools', ], keywords='HTTP API testing Dredd', platforms='any', packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'dredd-hooks-python = dredd_hooks.__main__:main' ], }, tests_require=['flake8'], test_suite='test', )
Add comments for tests of caching.
import unittest import mock import chainer from chainer.functions.pooling import pooling_nd_kernel from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'ndim': [2, 3, 4], })) @attr.gpu class TestPoolingNDKernelMemo(unittest.TestCase): def setUp(self): chainer.cuda.clear_memo() def test_pooling_nd_kernel_forward_memo(self): ndim = self.ndim with mock.patch('chainer.functions.pooling.pooling_nd_kernel.' 'PoolingNDKernelForward._generate') as m: pooling_nd_kernel.PoolingNDKernelForward.generate(ndim) m.assert_called_once_with(ndim) pooling_nd_kernel.PoolingNDKernelForward.generate(ndim) # Check that the mocked _generate() function is called just once # because the result of generate() function is cached. m.assert_called_once_with(ndim) def test_pooling_nd_kernel_backward_memo(self): ndim = self.ndim with mock.patch('chainer.functions.pooling.pooling_nd_kernel.' 'PoolingNDKernelBackward._generate') as m: pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim) m.assert_called_once_with(ndim) pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim) # Check that the mocked _generate() function is called just once # because the result of generate() function is cached. m.assert_called_once_with(ndim) testing.run_module(__name__, __file__)
import unittest import mock import chainer from chainer.functions.pooling import pooling_nd_kernel from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'ndim': [2, 3, 4], })) @attr.gpu class TestPoolingNDKernelMemo(unittest.TestCase): def setUp(self): chainer.cuda.clear_memo() def test_pooling_nd_kernel_forward_memo(self): ndim = self.ndim with mock.patch('chainer.functions.pooling.pooling_nd_kernel.' 'PoolingNDKernelForward._generate') as m: pooling_nd_kernel.PoolingNDKernelForward.generate(ndim) m.assert_called_once_with(ndim) pooling_nd_kernel.PoolingNDKernelForward.generate(ndim) m.assert_called_once_with(ndim) def test_pooling_nd_kernel_backward_memo(self): ndim = self.ndim with mock.patch('chainer.functions.pooling.pooling_nd_kernel.' 'PoolingNDKernelBackward._generate') as m: pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim) m.assert_called_once_with(ndim) pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim) m.assert_called_once_with(ndim) testing.run_module(__name__, __file__)
Fix support for multiple tests in the same directory
import test from "ava"; import {runKaba} from "./lib/runner"; /** * @typedef {{ * status: number, * dir?: string, * args?: string[], * match?: RegExp, * noMatch?: RegExp, * }} FixtureConfig */ /* eslint-disable camelcase */ /** @var {Object<string,FixtureConfig>} fixtureTests */ let fixtureTests = { js: { status: 0, }, scss_fail_on_error: { status: 1, noMatch: /Found \d+ Stylelint issues:/, }, scss_fail_on_error_lint: { status: 1, dir: "scss_fail_on_error", args: ["--lint"], match: /Found \d+ Stylelint issues:/, }, scss: { status: 0, }, ts: { status: 0, }, }; /* eslint-enable camelcase */ Object.keys(fixtureTests).forEach(key => { test(`File: ${key}`, t => { let expected = fixtureTests[key]; let result = runKaba(expected.dir || key, expected.args || []); let stdout = null !== result.stdout ? result.stdout.toString() : ""; t.is(result.status, expected.status); if (undefined !== expected.match) { t.truthy(expected.match.test(stdout)); } if (undefined !== expected.noMatch) { t.falsy(expected.noMatch.test(stdout)); } }); });
import test from "ava"; import {runKaba} from "./lib/runner"; /** * @typedef {{ * status: number, * args?: string[], * match?: RegExp, * noMatch?: RegExp, * }} FixtureConfig */ /* eslint-disable camelcase */ /** @var {Object<string,FixtureConfig>} fixtureTests */ let fixtureTests = { js: { status: 0, }, scss_fail_on_error: { status: 1, noMatch: /Found \d+ Stylelint issues:/, }, scss_fail_on_error_lint: { status: 1, args: ["--lint"], match: /Found \d+ Stylelint issues:/, }, scss: { status: 0, }, ts: { status: 0, }, }; /* eslint-enable camelcase */ Object.keys(fixtureTests).forEach(key => { test(`File: ${key}`, t => { let expected = fixtureTests[key]; let result = runKaba(key, expected.args || []); let stdout = null !== result.stdout ? result.stdout.toString() : ""; t.is(result.status, expected.status); if (undefined !== expected.match) { t.truthy(expected.match.test(stdout)); } if (undefined !== expected.noMatch) { t.falsy(expected.noMatch.test(stdout)); } }); });
Set jshint configuration option 'latedef' to false
module.exports = function (grunt) { "use strict"; // load all grunt tasks require('load-grunt-tasks')(grunt); // Default task. grunt.registerTask('default', ['jshint', 'karma']); // uglify grunt.registerTask('minify', ['uglify']); var testConfig = function(configFile, customOptions) { var options = { configFile: configFile, keepalive: true }; var travisOptions = process.env.TRAVIS && { browsers: ['Firefox'], reporters: 'dots' }; return grunt.util._.extend(options, customOptions, travisOptions); }; // Project configuration. grunt.initConfig({ karma: { unit: { options: testConfig('test/test.conf.js') } }, jshint:{ files: ['src/**/*.js', 'test/**/*.js', 'demo/**/*.js'], options: { curly: true, eqeqeq: true, immed: true, latedef: false, newcap: true, noarg: true, sub: true, boss: true, eqnull: true, globals: {} } }, uglify: { build: { src: ['src/**/*.js'], dest: 'calendar.min.js' } } }); };
module.exports = function (grunt) { "use strict"; // load all grunt tasks require('load-grunt-tasks')(grunt); // Default task. grunt.registerTask('default', ['jshint', 'karma']); // uglify grunt.registerTask('minify', ['uglify']); var testConfig = function(configFile, customOptions) { var options = { configFile: configFile, keepalive: true }; var travisOptions = process.env.TRAVIS && { browsers: ['Firefox'], reporters: 'dots' }; return grunt.util._.extend(options, customOptions, travisOptions); }; // Project configuration. grunt.initConfig({ karma: { unit: { options: testConfig('test/test.conf.js') } }, jshint:{ files:['src/**/*.js', 'test/**/*.js', 'demo/**/*.js'], options:{ curly:true, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, sub:true, boss:true, eqnull:true, globals:{} } }, uglify: { build: { src: ['src/**/*.js'], dest: 'calendar.min.js' } } }); };
Revert "BUG: fms_v5 | ep importer -> the titles are compared using the same htmlspecialchars encoding" This reverts commit 7d55ab33101d4ce18e99c14034d6f758f519b315.
<?php /*"****************************************************************************************************** * (c) 2004-2006 by MulchProductions, www.mulchprod.de * * (c) 2007-2014 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * *-------------------------------------------------------------------------------------------------------* * $Id$ * ********************************************************************************************************/ echo "+-------------------------------------------------------------------------------+\n"; echo "| Kajona Debug Subsystem |\n"; echo "| |\n"; echo "| PHPINFO |\n"; echo "| |\n"; echo "+-------------------------------------------------------------------------------+\n"; phpinfo(); echo "\n\n"; echo "+-------------------------------------------------------------------------------+\n"; echo "| (c) www.kajona.de |\n"; echo "+-------------------------------------------------------------------------------+\n";
<?php /*"****************************************************************************************************** * (c) 2004-2006 by MulchProductions, www.mulchprod.de * * (c) 2007-2014 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * *-------------------------------------------------------------------------------------------------------* * $Id$ * ********************************************************************************************************/ echo "+-------------------------------------------------------------------------------+\n"; echo "| Kajona Debug Subsystem |\n"; echo "| |\n"; echo "| PHPINFO |\n"; echo "| |\n"; echo "+-------------------------------------------------------------------------------+\n"; require_once __DIR__.'/../../../core_agp/module_phpexcel/system/phpexcel/PHPExcel.php'; echo PHPExcel_Shared_File::sys_get_temp_dir(); echo "\n\n"; echo "+-------------------------------------------------------------------------------+\n"; echo "| (c) www.kajona.de |\n"; echo "+-------------------------------------------------------------------------------+\n";
Fix naming issues in dictionary test
<?php namespace Shadowhand\Test\Destrukt; use Shadowhand\Destrukt\Dictionary; class DictionaryTest extends StructTest { public function setUp() { $this->struct = new Dictionary([ 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, ]); } public function testReplace() { $dict = $this->struct; $copy = $dict->withData([ 'one' => 'uno', 'two' => 'dos', 'three' => 'tres', 'four' => 'quatro', ]); $this->assertEquals(1, $dict->getValue('one')); $this->assertEquals('uno', $copy->getValue('one')); } /** * @expectedException \InvalidArgumentException */ public function testReplaceFailure() { $this->struct->withData([3, 2, 1]); } public function testAppend() { $dict = $this->struct; $copy = $dict->withValue('five', 5); $this->assertEquals(4, count($dict)); $this->assertEquals(5, count($copy)); $this->assertEquals(null, $dict->getValue('five')); $this->assertEquals(5, $copy->getValue('five')); $this->assertEquals(null, $copy->getValue('six')); } /** * @expectedException \InvalidArgumentException */ public function testAppendKeyFailure() { $this->struct->withValue(6, 'six'); } }
<?php namespace Shadowhand\Test\Destrukt; use Shadowhand\Destrukt\Dictionary; class HashTest extends StructTest { public function setUp() { $this->struct = new Dictionary([ 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, ]); } public function testReplace() { $hash = $this->struct; $copy = $hash->withData([ 'one' => 'uno', 'two' => 'dos', 'three' => 'tres', 'four' => 'quatro', ]); $this->assertEquals(1, $hash->getValue('one')); $this->assertEquals('uno', $copy->getValue('one')); } public function testAppend() { $hash = $this->struct; $copy = $hash->withValue('five', 5); $this->assertEquals(4, count($hash)); $this->assertEquals(5, count($copy)); $this->assertEquals(null, $hash->getValue('five')); $this->assertEquals(5, $copy->getValue('five')); $this->assertEquals(null, $copy->getValue('six')); } /** * @expectedException \InvalidArgumentException */ public function testAppendKeyFailure() { $this->struct->withValue(6, 'six'); } /** * @expectedException \InvalidArgumentException */ public function testValidateFailure() { $this->struct->validate([3, 2, 1]); } }
Change function-based generic view to class-based. As per their deprecation policy, Django 1.5 removed function-based generic views.
# encoding: utf-8 """ URL conf for django-sphinxdoc. """ from django.conf.urls.defaults import patterns, url from django.views.generic.list import ListView from sphinxdoc import models from sphinxdoc.views import ProjectSearchView urlpatterns = patterns('sphinxdoc.views', url( r'^$', ListView.as_view(queryset=models.Project.objects.all().order_by('name')) ), url( r'^(?P<slug>[\w-]+)/search/$', ProjectSearchView(), name='doc-search', ), # These URLs have to be without the / at the end so that relative links in # static HTML files work correctly and that browsers know how to name files # for download url( r'^(?P<slug>[\w-]+)/(?P<type_>_images|_static|_downloads|_source)/' + \ r'(?P<path>.+)$', 'sphinx_serve', ), url( r'^(?P<slug>[\w-]+)/_objects/$', 'objects_inventory', name='objects-inv', ), url( r'^(?P<slug>[\w-]+)/$', 'documentation', {'path': ''}, name='doc-index', ), url( r'^(?P<slug>[\w-]+)/(?P<path>.+)/$', 'documentation', name='doc-detail', ), )
# encoding: utf-8 """ URL conf for django-sphinxdoc. """ from django.conf.urls.defaults import patterns, url from django.views.generic import list_detail from sphinxdoc import models from sphinxdoc.views import ProjectSearchView project_info = { 'queryset': models.Project.objects.all().order_by('name'), 'template_object_name': 'project', } urlpatterns = patterns('sphinxdoc.views', url( r'^$', list_detail.object_list, project_info, ), url( r'^(?P<slug>[\w-]+)/search/$', ProjectSearchView(), name='doc-search', ), # These URLs have to be without the / at the end so that relative links in # static HTML files work correctly and that browsers know how to name files # for download url( r'^(?P<slug>[\w-]+)/(?P<type_>_images|_static|_downloads|_source)/' + \ r'(?P<path>.+)$', 'sphinx_serve', ), url( r'^(?P<slug>[\w-]+)/_objects/$', 'objects_inventory', name='objects-inv', ), url( r'^(?P<slug>[\w-]+)/$', 'documentation', {'path': ''}, name='doc-index', ), url( r'^(?P<slug>[\w-]+)/(?P<path>.+)/$', 'documentation', name='doc-detail', ), )
Fix for new builder of laravel
<?php namespace Nbj\Cockroach\Builder; use Illuminate\Database\Schema\Builder; class CockroachBuilder extends Builder { /** * Determine if the given table exists. * * @param string $table * @return bool */ public function hasTable($table) { if (is_array($schema = $this->connection->getConfig('schema'))) { $schema = head($schema); } $schema = $schema ? $schema : 'public'; $table = $this->connection->getTablePrefix().$table; return count($this->connection->select( $this->grammar->compileTableExists(), [$schema, $table] )) > 0; } /** * Drop all tables from the database. * * @return void */ public function dropAllTables() { $tables = []; foreach ($this->getAllTables() as $row) { $row = (array) $row; $tables[] = reset($row); } if (empty($tables)) { return; } $this->connection->statement( $this->grammar->compileDropAllTables($tables) ); } /** * Get all of the table names for the database. * * @return array */ public function getAllTables() { return $this->connection->select( $this->grammar->compileGetAllTables($this->connection->getConfig('schema')) ); } }
<?php namespace Nbj\Cockroach\Builder; use Illuminate\Database\Schema\Builder; class CockroachBuilder extends Builder { /** * Determine if the given table exists. * * @param string $table * @return bool */ public function hasTable($table) { if (is_array($schema = $this->connection->getConfig('schema'))) { $schema = head($schema); } $schema = $schema ? $schema : 'public'; $table = $this->connection->getTablePrefix().$table; return count($this->connection->select( $this->grammar->compileTableExists(), [$schema, $table] )) > 0; } /** * Drop all tables from the database. * * @return void */ public function dropAllTables() { $tables = []; foreach ($this->getAllTables() as $row) { $row = (array) $row; $tables[] = reset($row); } if (empty($tables)) { return; } $this->connection->statement( $this->grammar->compileDropAllTables($tables) ); } /** * Get all of the table names for the database. * * @return array */ protected function getAllTables() { return $this->connection->select( $this->grammar->compileGetAllTables($this->connection->getConfig('schema')) ); } }
Tag {{tmpl}} should not change nesting value
<?php class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag { public function getTokenType() { return 'Tmpl'; } public function getRegex() { return '/{{tmpl.*?}}/is'; } public function getNestingValue() { return array(0,0); } public function parseTag($rawTagString) { $matches = array(); preg_match('/^{{tmpl(\((.*?),(.*)\)(.*)|\((.*?)\)(.*)|(.*))}}$/is', $rawTagString, $matches); if (count($matches) == 8) { return array ( 'template' => $this->_extractId($matches[1]) ); } if (count($matches) == 7) { return array ( 'template' => $this->_extractId($matches[6]), 'data' => trim($matches[5]), ); } // Matched optional params as well return array ( 'template' => $this->_extractId($matches[4]), 'data' => trim($matches[2]), 'options' => trim($matches[3]) ); } private function _extractId($str) { return trim($str, "'\"# \t\n\r\0\x0B"); } }
<?php class jQueryTmpl_Tag_Tmpl implements jQueryTmpl_Tag { public function getTokenType() { return 'Tmpl'; } public function getRegex() { return '/{{tmpl.*?}}/is'; } public function getNestingValue() { return array(0,1); } public function parseTag($rawTagString) { $matches = array(); preg_match('/^{{tmpl(\((.*?),(.*)\)(.*)|\((.*?)\)(.*)|(.*))}}$/is', $rawTagString, $matches); if (count($matches) == 8) { return array ( 'template' => $this->_extractId($matches[1]) ); } if (count($matches) == 7) { return array ( 'template' => $this->_extractId($matches[6]), 'data' => trim($matches[5]), ); } // Matched optional params as well return array ( 'template' => $this->_extractId($matches[4]), 'data' => trim($matches[2]), 'options' => trim($matches[3]) ); } private function _extractId($str) { return trim($str, "'\"# \t\n\r\0\x0B"); } }
Use new PROJECTIONCHANGE event properties
TC.control = TC.control || {}; if (!TC.Control) { TC.syncLoadJS(TC.apiLocation + 'TC/Control'); } TC.control.NavBarHome = function () { TC.Control.apply(this, arguments); }; TC.inherit(TC.control.NavBarHome, TC.Control); (function () { var ctlProto = TC.control.NavBarHome.prototype; ctlProto.CLASS = 'tc-ctl-nav-home'; ctlProto.render = function () { var self = this; if (!self.wrap) { self.wrap = new TC.wrap.control.NavBarHome(self); } return Promise.resolve(); }; ctlProto.register = function (map) { const self = this; const result = TC.Control.prototype.register.call(self, map); self.wrap.register(map); map.on(TC.Consts.event.PROJECTIONCHANGE, function (e) { const crs = e.newCrs; var bottomLeft = TC.Util.reproject([map.options.initialExtent[0], map.options.initialExtent[1]], map.options.crs, crs); var topRight = TC.Util.reproject([map.options.initialExtent[2], map.options.initialExtent[3]], map.options.crs, crs); self.wrap.setInitialExtent([bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]]); }); return result; }; })();
TC.control = TC.control || {}; if (!TC.Control) { TC.syncLoadJS(TC.apiLocation + 'TC/Control'); } TC.control.NavBarHome = function () { TC.Control.apply(this, arguments); }; TC.inherit(TC.control.NavBarHome, TC.Control); (function () { var ctlProto = TC.control.NavBarHome.prototype; ctlProto.CLASS = 'tc-ctl-nav-home'; ctlProto.render = function () { var self = this; if (!self.wrap) { self.wrap = new TC.wrap.control.NavBarHome(self); } return Promise.resolve(); }; ctlProto.register = function (map) { const self = this; const result = TC.Control.prototype.register.call(self, map); self.wrap.register(map); map.on(TC.Consts.event.PROJECTIONCHANGE, function (e) { const crs = e.crs; var bottomLeft = TC.Util.reproject([map.options.initialExtent[0], map.options.initialExtent[1]], map.options.crs, crs); var topRight = TC.Util.reproject([map.options.initialExtent[2], map.options.initialExtent[3]], map.options.crs, crs); self.wrap.setInitialExtent([bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]]); }); return result; }; })();
Fix relative import to be absolute
import d3 from 'd3'; import fcRebind from 'd3fc-rebind'; import {getStockFluxData} from 'stockflux-core/src/services/StockFluxService'; export default function() { var historicFeed = getStockFluxData(), granularity, candles; var allowedPeriods = d3.map(); allowedPeriods.set(60 * 60 * 24, 'daily'); allowedPeriods.set(60 * 60 * 24 * 7, 'weekly'); var stockFluxAdaptor = function stockFluxAdaptor(cb) { var startDate = new Date(); historicFeed.start(startDate); historicFeed(cb); }; stockFluxAdaptor.candles = function(x) { if (!arguments.length) { return candles; } candles = x; return stockFluxAdaptor; }; stockFluxAdaptor.granularity = function(x) { if (!arguments.length) { return granularity; } if (!allowedPeriods.has(x)) { throw new Error('Granularity of ' + x + ' is not supported.'); } granularity = x; return stockFluxAdaptor; }; stockFluxAdaptor.apiKey = function() { throw new Error('Not implemented.'); }; stockFluxAdaptor.database = function() { throw new Error('Not implemented.'); }; stockFluxAdaptor.columnNameMap = function() { throw new Error('Not implemented.'); }; fcRebind.rebindAll(stockFluxAdaptor, historicFeed); return stockFluxAdaptor; }
import d3 from 'd3'; import fcRebind from 'd3fc-rebind'; import {getStockFluxData} from '../../../../../../node_modules/stockflux-core/src/services/StockFluxService'; export default function() { var historicFeed = getStockFluxData(), granularity, candles; var allowedPeriods = d3.map(); allowedPeriods.set(60 * 60 * 24, 'daily'); allowedPeriods.set(60 * 60 * 24 * 7, 'weekly'); var stockFluxAdaptor = function stockFluxAdaptor(cb) { var startDate = new Date(); historicFeed.start(startDate); historicFeed(cb); }; stockFluxAdaptor.candles = function(x) { if (!arguments.length) { return candles; } candles = x; return stockFluxAdaptor; }; stockFluxAdaptor.granularity = function(x) { if (!arguments.length) { return granularity; } if (!allowedPeriods.has(x)) { throw new Error('Granularity of ' + x + ' is not supported.'); } granularity = x; return stockFluxAdaptor; }; stockFluxAdaptor.apiKey = function() { throw new Error('Not implemented.'); }; stockFluxAdaptor.database = function() { throw new Error('Not implemented.'); }; stockFluxAdaptor.columnNameMap = function() { throw new Error('Not implemented.'); }; fcRebind.rebindAll(stockFluxAdaptor, historicFeed); return stockFluxAdaptor; }
Use inline-block instead of float for iframes to prevent text from wrapping around them.
<?php class IncludeSteepGadgets { static function HookParser($parser) { $parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender"); $parser->setHook("data-map", "IncludeSteepGadgets::MapRender"); return true; } static function ProcessModelRender($input, $args, $parser, $frame) { return IncludeSteepGadgets::Render($args, "/process-model", "process-model"); } static function MapRender($input, $args, $parser, $frame) { return IncludeSteepGadgets::Render($args, "/energy-efficiency-planner", "data-map"); } static function Render($args, $location, $tag) { if (isset($args['name'])) { if (isset($args['width'])) { $width = $args['width']; } else { $width = "100%"; } if (isset($args['height'])) { $height = $args['height']; } else { $height = "600px"; } $iframeAttrs = array( "src" => $location . "/?name=" . $args['name'], "style" => "width:" . $width . "; height:" . $height . "; display:inline-block;" ); // This automatically escapes attribute values for us. return Html::rawElement( "iframe", $iframeAttrs ); } else { return "Attempt to include " . $tag . " without setting name attribute."; } } } ?>
<?php class IncludeSteepGadgets { static function HookParser($parser) { $parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender"); $parser->setHook("data-map", "IncludeSteepGadgets::MapRender"); return true; } static function ProcessModelRender($input, $args, $parser, $frame) { return IncludeSteepGadgets::Render($args, "/process-model", "process-model"); } static function MapRender($input, $args, $parser, $frame) { return IncludeSteepGadgets::Render($args, "/energy-efficiency-planner", "data-map"); } static function Render($args, $location, $tag) { if (isset($args['name'])) { if (isset($args['width'])) { $width = $args['width']; } else { $width = "100%"; } if (isset($args['height'])) { $height = $args['height']; } else { $height = "600px"; } $iframeAttrs = array( "src" => $location . "/?name=" . $args['name'], "style" => "width:" . $width . "; height:" . $height . "; float:left;" ); // This automatically escapes attribute values for us. return Html::rawElement( "iframe", $iframeAttrs ); } else { return "Attempt to include " . $tag . " without setting name attribute."; } } } ?>
Append 站 to train station name
package cn.sunner.sms2calendar; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Sunner on 6/29/16. */ public class N12306Parser extends SMSParser { public N12306Parser(String text) { super(text); } @Override protected boolean parse() { String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(text); if (!m.matches()) { return false; } title = m.group(3); location = m.group(4) + "站"; // Append 站 to make it more accurate for maps beginTime = new GregorianCalendar( Calendar.getInstance().get(Calendar.YEAR), // Use this year Integer.parseInt(m.group(1)), // Month Integer.parseInt(m.group(2)), // Day Integer.parseInt(m.group(5)), // Hour Integer.parseInt(m.group(6)) // Minute ); // set end time to 1 hour later endTime = (Calendar) beginTime.clone(); endTime.add(Calendar.HOUR, 1); return true; } }
package cn.sunner.sms2calendar; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Sunner on 6/29/16. */ public class N12306Parser extends SMSParser { public N12306Parser(String text) { super(text); } @Override protected boolean parse() { String pattern = ".*[购|签](\\d+)月(\\d+)日(.+[号|铺])([^\\d]+)(\\d+):(\\d+)开。.*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(text); if (!m.matches()) { return false; } this.title = m.group(3); this.location = m.group(4); this.beginTime = new GregorianCalendar( Calendar.getInstance().get(Calendar.YEAR), // Use this year Integer.parseInt(m.group(1)), // Month Integer.parseInt(m.group(2)), // Day Integer.parseInt(m.group(5)), // Hour Integer.parseInt(m.group(6)) // Minute ); // set end time to 1 hour later endTime = (Calendar) beginTime.clone(); endTime.add(Calendar.HOUR, 1); return true; } }
Use get_prep_value instead of the database related one. Closes gh-42
from django.core.exceptions import ValidationError from django.db import models from django.utils import simplejson class JSONField(models.TextField): """Simple JSON field that stores python structures as JSON strings on database. """ __metaclass__ = models.SubfieldBase def to_python(self, value): """ Convert the input JSON value into python structures, raises django.core.exceptions.ValidationError if the data can't be converted. """ if self.blank and not value: return None if isinstance(value, basestring): try: return simplejson.loads(value) except Exception, e: raise ValidationError(str(e)) else: return value def validate(self, value, model_instance): """Check value is a valid JSON string, raise ValidationError on error.""" super(JSONField, self).validate(value, model_instance) try: return simplejson.loads(value) except Exception, e: raise ValidationError(str(e)) def get_prep_value(self, value): """Convert value to JSON string before save""" try: return simplejson.dumps(value) except Exception, e: raise ValidationError(str(e))
from django.core.exceptions import ValidationError from django.db import models from django.utils import simplejson class JSONField(models.TextField): """Simple JSON field that stores python structures as JSON strings on database. """ __metaclass__ = models.SubfieldBase def to_python(self, value): """ Convert the input JSON value into python structures, raises django.core.exceptions.ValidationError if the data can't be converted. """ if self.blank and not value: return None if isinstance(value, basestring): try: return simplejson.loads(value) except Exception, e: raise ValidationError(str(e)) else: return value def validate(self, value, model_instance): """Check value is a valid JSON string, raise ValidationError on error.""" super(JSONField, self).validate(value, model_instance) try: return simplejson.loads(value) except Exception, e: raise ValidationError(str(e)) def get_db_prep_value(self, value, connection, prepared=False): """Convert value to JSON string before save""" try: return simplejson.dumps(value) except Exception, e: raise ValidationError(str(e))
Revert "Updating md5 for fixed file" because this was fixed properly in unstable (but will break SnpEff if put into Stable). This reverts commit 6b4182c6ab3e214da4c73bc6f3687ac6d1c0b72c.
package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("6645babc8c7d46be0da223477c7b1291")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } }
package org.broadinstitute.sting.gatk.walkers.CNV; import org.broadinstitute.sting.WalkerTest; import org.testng.annotations.Test; import java.util.Arrays; public class SymbolicAllelesIntegrationTest extends WalkerTest { public static String baseTestString(String reference, String VCF) { return "-T CombineVariants" + " -R " + reference + " --variant:vcf " + validationDataLocation + VCF + " -filteredRecordsMergeType KEEP_IF_ANY_UNFILTERED" + " -genotypeMergeOptions REQUIRE_UNIQUE" + " -setKey null" + " -o %s" + " -NO_HEADER"; } @Test public void test1() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_1.vcf"), 1, Arrays.asList("89a1c56f264ac27a2a4be81072473b6f")); executeTest("Test symbolic alleles", spec); } @Test public void test2() { WalkerTestSpec spec = new WalkerTestSpec( baseTestString(b36KGReference, "symbolic_alleles_2.vcf"), 1, Arrays.asList("3008d6f5044bc14801e5c58d985dec72")); executeTest("Test symbolic alleles mixed in with non-symbolic alleles", spec); } }
Introduce set_of (similar to list_of validator)
# Licenced under the txaws licence available at /LICENSE in the txaws source. """ attrs validators for internal use. """ import attr from attr import validators def list_of(validator): """ Require a value which is a list containing elements which the given validator accepts. """ return _ContainerOf(list, validator) def set_of(validator): """ Require a value which is a set containing elements which the given validator accepts. """ return _ContainerOf(set, validator) @attr.s(frozen=True) class _ContainerOf(object): """ attrs validator for a container of objects which satisfy another validator. L{list_of}, L{set_of}, etc are the public constructors to hide the type and prevent subclassing. """ container_type = attr.ib() validator = attr.ib() def __call__(self, inst, a, value): validators.instance_of(self.container_type)(inst, a, value) for n, element in enumerate(sorted(value)): inner_identifier = u"sorted({})[{}]".format(a.name, n) # Create an Attribute with a name that refers to the # validator we're using and the index we're validating. # Otherwise the validation failure is pretty confusing. inner_attr = attr.Attribute( name=inner_identifier, default=None, validator=self.validator, repr=False, cmp=False, hash=False, init=False, ) self.validator(inst, inner_attr, element)
# Licenced under the txaws licence available at /LICENSE in the txaws source. """ attrs validators for internal use. """ import attr from attr import validators def list_of(validator): """ Require a value which is a list containing elements which the given validator accepts. """ return _ListOf(validator) @attr.s(frozen=True) class _ListOf(object): """ attrs validator for a list of elements which satisfy another validator. L{list_of} is the public constructor to hide the type and prevent subclassing. """ validator = attr.ib() def __call__(self, inst, a, value): validators.instance_of(list)(inst, a, value) for n, element in enumerate(value): inner_identifier = u"{}[{}]".format(a.name, n) # Create an Attribute with a name that refers to the # validator we're using and the index we're validating. # Otherwise the validation failure is pretty confusing. inner_attr = attr.Attribute( name=inner_identifier, default=None, validator=self.validator, repr=False, cmp=False, hash=False, init=False, ) self.validator(inst, inner_attr, element)
Add type check when exchanging an array
<?php namespace RDM\Generics; class TypedArrayObject extends \ArrayObject { private $type; /** * {@inheritDoc} * * @param string $type The type of elements the array can contain. * Can be any of the primitive types or a class name. */ public function __construct($type, $array = array()) { $this->type = $type; } private function isValid($value) { switch ($this->type) { case 'bool': return is_bool($value); case 'int': return is_int($value); case 'float': return is_float($value); case 'string': return is_string($value); case 'array': return is_array($value); case 'resource': return is_resource($value); case 'callable': return is_callable($value); default: return is_a($value, $this->type); } } /** * {@inheritDoc} * * @throws \InvalidArgumentException If the given value was not of the specified type */ public function offsetSet($offset, $value) { if ($this->isValid($value)) { parent::offsetSet($offset, $value); } else { throw new \InvalidArgumentException('The given value was not of type ' . $this->type); } } /** * {@inheritDoc} */ public function exchangeArray($input) { foreach ($input as $item) { if (!$this->isValid($value)) { throw new \InvalidArgumentException('The given value was not of type ' . $this->type); } } parent::exchangeArray($input); } }
<?php namespace RDM\Generics; class TypedArrayObject extends \ArrayObject { private $type; /** * {@inheritDoc} * * @param string $type The type of elements the array can contain. * Can be any of the primitive types or a class name. */ public function __construct($type, $array = array()) { $this->type = $type; } private function isValid($value) { switch ($this->type) { case 'bool': return is_bool($value); case 'int': return is_int($value); case 'float': return is_float($value); case 'string': return is_string($value); case 'array': return is_array($value); case 'resource': return is_resource($value); case 'callable': return is_callable($value); default: return is_a($value, $this->type); } } /** * {@inheritDoc} * * @throws \InvalidArgumentException If the given value was not of the specified type */ public function offsetSet($offset, $value) { if ($this->isValid($value)) { parent::offsetSet($offset, $value); } else { throw new \InvalidArgumentException('The given value was not of type ' . $this->type); } } }
Test (absolute basics): Change margins to absolute coordinates
/** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-30px' }); const targetTwo = createTarget({ top: '30px' }); const targetThree = createTarget({ top: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetTwo); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); });
/** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ marginLeft: '-30px' }); const targetTwo = createTarget({ marginTop: '30px' }); const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetTwo); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); });
Change String array constructor to varargs
package me.rbrickis.mojo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Arguments { private List<String> arguments; public Arguments() { this.arguments = new ArrayList<>(); } public Arguments(String... arguments) { this.arguments = Arrays.asList(arguments); } public Arguments(List<String> arguments) { this.arguments = arguments; } /** * @see Arguments#size() */ public int length() { return size(); } /** * @return The size of the arguments provide */ public int size() { return arguments.size(); } /** * @param index the index to pull from * @return 'null' if the index is out of bounds, or the String at the index. */ public String get(int index) { try { return arguments.get(index); } catch (IndexOutOfBoundsException ex) { return null; } } public String join(int at, char delimiter) { StringBuilder builder = new StringBuilder(); for (int x = at; x < arguments.size(); x++) { builder.append(get(x)).append(delimiter); } return builder.toString(); } public String join(int at) { return join(at, ' '); } public List<String> getArguments() { return arguments; } }
package me.rbrickis.mojo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Arguments { private List<String> arguments; public Arguments() { this.arguments = new ArrayList<>(); } public Arguments(String[] arguments) { this.arguments = Arrays.asList(arguments); } public Arguments(List<String> arguments) { this.arguments = arguments; } /** * @see Arguments#size() */ public int length() { return size(); } /** * @return The size of the arguments provide */ public int size() { return arguments.size(); } /** * @param index the index to pull from * @return 'null' if the index is out of bounds, or the String at the index. */ public String get(int index) { try { return arguments.get(index); } catch (IndexOutOfBoundsException ex) { return null; } } public String join(int at, char delimiter) { StringBuilder builder = new StringBuilder(); for (int x = at; x < arguments.size(); x++) { builder.append(get(x)).append(delimiter); } return builder.toString(); } public String join(int at) { return join(at, ' '); } public List<String> getArguments() { return arguments; } }
Print "Gesamtproduktgüte" on any key press.
package rogue.creature; import java.util.Collection; import jade.fov.RayCaster; import jade.fov.ViewField; import jade.ui.Camera; import jade.ui.Terminal; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; public class Player extends Creature implements Camera { private Terminal term; private ViewField fov; public Player(Terminal term) { super(ColoredChar.create('@')); this.term = term; fov = new RayCaster(); } @Override public void act() { try { char key; key = term.getKey(); System.out.println("Gesamtproduktgüte"); switch(key) { case 'q': expire(); break; default: Direction dir = Direction.keyToDir(key); if(dir != null) move(dir); break; } } catch(InterruptedException e) { e.printStackTrace(); } } @Override public Collection<Coordinate> getViewField() { return fov.getViewField(world(), pos(), 5); } }
package rogue.creature; import java.util.Collection; import jade.fov.RayCaster; import jade.fov.ViewField; import jade.ui.Camera; import jade.ui.Terminal; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; public class Player extends Creature implements Camera { private Terminal term; private ViewField fov; public Player(Terminal term) { super(ColoredChar.create('@')); this.term = term; fov = new RayCaster(); } @Override public void act() { try { char key; key = term.getKey(); switch(key) { case 'q': expire(); break; default: Direction dir = Direction.keyToDir(key); if(dir != null) move(dir); break; } } catch(InterruptedException e) { e.printStackTrace(); } } @Override public Collection<Coordinate> getViewField() { return fov.getViewField(world(), pos(), 5); } }
Remove synchronization, it leads to deadlocks Example: Thread A gets the lock in acquire(), does not hold the monitor anymore.. Thread B calls acquire() and waits for the lock (while holding the monitor) Thead A wants to call release(), but cannot do that because thread B is holding the monitor. Deadlock until timeout for thread A, at which time thread B holds the monitor again and continues
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.tenant; import com.yahoo.path.Path; import com.yahoo.vespa.config.server.TimeoutBudget; import com.yahoo.vespa.curator.Curator; import com.yahoo.vespa.curator.recipes.CuratorLock; import java.util.concurrent.TimeUnit; /** * A lock to protect session activation. * * @author lulf * @since 5.1 */ public class ActivateLock { private static final String ACTIVATE_LOCK_NAME = "activateLock"; private final CuratorLock curatorLock; public ActivateLock(Curator curator, Path rootPath) { this.curatorLock = new CuratorLock(curator, rootPath.append(ACTIVATE_LOCK_NAME).getAbsolute()); } public boolean acquire(TimeoutBudget timeoutBudget, boolean ignoreLockError) { try { return curatorLock.tryLock(timeoutBudget.timeLeft().toMillis(), TimeUnit.MILLISECONDS); } catch (Exception e) { if (!ignoreLockError) { throw new RuntimeException(e); } return false; } } public void release() { if (curatorLock.hasLock()) { curatorLock.unlock(); } } @Override public String toString() { return "ActivateLock (" + curatorLock + "), has lock: " + curatorLock.hasLock(); } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.tenant; import com.yahoo.path.Path; import com.yahoo.vespa.config.server.TimeoutBudget; import com.yahoo.vespa.curator.Curator; import com.yahoo.vespa.curator.recipes.CuratorLock; import java.util.concurrent.TimeUnit; /** * A lock to protect session activation. * * @author lulf * @since 5.1 */ public class ActivateLock { private static final String ACTIVATE_LOCK_NAME = "activateLock"; private final CuratorLock curatorLock; public ActivateLock(Curator curator, Path rootPath) { this.curatorLock = new CuratorLock(curator, rootPath.append(ACTIVATE_LOCK_NAME).getAbsolute()); } public synchronized boolean acquire(TimeoutBudget timeoutBudget, boolean ignoreLockError) { try { return curatorLock.tryLock(timeoutBudget.timeLeft().toMillis(), TimeUnit.MILLISECONDS); } catch (Exception e) { if (!ignoreLockError) { throw new RuntimeException(e); } return false; } } public synchronized void release() { if (curatorLock.hasLock()) { curatorLock.unlock(); } } @Override public String toString() { return "ActivateLock (" + curatorLock + "), has lock: " + curatorLock.hasLock(); } }
Use new structure for 2.0
(function() { /***********************************************************/ /* Handle Proceed to Payment /***********************************************************/ jQuery(function() { jQuery(document).on('proceedToPayment', function(event, ShoppingCart) { if (ShoppingCart.gateway != 'paypal_express') { return; } var order = { products: storejs.get('grav-shoppingcart-basket-data'), data: storejs.get('grav-shoppingcart-checkout-form-data'), shipping: storejs.get('grav-shoppingcart-shipping-method'), payment: 'paypal', token: storejs.get('grav-shoppingcart-order-token').token, amount: ShoppingCart.totalOrderPrice.toString(), gateway: ShoppingCart.gateway }; jQuery.ajax({ url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '/task:preparePayment', data: order, type: 'POST' }) .success(function(redirectUrl) { ShoppingCart.clearCart(); window.location = redirectUrl; }) .error(function() { alert('Payment not successful. Please contact us.'); }); }); }); })();
(function() { /***********************************************************/ /* Handle Proceed to Payment /***********************************************************/ jQuery(function() { jQuery(document).on('proceedToPayment', function(event, ShoppingCart) { if (ShoppingCart.gateway != 'paypal_express') { return; } var order = { products: storejs.get('grav-shoppingcart-basket-data'), data: storejs.get('grav-shoppingcart-checkout-form-data'), shipping: storejs.get('grav-shoppingcart-shipping-method'), payment: 'paypal', token: storejs.get('grav-shoppingcart-order-token').token, amount: ShoppingCart.totalOrderPrice.toString(), gateway: ShoppingCart.gateway }; jQuery.ajax({ url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '?task=preparePayment', data: order, type: 'POST' }) .success(function(redirectUrl) { ShoppingCart.clearCart(); window.location = redirectUrl; }) .error(function() { alert('Payment not successful. Please contact us.'); }); }); }); })();
Fix roam param for compatibility.
import * as zrUtil from 'zrender/src/core/util'; function dataToCoordSize(dataSize, dataItem) { dataItem = dataItem || [0, 0]; return zrUtil.map([0, 1], function (dimIdx) { var val = dataItem[dimIdx]; var halfSize = dataSize[dimIdx] / 2; var p1 = []; var p2 = []; p1[dimIdx] = val - halfSize; p2[dimIdx] = val + halfSize; p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx]; return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]); }, this); } export default function (coordSys) { var rect = coordSys.getBoundingRect(); return { coordSys: { type: 'geo', x: rect.x, y: rect.y, width: rect.width, height: rect.height }, api: { coord: function (data) { // do not provide "out" and noRoam param, // Compatible with this usage: // echarts.util.map(item.points, api.coord) return coordSys.dataToPoint(data); }, size: zrUtil.bind(dataToCoordSize, coordSys) } }; }
import * as zrUtil from 'zrender/src/core/util'; function dataToCoordSize(dataSize, dataItem) { dataItem = dataItem || [0, 0]; return zrUtil.map([0, 1], function (dimIdx) { var val = dataItem[dimIdx]; var halfSize = dataSize[dimIdx] / 2; var p1 = []; var p2 = []; p1[dimIdx] = val - halfSize; p2[dimIdx] = val + halfSize; p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx]; return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]); }, this); } export default function (coordSys) { var rect = coordSys.getBoundingRect(); return { coordSys: { type: 'geo', x: rect.x, y: rect.y, width: rect.width, height: rect.height }, api: { coord: function (data, noRoam) { // do not provide "out" param return coordSys.dataToPoint(data, noRoam); }, size: zrUtil.bind(dataToCoordSize, coordSys) } }; }
Update service worker to use cache and update strategy
var CACHE_NAME = 'static'; function _addToCache(method, resource, url) { if (method === 'addAll') { return caches.open(CACHE_NAME).then(cache => { cache[method](resource); }); } else if (method === 'put') { return caches.open(CACHE_NAME).then(cache => { cache[method](url, resource); }); } } function _getFromCache(req) { return caches.open(CACHE_NAME) .then(cache => { return caches.match(req).then(response => { if (response) { return response; } return fetch(req); }); }); } function updateCache(req) { caches.open(CACHE_NAME) .then(cache => { return fetch(req).then(response => { return cache.put(req, response.clone()); }); }) } self.addEventListener('install', function _installHandler(e) { e.waitUntil(_addToCache('addAll', [ '/css/master.css', '/js/app.js', '/views/templates.html', '/']) ); }); self.addEventListener('fetch', function _fetchHandler(e) { e.respondWith(_getFromCache(e.request.clone())); e.waitUntil(updateCache(e.request)); });
var CACHE_NAME = 'static'; function _addToCache(method, resource, url) { if (method === 'addAll') { return caches.open(CACHE_NAME).then(cache => { cache[method](resource); }); } else if (method === 'put') { return caches.open(CACHE_NAME).then(cache => { cache[method](url, resource); }); } } self.addEventListener('install', function _installHandler(e) { e.waitUntil(_addToCache('addAll', [ '/css/master.css', '/js/app.js', '/views/templates.html', '/']) ); }); self.addEventListener('fetch', function _fetchHandler(e) { e.respondWith( caches.match(e.request) .then(function (response) { if (response) { return response; } var request = e.request.clone(); return fetch(e.request).then( response => { if (!response || response.status !== 200 || response.type !== 'basic') { return response; } var responseClone = response.clone(); _addToCache(e.request, responseClone); return response; } ); }) ); });
Fix refresh button highlighted after click
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import ContainerFluid from '../ContainerFluid' import VmUserMessages from '../VmUserMessages' import UserMenu from './UserMenu' import { getAllVms } from '../../actions/vm' /** * Main application header on top of the page */ const VmsPageHeader = ({ title, onRefresh }) => { const titleStyle = { padding: '0px 0 5px' } return ( <nav className='navbar navbar-default navbar-pf navbar-fixed-top'> <ContainerFluid> <div className='navbar-header'> <a className='navbar-brand' style={titleStyle} href='/'>{title}</a> </div> <ul className='nav navbar-nav navbar-utility'> <li> <a href='#' onClick={onRefresh}> <span className='fa fa-refresh' />&nbsp;Refresh </a> </li> <UserMenu /> <VmUserMessages /> </ul> </ContainerFluid> </nav> ) } VmsPageHeader.propTypes = { title: PropTypes.string.isRequired, onRefresh: PropTypes.func.isRequired, } export default connect( (state) => ({ }), (dispatch) => ({ onRefresh: () => dispatch(getAllVms({ shallowFetch: false })), }) )(VmsPageHeader)
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import ContainerFluid from '../ContainerFluid' import VmUserMessages from '../VmUserMessages' import UserMenu from './UserMenu' import { getAllVms } from '../../actions/vm' /** * Main application header on top of the page */ const VmsPageHeader = ({ title, onRefresh }) => { const titleStyle = { padding: '0px 0 5px' } return ( <nav className='navbar navbar-default navbar-pf navbar-fixed-top'> <ContainerFluid> <div className='navbar-header'> <a className='navbar-brand' style={titleStyle} href='/'>{title}</a> </div> <ul className='nav navbar-nav navbar-utility'> <li> <a href='#' data-toggle='dropdown' onClick={onRefresh}> <span className='fa fa-refresh' />&nbsp;Refresh </a> </li> <UserMenu /> <VmUserMessages /> </ul> </ContainerFluid> </nav> ) } VmsPageHeader.propTypes = { title: PropTypes.string.isRequired, onRefresh: PropTypes.func.isRequired, } export default connect( (state) => ({ }), (dispatch) => ({ onRefresh: () => dispatch(getAllVms({ shallowFetch: false })), }) )(VmsPageHeader)
Print client-POSTed data, more verbose error handling And less fiddling with the returned header. For the time being, I don't care about correcting the bugs in that part of the code.
# Adapted from http://stackoverflow.com/questions/10017859/how-to-build-a-simple-http-post-server # Thank you! import sys import BaseHTTPServer import cgi class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) postvars = {} try: if ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) print "Client posted", postvars self.send_response(200) """ self.send_header("Content-type", "text") self.send_header("Content-length", str(len(body))) """ self.end_headers() # self.wfile.write(body) except Exception, e: print "Error", repr(e) def httpd(handler_class=MyHandler, server_address = ('127.0.0.1', 8000)): try: print "Server started" srvr = BaseHTTPServer.HTTPServer(server_address, handler_class) srvr.serve_forever() # serve_forever except KeyboardInterrupt: srvr.socket.close() if __name__ == "__main__": httpd(server_address = (sys.argv[1], int(sys.argv[2])))
# Adapted from http://stackoverflow.com/questions/10017859/how-to-build-a-simple-http-post-server # Thank you! import sys import BaseHTTPServer import cgi class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) postvars = {} try: if ctype == 'application/x-www-form-urlencoded': length = int(self.headers.getheader('content-length')) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) self.send_response(200) self.send_header("Content-type", "text") self.send_header("Content-length", str(len(body))) self.end_headers() self.wfile.write(body) except: print "Error" def httpd(handler_class=MyHandler, server_address = ('127.0.0.1', 8000)): try: print "Server started" srvr = BaseHTTPServer.HTTPServer(server_address, handler_class) srvr.serve_forever() # serve_forever except KeyboardInterrupt: srvr.socket.close() if __name__ == "__main__": httpd(server_address = (sys.argv[1], int(sys.argv[2])))
Add import error message to example
import re try: from cron_descriptor import Options, ExpressionDescriptor except ImportError: print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m') print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') raise class CrontabReader(object): """ Simple example reading /etc/contab """ rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$") def __init__(self, cronfile): """Initialize CrontabReader Args: cronfile: Path to cronfile Returns: None """ options = Options() options.day_of_week_start_index_zero = False options.use_24hour_time_format = True with open(cronfile) as f: for line in f.readlines(): parsed_line = self.parse_cron_line(line) if parsed_line: print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options))) def parse_cron_line(self, line): """Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line """ stripped = line.strip() if stripped and stripped.startswith('#') is False: rexres = self.rex.search(stripped) if rexres: return ' '.join(rexres.group(1).split()) return None CrontabReader('/etc/crontab')
from cron_descriptor import Options, ExpressionDescriptor import re class CrontabReader(object): """ Simple example reading /etc/contab """ rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$") def __init__(self, cronfile): """Initialize CrontabReader Args: cronfile: Path to cronfile Returns: None """ options = Options() options.day_of_week_start_index_zero = False options.use_24hour_time_format = True with open(cronfile) as f: for line in f.readlines(): parsed_line = self.parse_cron_line(line) if parsed_line: print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options))) def parse_cron_line(self, line): """Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line """ stripped = line.strip() if stripped and stripped.startswith('#') is False: rexres = self.rex.search(stripped) if rexres: return ' '.join(rexres.group(1).split()) return None CrontabReader('/etc/crontab')
Update to version 0.2 and some trove classifiers
#!/usr/bin/env python from distutils.core import setup, Command class TestDiscovery(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess errno = subprocess.call([ sys.executable, '-m', 'unittest', 'discover', '-p', '*.py', 'tests', ]) raise SystemExit(errno) setup(name='steel', version='0.2', description='A Python framework for describing binary file formats', author='Marty Alchin', author_email='[email protected]', url='https://github.com/gulopine/steel', packages=['steel', 'steel.bits', 'steel.chunks', 'steel.common', 'steel.fields'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: System :: Filesystems', ], cmdclass={'test': TestDiscovery}, )
#!/usr/bin/env python from distutils.core import setup, Command class TestDiscovery(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess errno = subprocess.call([ sys.executable, '-m', 'unittest', 'discover', '-p', '*.py', 'tests', ]) raise SystemExit(errno) setup(name='steel', version='0.1', description='A Python framework for describing binary file formats', author='Marty Alchin', author_email='[email protected]', url='https://github.com/gulopine/steel', packages=['steel', 'steel.bits', 'steel.chunks', 'steel.common', 'steel.fields'], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: System :: Filesystems', ], cmdclass={'test': TestDiscovery}, )
Add artificial limit of 500 records in lieu of pagination
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache) { var queryString; queryString = function (parameters) { return _.map(parameters, function (value, key) { return '(' + key + ':' + value + ')'; }) .join(' AND '); }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : '') + '&limit=500', success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { callback(err); } })); }; }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache) { var queryString; queryString = function (parameters) { return _.map(parameters, function (value, key) { return '(' + key + ':' + value + ')'; }) .join(' AND '); }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''), success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { callback(err); } })); }; }; } ); }());
Update js to set also time (not just date)
function getDatePicker() { var languageUA = { days: ['Неділя','Понеділок','Вівторок','Середа','Четвер','Пятниця','Субота'], daysShort: ['Нед','Пон','Вів','Сер','Чет','Пят','Суб'], daysMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'], months: ['Січень','Лютий','Березень','Квітень','Травень','Червень','Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'], monthsShort: ['Січ','Лют','Бер','Кві','Тра','Чер','Лип','Сер','Вер','Жов','Лис','Гру'], today: 'Сьогодні', clear: 'Очистити', dateFormat: 'yyyy-mm-dd', timeFormat: 'hh:ii', firstDay: 1, }; $('#id_valid_from').datepicker({ language: languageUA, timepicker: true, }); $('#id_valid_to').datepicker({ language: languageUA, timepicker: true, }); } $(document).ready( function() { getDatePicker(); });
function getDatePicker() { var languageUA = { days: ['Неділя','Понеділок','Вівторок','Середа','Четвер','Пятниця','Субота'], daysShort: ['Нед','Пон','Вів','Сер','Чет','Пят','Суб'], daysMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'], months: ['Січень','Лютий','Березень','Квітень','Травень','Червень','Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'], monthsShort: ['Січ','Лют','Бер','Кві','Тра','Чер','Лип','Сер','Вер','Жов','Лис','Гру'], today: 'Сьогодні', clear: 'Очистити', dateFormat: 'yyyy-mm-dd', timeFormat: 'hh:ii', firstDay: 1, }; $('#id_valid_from').datepicker({ language: languageUA, maxDate: new Date(), }); $('#id_valid_to').datepicker({ language: languageUA, maxDate: new Date(), }); } $(document).ready( function() { getDatePicker(); });
Add petition start date and running time back in for ended petitions
import React from 'react'; import styles from './petition-sidebar.scss'; import Countdown from 'components/Countdown'; import PetitionResponseStatus from 'containers/PetitionResponseStatus'; import ButtonIcon from 'components/ButtonIcon'; import FakeButton from 'components/FakeButton'; import SupportButton from 'containers/SupportButton'; import SharePetition from 'containers/SharePetition'; import settings from 'settings'; const PetitionSidebar = ({ processing, timeMetric, isSupportable, userHasSupported, startDate, runningTime }) => ( <aside role='complementary' className={styles.root}> {processing && <PetitionResponseStatus /> } {isSupportable && <div className={styles.counter}> <Countdown timeMetric={timeMetric} /> </div> } <div className={styles.specifics}> <p>{startDate}</p> <p>{runningTime}</p> </div> <div className={styles['support-button']}> {isSupportable && !userHasSupported && <SupportButton /> } {isSupportable && userHasSupported && <FakeButton disabled block> <ButtonIcon id={'Checkmark'} modifier={'dimmed'}> {settings.petitionPage.supportButton.supportedText} </ButtonIcon> </FakeButton> } {!isSupportable && <FakeButton disabled block> {settings.petitionPage.supportButton.unsupportableText} </FakeButton> } </div> <div className={styles.share}> <SharePetition /> </div> </aside> ); export default PetitionSidebar;
import React from 'react'; import styles from './petition-sidebar.scss'; import Countdown from 'components/Countdown'; import PetitionResponseStatus from 'containers/PetitionResponseStatus'; import ButtonIcon from 'components/ButtonIcon'; import FakeButton from 'components/FakeButton'; import SupportButton from 'containers/SupportButton'; import SharePetition from 'containers/SharePetition'; import settings from 'settings'; const PetitionSidebar = ({ processing, timeMetric, isSupportable, userHasSupported, startDate, runningTime }) => ( <aside role='complementary' className={styles.root}> {processing && <PetitionResponseStatus /> } {isSupportable && <div> <div className={styles.counter}> <Countdown timeMetric={timeMetric} /> </div> <div className={styles.specifics}> <p>{startDate}</p> <p>{runningTime}</p> </div> </div> } <div className={styles['support-button']}> {isSupportable && !userHasSupported && <SupportButton /> } {isSupportable && userHasSupported && <FakeButton disabled block> <ButtonIcon id={'Checkmark'} modifier={'dimmed'}> {settings.petitionPage.supportButton.supportedText} </ButtonIcon> </FakeButton> } {!isSupportable && <FakeButton disabled block> {settings.petitionPage.supportButton.unsupportableText} </FakeButton> } </div> <div className={styles.share}> <SharePetition /> </div> </aside> ); export default PetitionSidebar;
Remove certain meddlesome ActBlue filing from a skip list
var async = require('async'), fs = require('fs'), filingQueue = require('./import'), yauzl = require('yauzl'); var filings_dir = __dirname + '/../../data/fec/filings'; function unzipFile(file,cb) { yauzl.open(file, { autoClose: false }, function(err, zipfile) { if (err) throw err; filingQueue.drain = null; zipfile.on('entry', function(entry) { if (entry.fileName.indexOf('.fec') !== -1) { filingQueue.push({ name: entry.fileName, openStream: function (cb) { zipfile.openReadStream(entry, cb); } }); } }); zipfile.once('end', function () { filingQueue.drain = function () { zipfile.close(); cb(); }; }); }); } fs.readdir(filings_dir, function(err, files) { var q = async.queue(unzipFile, 1); files.forEach(function (file) { if (file.indexOf('.zip') === -1) { return; } q.push(filings_dir + '/' + file); }); q.drain = function () { console.log('done'); }; });
var async = require('async'), fs = require('fs'), filingQueue = require('./import'), yauzl = require('yauzl'); var filings_dir = __dirname + '/../../data/fec/filings'; function unzipFile(file,cb) { yauzl.open(file, { autoClose: false }, function(err, zipfile) { if (err) throw err; filingQueue.drain = null; zipfile.on('entry', function(entry) { if (entry.fileName.indexOf('.fec') !== -1 && entry.fileName.indexOf('1047732.fec') == -1) { filingQueue.push({ name: entry.fileName, openStream: function (cb) { zipfile.openReadStream(entry, cb); } }); } }); zipfile.once('end', function () { filingQueue.drain = function () { zipfile.close(); cb(); }; }); }); } fs.readdir(filings_dir, function(err, files) { var q = async.queue(unzipFile, 1); files.forEach(function (file) { if (file.indexOf('.zip') === -1) { return; } q.push(filings_dir + '/' + file); }); q.drain = function () { console.log('done'); }; });
Add source to project build index query
from __future__ import absolute_import, division, unicode_literals from flask import Response, request from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.models import Project, Build class ProjectBuildIndexAPIView(APIView): def _get_project(self, project_id): project = Project.query.options( joinedload(Project.repository, innerjoin=True), ).filter_by(slug=project_id).first() if project is None: project = Project.query.options( joinedload(Project.repository), ).get(project_id) return project def get(self, project_id): project = self._get_project(project_id) if not project: return '', 404 include_patches = request.args.get('include_patches') or '1' queryset = Build.query.options( joinedload('project', innerjoin=True), joinedload('author'), joinedload('source'), ).filter( Build.project_id == project.id, ).order_by(Build.date_created.desc()) if include_patches == '0': queryset = queryset.filter( Build.patch == None, # NOQA ) return self.paginate(queryset) def get_stream_channels(self, project_id=None): project = self._get_project(project_id) if not project: return Response(status=404) return ['projects:{0}:builds'.format(project.id.hex)]
from __future__ import absolute_import, division, unicode_literals from flask import Response, request from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.models import Project, Build class ProjectBuildIndexAPIView(APIView): def _get_project(self, project_id): project = Project.query.options( joinedload(Project.repository, innerjoin=True), ).filter_by(slug=project_id).first() if project is None: project = Project.query.options( joinedload(Project.repository), ).get(project_id) return project def get(self, project_id): project = self._get_project(project_id) if not project: return '', 404 include_patches = request.args.get('include_patches') or '1' queryset = Build.query.options( joinedload(Build.project, innerjoin=True), joinedload(Build.author), ).filter( Build.project_id == project.id, ).order_by(Build.date_created.desc()) if include_patches == '0': queryset = queryset.filter( Build.patch == None, # NOQA ) return self.paginate(queryset) def get_stream_channels(self, project_id=None): project = self._get_project(project_id) if not project: return Response(status=404) return ['projects:{0}:builds'.format(project.id.hex)]
redis_commands: Use a synopsis for usage examples
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): command_url = "%s%s" % (url, row.get('href')) for sibling in command.itersiblings(): usage = "" for command_args in command.findall('span'): usage = "%s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip()) summary = "%s" % (sibling.text) data[command_url] = (row.text, summary, usage) for command_url in data.keys(): command, summary, usage = data[command_url] summary = unicode(summary).encode("utf-8") usage = unicode(usage).encode("utf-8") f.write("\t".join([str(command), # title "", # namespace command_url, # url summary, # description usage, # synopsis "", # details "", # type "" # lang ]) ) f.write("\n") f.close()
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): command_url = "%s%s" % (url, row.get('href')) for sibling in command.itersiblings(): usage = "" for command_args in command.findall('span'): usage = "Usage: %s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip()) summary = "%s<br>%s" % (sibling.text, usage) data[command_url] = (row.text, summary) for command_url in data.keys(): command, summary = data[command_url] summary = unicode(summary).encode("utf-8") f.write("\t".join([str(command), # title "", # namespace command_url, # url summary, # description "", # synopsis "", # details "", # type "" # lang ]) ) f.write("\n") f.close()
Make xmvn-resolve print resolved artifact files
/*- * Copyright (c) 2012 Red Hat, 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 org.fedoraproject.maven.tools.resolver; import java.io.File; import java.util.StringTokenizer; import org.fedoraproject.maven.resolver.DefaultResolver; import org.fedoraproject.maven.resolver.Resolver; import org.fedoraproject.maven.resolver.SystemResolver; public class ResolverCli { public static void main( String[] args ) { Resolver resolver = new DefaultResolver(); for ( String arg : args ) { StringTokenizer tok = new StringTokenizer( arg, ":" ); String groupId = tok.nextToken(); String artifactId = tok.nextToken(); String version = tok.hasMoreTokens() ? tok.nextToken() : "SYSTEM"; String extension = tok.hasMoreTokens() ? tok.nextToken() : "pom"; File file = resolver.resolve( groupId, artifactId, version, extension ); System.out.println( file ); } SystemResolver.printInvolvedPackages(); } }
/*- * Copyright (c) 2012 Red Hat, 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 org.fedoraproject.maven.tools.resolver; import java.util.StringTokenizer; import org.fedoraproject.maven.resolver.DefaultResolver; import org.fedoraproject.maven.resolver.Resolver; import org.fedoraproject.maven.resolver.SystemResolver; public class ResolverCli { public static void main( String[] args ) { Resolver resolver = new DefaultResolver(); for ( String arg : args ) { StringTokenizer tok = new StringTokenizer( arg, ":" ); String groupId = tok.nextToken(); String artifactId = tok.nextToken(); String version = tok.hasMoreTokens() ? tok.nextToken() : "SYSTEM"; String extension = tok.hasMoreTokens() ? tok.nextToken() : "pom"; resolver.resolve( groupId, artifactId, version, extension ); } SystemResolver.printInvolvedPackages(); } }
Align award to tree sort
import { inject as service } from '@ember/service'; import { not, sort, filterBy } from '@ember/object/computed'; import { task } from 'ember-concurrency'; import Component from '@ember/component'; export default Component.extend({ store: service(), flashMessages: service(), isDisabled: not( 'model.permissions.write', ), sortedContestsProperties: [ 'awardTreeSort', ], sortedContests: sort( 'model.contests', 'sortedContestsProperties' ), filteredContests: filterBy( 'model.contests', 'isIncluded', ), includedContests: sort( 'filteredContests', 'sortedContestsProperties' ), toggleContest: task(function *(property, value) { if (value) { try { let contest = yield property.include({ 'by': this.get('currentUser.user.id'), }); this.store.pushPayload('contest', contest); this.flashMessages.success("Included!"); } catch(e) { this.flashMessages.danger("Problem!"); } } else { try { let contest = yield property.exclude({ 'by': this.get('currentUser.user.id'), }); this.store.pushPayload('contest', contest); this.flashMessages.success("Excluded!"); } catch(e) { this.flashMessages.danger("Problem!"); } } }).drop(), });
import { inject as service } from '@ember/service'; import { not, sort, filterBy } from '@ember/object/computed'; import { task } from 'ember-concurrency'; import Component from '@ember/component'; export default Component.extend({ store: service(), flashMessages: service(), isDisabled: not( 'model.permissions.write', ), sortedContestsProperties: [ 'isPrimary:desc', 'groupKindSort', 'awardQualifier', 'awardAgeSort', 'awardName', ], sortedContests: sort( 'model.contests', 'sortedContestsProperties' ), filteredContests: filterBy( 'model.contests', 'isIncluded', ), includedContests: sort( 'filteredContests', 'sortedContestsProperties' ), toggleContest: task(function *(property, value) { if (value) { try { let contest = yield property.include({ 'by': this.get('currentUser.user.id'), }); this.store.pushPayload('contest', contest); this.flashMessages.success("Included!"); } catch(e) { this.flashMessages.danger("Problem!"); } } else { try { let contest = yield property.exclude({ 'by': this.get('currentUser.user.id'), }); this.store.pushPayload('contest', contest); this.flashMessages.success("Excluded!"); } catch(e) { this.flashMessages.danger("Problem!"); } } }).drop(), });
Fix seller user group level security After refactoring Admin* components to Seller* components we forgot to update the seller user group security controller to use "sellerusergroupid" $stateParam instead of the old "adminusergroupid".
angular.module('orderCloud') .controller('SecurityCtrl', SecurityController) ; function SecurityController($exceptionHandler, $stateParams, toastr, Assignments, AvailableProfiles, OrderCloudSDK) { var vm = this; vm.assignments = Assignments; vm.profiles = AvailableProfiles; vm.buyerid = $stateParams.buyerid; vm.usergroupid = $stateParams.usergroupid; vm.adminusergroupid = $stateParams.adminusergroupid; vm.updateAssignment = function(scope) { if (scope.profile.selected) { var assignment = { securityProfileID: scope.profile.ID, buyerID: $stateParams.buyerid, userGroupID: $stateParams.usergroupid || $stateParams.sellerusergroupid }; OrderCloudSDK.SecurityProfiles.SaveAssignment(assignment) .then(function() { toastr.success(scope.profile.Name + ' was enabled.'); }) .catch(function(ex) { scope.profile.selected = false; $exceptionHandler(ex); }); } else { var options = { buyerID: $stateParams.buyerid, userGroupID: $stateParams.usergroupid || $stateParams.sellerusergroupid }; OrderCloudSDK.SecurityProfiles.DeleteAssignment(scope.profile.ID, options) .then(function() { toastr.success(scope.profile.Name + ' was disabled.'); }) .catch(function(ex) { scope.profile.selected = true; $exceptionHandler(ex); }); } }; }
angular.module('orderCloud') .controller('SecurityCtrl', SecurityController) ; function SecurityController($exceptionHandler, $stateParams, toastr, Assignments, AvailableProfiles, OrderCloudSDK) { var vm = this; vm.assignments = Assignments; vm.profiles = AvailableProfiles; vm.buyerid = $stateParams.buyerid; vm.usergroupid = $stateParams.usergroupid; vm.adminusergroupid = $stateParams.adminusergroupid; vm.updateAssignment = function(scope) { if (scope.profile.selected) { var assignment = { securityProfileID: scope.profile.ID, buyerID: $stateParams.buyerid, userGroupID: $stateParams.usergroupid || $stateParams.adminusergroupid }; OrderCloudSDK.SecurityProfiles.SaveAssignment(assignment) .then(function() { toastr.success(scope.profile.Name + ' was enabled.'); }) .catch(function(ex) { scope.profile.selected = false; $exceptionHandler(ex); }); } else { var options = { buyerID: $stateParams.buyerid, userGroupID: $stateParams.usergroupid || $stateParams.adminusergroupid }; OrderCloudSDK.SecurityProfiles.DeleteAssignment(scope.profile.ID, options) .then(function() { toastr.success(scope.profile.Name + ' was disabled.'); }) .catch(function(ex) { scope.profile.selected = true; $exceptionHandler(ex); }); } }; }
system: Load specific L10n providers in factory
<?php /** * Factory class for providing Localization implementations * @author M2Mobi, Heinz Wiesinger */ class L10nFactory { /** * Instance of the L10nProvider * @var array */ private static $lprovider; /** * Constructor */ public function __construct() { } /** * Destructor */ public function __destruct() { } /** * This method returns an object with the appropriate localization * implementation provider * @param String $provider The localization implementation requested * @param String $language POSIX locale definition * @return L10nProvider $return Instance of the localization provider requested */ public static function get_localization($provider, $language) { switch($provider) { case "php": if (!isset(self::$lprovider[$provider])) { require_once("class.class.l10nproviderphp.inc.php"); self::$lprovider[$provider] = new L10nProviderPHP($language); } return self::$lprovider[$provider]; break; case "gettext": default: if (!isset(self::$lprovider[$provider])) { require_once("class.class.l10nprovidergettext.inc.php"); self::$lprovider[$provider] = new L10nProviderGettext($language); } return self::$lprovider[$provider]; break; } } } ?>
<?php /** * Factory class for providing Localization implementations * @author M2Mobi, Heinz Wiesinger */ class L10nFactory { /** * Instance of the L10nProvider * @var array */ private static $lprovider; /** * Constructor */ public function __construct() { } /** * Destructor */ public function __destruct() { } /** * This method returns an object with the appropriate localization * implementation provider * @param String $provider The localization implementation requested * @param String $language POSIX locale definition * @return L10nProvider $return Instance of the localization provider requested */ public static function get_localization($provider, $language) { switch($provider) { case "php": if (!isset(self::$lprovider[$provider])) { self::$lprovider[$provider] = new L10nProviderPHP($language); } return self::$lprovider[$provider]; break; case "gettext": default: if (!isset(self::$lprovider[$provider])) { self::$lprovider[$provider] = new L10nProviderGettext($language); } return self::$lprovider[$provider]; break; } } } ?>
Undone: Set local worker as default for SyftTensor owner
import random from syft.frameworks.torch.tensors import PointerTensor class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = None def create_pointer( self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None ): if owner is None: owner = self.owner if location is None: location = self.owner.id owner = self.owner.get_worker(owner) location = self.owner.get_worker(location) if id_at_location is None: id_at_location = self.id if ptr_id is None: if location.id != self.owner.id: ptr_id = self.id else: ptr_id = int(10e10 * random.random()) # previous_pointer = owner.get_pointer_to(location, id_at_location) previous_pointer = None if previous_pointer is None: ptr = PointerTensor( parent=self, location=location, id_at_location=id_at_location, register=register, owner=owner, id=ptr_id, ) return ptr
import random from syft.frameworks.torch.tensors import PointerTensor import syft class TorchTensor: """ This tensor is simply a more convenient way to add custom functions to all Torch tensor types. """ def __init__(self): self.id = None self.owner = syft.local_worker def create_pointer( self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None ): if owner is None: owner = self.owner if location is None: location = self.owner.id owner = self.owner.get_worker(owner) location = self.owner.get_worker(location) if id_at_location is None: id_at_location = self.id if ptr_id is None: if location.id != self.owner.id: ptr_id = self.id else: ptr_id = int(10e10 * random.random()) # previous_pointer = owner.get_pointer_to(location, id_at_location) previous_pointer = None if previous_pointer is None: ptr = PointerTensor( parent=self, location=location, id_at_location=id_at_location, register=register, owner=owner, id=ptr_id, ) return ptr
Fix the error when there's no thumbnail available In case the API returns null for the thumbnail, a dummy image is set as the thumbnail prop
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = 'http://placehold.it/250x250'; if(this.props.character.thumbnail) { image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension; } return ( <img className="character-image" src={image}/> ) }, getName: function() { return ( <span className="character-name"> {this.props.character.name} </span> ); }, getDescription: function() { var description = this.props.character.description ? this.props.character.description : 'No description' return ( <p> {description} </p> ) }, getLinks: function() { return ( <p> <a href={this.props.character.urls[0].url}>Wiki</a>| <a href={this.props.character.urls[1].url}>More details</a> </p> ) }, render: function () { return ( <div className="row character"> <div className="col-xs-12"> <div className="row"> <div className="col-xs-3"> {this.getThumbnail()} </div> <div className="col-xs-9"> {this.getName()} <div className="character-description"> {this.getDescription()} {this.getLinks()} </div> </div> </div> </div> </div> ); } }); module.exports = Character;
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension; return ( <img className="character-image" src={image}/> ) }, getName: function() { return ( <span className="character-name"> {this.props.character.name} </span> ); }, getDescription: function() { var description = this.props.character.description ? this.props.character.description : 'No description' return ( <p> {description} </p> ) }, getLinks: function() { return ( <p> <a href={this.props.character.urls[0].url}>Wiki</a>| <a href={this.props.character.urls[1].url}>More details</a> </p> ) }, render: function () { return ( <div className="row character"> <div className="col-xs-12"> <div className="row"> <div className="col-xs-3"> {this.getThumbnail()} </div> <div className="col-xs-9"> {this.getName()} <div className="character-description"> {this.getDescription()} {this.getLinks()} </div> </div> </div> </div> </div> ); } }); module.exports = Character;
Change units in weather api to imperial
//Geolocation Function is listed below. function geoLocation() { var output = document.getElementById("out"); /*$.getJSON('https://ipinfo.io/geo', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; var city = response.city; var state = response.region; var postal = response.postal; var country = response.country; output.innerHTML = "<p>Here is the weather for " + city + ", " + state;*/ $.getJSON('http://ip-api.com/json', function(response) { var city = response.city; var state = response.region; var zip = response.zip; var country = response.countryCode; var ip = response.query; output.innerHTML = "<p>Here is the weather for " + city + ", " + state; $.getJSON('http://api.openweathermap.org/data/2.5/weather?zip=' + zip + ',' + country + "&units=imperial" + "&appid=ec96c6ed7e722bdd15cfebffbff509a6", function(data) { //var main = data.main.split(','); var temp = data.main.temp; console.log(temp); var weatherConditions = document.getElementById("conditions"); conditions.innerHTML = "<p>The current temperature is " + temp; }); }); }
//Geolocation Function is listed below. function geoLocation() { var output = document.getElementById("out"); /*$.getJSON('https://ipinfo.io/geo', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; var city = response.city; var state = response.region; var postal = response.postal; var country = response.country; output.innerHTML = "<p>Here is the weather for " + city + ", " + state;*/ $.getJSON('http://ip-api.com/json', function(response) { var city = response.city; var state = response.region; var zip = response.zip; var country = response.countryCode; var ip = response.query; output.innerHTML = "<p>Here is the weather for " + city + ", " + state; $.getJSON('http://api.openweathermap.org/data/2.5/weather?zip=' + zip + ',' + country + "&appid=ec96c6ed7e722bdd15cfebffbff509a6", function(data) { //var main = data.main.split(','); var temp = data.main.temp; console.log(temp); var weatherConditions = document.getElementById("conditions"); conditions.innerHTML = "<p>The current temperature is " + temp; }); }); }
Fix notifications to use the wordName rather than wordId
import Ember from 'ember'; import ENV from '../config/environment'; import { Bindings } from 'ember-pusher/bindings'; // used by the Application controller export default Ember.Mixin.create(Bindings, { logPusherEvents: (ENV.environment === "development"), PUSHER_SUBSCRIPTIONS: { activities: ["push"] }, userChannel: function() { console.log(this.get("session.username")); }.property("session.username"), subscribeToMyChannel: function() { var channelName = this.get("username") + '_channel'; this.pusher.wire(this, channelName, ['notify']); }.observes("userChannel"), init: function() { this._super(); this.subscribeToMyChannel(); }, actions: { push: function(data) { this.store.pushPayload('activity', data); }, notify: function(data) { this.store.pushPayload('notification', data); var activity = data.activities[0]; Ember.$.post(ENV.api + "/notifications/" + data.notification.id + "/ack"); switch (activity.type) { case "ProposalComment": this.get("notifier").show("On your proposal for " + activity.wordName, {name: "New Comment", route: ["proposal.index", activity.proposalId]}); break; case "ProposalClosed": this.get("notifier").show("Your proposal for " + activity.wordName + " was " + activity.finalState, {name: "Proposal", route: ["proposal.index", activity.proposalId]}); break; } } }, });
import Ember from 'ember'; import ENV from '../config/environment'; import { Bindings } from 'ember-pusher/bindings'; // used by the Application controller export default Ember.Mixin.create(Bindings, { logPusherEvents: (ENV.environment === "development"), PUSHER_SUBSCRIPTIONS: { activities: ["push"] }, userChannel: function() { console.log(this.get("session.username")); }.property("session.username"), subscribeToMyChannel: function() { var channelName = this.get("username") + '_channel'; this.pusher.wire(this, channelName, ['notify']); }.observes("userChannel"), init: function() { this._super(); this.subscribeToMyChannel(); }, actions: { push: function(data) { this.store.pushPayload('activity', data); }, notify: function(data) { this.store.pushPayload('notification', data); var activity = data.activities[0]; Ember.$.post(ENV.api + "/notifications/" + data.notification.id + "/ack"); switch (activity.type) { case "ProposalComment": this.get("notifier").show("On your proposal for " + activity.wordId, {name: "New Comment", route: ["proposal.index", activity.proposalId]}); break; case "ProposalClosed": this.get("notifier").show("Your proposal for " + activity.wordId + " was " + activity.finalState, {name: "Proposal", route: ["proposal.index", activity.proposalId]}); break; } } }, });
Make min length of lastname =2
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use App\Business; use App\Contact; use Route; class AlterContactRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return $this->contact === null || \Auth::user()->contacts->contains($this->contact); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'firstname' => 'required|min:3', 'lastname' => 'required|min:2', 'gender' => 'required|max:1', 'mobile_country' => 'required_with:mobile|size:2', 'mobile' => 'phone', 'email' => 'email' ]; switch ($this->method()) { case 'PATCH': case 'PUT': case 'POST': return $rules; break; default: return []; break; } } }
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use App\Business; use App\Contact; use Route; class AlterContactRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return $this->contact === null || \Auth::user()->contacts->contains($this->contact); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'firstname' => 'required|min:3', 'lastname' => 'required|min:3', 'gender' => 'required|max:1', 'mobile_country' => 'required_with:mobile|size:2', 'mobile' => 'phone', 'email' => 'email' ]; switch ($this->method()) { case 'PATCH': case 'PUT': case 'POST': return $rules; break; default: return []; break; } } }
Check event name when constructing. Cannot be empty.
<?php namespace Arch; /** * Class event */ class Event { /** * The event name * @var string */ protected $name; /** * The event callback * @var mixed */ protected $callback; /** * An optional target * @var mixed */ protected $target; /** * Returns a new event * @param string $name The event name * @param mixed $callback The event callback */ public function __construct($name, $callback, $target = null) { if (!is_string($name)) { throw new \Exception('Invalid event name'); } if (empty($name)) { throw new \Exception('Invalid event name'); } $this->name = $name; if (!is_callable($callback)) { throw new \Exception('Invalid event callback'); } $this->callback = $callback; $this->target = $target; } /** * Triggers this event * @param mixed $target An optional target */ public function trigger($target = null) { if (empty($target)) { $target = $this->target; } $fn = $this->callback; $fn($target); } }
<?php namespace Arch; /** * Class event */ class Event { /** * The event name * @var string */ protected $name; /** * The event callback * @var mixed */ protected $callback; /** * An optional target * @var mixed */ protected $target; /** * Returns a new event * @param string $name The event name * @param mixed $callback The event callback */ public function __construct($name, $callback, $target = null) { if (!is_string($name)) { throw new \Exception('Invalid event name'); } $this->name = $name; if (!is_callable($callback)) { throw new \Exception('Invalid event callback'); } $this->callback = $callback; $this->target = $target; } /** * Triggers this event * @param mixed $target An optional target */ public function trigger($target = null) { if (empty($target)) { $target = $this->target; } $fn = $this->callback; $fn($target); } }
Use existing `afterNodeCreate` signal to trigger NodeConfigurator
<?php namespace M12\Foundation; /* * * This script belongs to the "M12.Foundation" package. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License, either version 3 of the * * License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Flow\Package\Package as BasePackage; use TYPO3\Flow\Core\Bootstrap; /** * The M12.Foundation Package */ class Package extends BasePackage { /** * Invokes custom PHP code directly after the package manager has been initialized. * * @param Bootstrap $bootstrap The current bootstrap * @return void */ public function boot(Bootstrap $bootstrap) { $dispatcher = $bootstrap->getSignalSlotDispatcher(); $dispatcher->connect('TYPO3\TYPO3CR\Domain\Model\Node', 'afterNodeCreate', 'M12\Foundation\Node\NodeConfigurator', 'afterNodeCreate'); } }
<?php namespace M12\Foundation; /* * * This script belongs to the "M12.Foundation" package. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License, either version 3 of the * * License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Flow\Package\Package as BasePackage; use TYPO3\Flow\Core\Bootstrap; /** * The M12.Foundation Package */ class Package extends BasePackage { /** * Invokes custom PHP code directly after the package manager has been initialized. * * @param Bootstrap $bootstrap The current bootstrap * @return void */ public function boot(Bootstrap $bootstrap) { $signalDispatcher = 'TYPO3\Neos\Service\NodeOperations'; $signalName = 'afterNodeCreate'; // We don't use `NodeOperations` during tests, so listen to original signal from TYPO3CR if ($bootstrap->getContext()->isTesting()) { $signalDispatcher = 'TYPO3\TYPO3CR\Domain\Model\Node'; } $dispatcher = $bootstrap->getSignalSlotDispatcher(); $dispatcher->connect($signalDispatcher, $signalName, 'M12\Foundation\Node\NodeConfigurator', 'afterNodeCreate'); } }
Revert to using the base postgres driver in tests
package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" ); final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } }
package org.realityforge.jeo.geolatte.jpa.eclipselink; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class DatabaseTestUtil { static Properties initDatabaseProperties() { final Properties properties = new Properties(); properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" ); final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test"; setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl ); setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" ); setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null ); properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() ); return properties; } private static void setProperty( final Properties properties, final String key, final String systemPropertyKey, final String defaultValue ) { final String value = System.getProperty( systemPropertyKey, defaultValue ); if ( null != value ) { properties.put( key, value ); } } public static EntityManager createEntityManager( final String persistenceUnitName ) { final Properties properties = initDatabaseProperties(); final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties ); return factory.createEntityManager(); } }
Add test for export declarations to findUsedIdentifiers I recently added some test that changed how identifiers were visited, and I just wanted to make sure I didn't break anything for the findUsedIdentifiers module.
import findUsedIdentifiers from '../findUsedIdentifiers'; import parse from '../parse'; it('finds used variables', () => { expect( findUsedIdentifiers( parse( ` api.something(); const foo = 'foo'; foo(); bar(); `, ), ), ).toEqual(new Set(['api', 'foo', 'bar'])); }); it('knows about jsx', () => { expect( findUsedIdentifiers( parse( ` <Foo bar={far.foo()}/> `, ), ), ).toEqual(new Set(['far', 'React', 'Foo'])); }); it('knows about flow annotations', () => { expect( findUsedIdentifiers( parse( ` class Foo { bar: Car; } `, ), ), ).toEqual(new Set(['Car'])); }); it('knows about export declarations', () => { expect( findUsedIdentifiers( parse( ` export { foo as bar } export { baz } `, ), ), ).toEqual(new Set(['foo', 'baz'])); }); it('treats items in arrays as used', () => { expect( findUsedIdentifiers( parse( ` [Foo, Bar] `, ), ), ).toEqual(new Set(['Foo', 'Bar'])); }); it('treats items used as arguments as used', () => { expect( findUsedIdentifiers( parse( ` foo(Foo, Bar); `, ), ), ).toEqual(new Set(['foo', 'Foo', 'Bar'])); });
import findUsedIdentifiers from '../findUsedIdentifiers'; import parse from '../parse'; it('finds used variables', () => { expect( findUsedIdentifiers( parse( ` api.something(); const foo = 'foo'; foo(); bar(); `, ), ), ).toEqual(new Set(['api', 'foo', 'bar'])); }); it('knows about jsx', () => { expect( findUsedIdentifiers( parse( ` <Foo bar={far.foo()}/> `, ), ), ).toEqual(new Set(['far', 'React', 'Foo'])); }); it('knows about flow annotations', () => { expect( findUsedIdentifiers( parse( ` class Foo { bar: Car; } `, ), ), ).toEqual(new Set(['Car'])); }); it('treats items in arrays as used', () => { expect( findUsedIdentifiers( parse( ` [Foo, Bar] `, ), ), ).toEqual(new Set(['Foo', 'Bar'])); }); it('treats items used as arguments as used', () => { expect( findUsedIdentifiers( parse( ` foo(Foo, Bar); `, ), ), ).toEqual(new Set(['foo', 'Foo', 'Bar'])); });
Add PHP code highlighting within package descriptions, patch from Amir.
<?php // Set the title for the main template $parent->context->page_title = $context->name.' | pear2.php.net'; ?> <div class="package"> <div class="grid_8 left"> <h2>Package :: <?php echo $context->name; ?></h2> <p><em><?php echo $context->summary; ?></em></p> <p> <?php $description = preg_replace("|<\?php(.*)\?\>|Use", "highlight_string('<?php\\1?>', true)", trim($context->getRaw('description'))); echo nl2br($description); ?> </p> <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?> </div> <div class="grid_4 right releases"> <h3>Releases</h3> <ul> <?php foreach ($context as $version => $release): ?> <li> <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?></a> <span class="stability"><?php echo $release['stability']; ?></span> <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr> <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download</a> </li> <?php endforeach; ?> </ul> </div> </div>
<?php // Set the title for the main template $parent->context->page_title = $context->name.' | pear2.php.net'; ?> <div class="package"> <div class="grid_8 left"> <h2>Package :: <?php echo $context->name; ?></h2> <p><em><?php echo $context->summary; ?></em></p> <p> <?php echo nl2br(trim($context->description)); ?> </p> <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?> </div> <div class="grid_4 right releases"> <h3>Releases</h3> <ul> <?php foreach ($context as $version => $release): ?> <li> <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?></a> <span class="stability"><?php echo $release['stability']; ?></span> <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?></abbr> <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download</a> </li> <?php endforeach; ?> </ul> </div> </div>
Change status from Beta to Production/Stable
#!/usr/bin/env python from setuptools import setup, find_packages with open('README.rst') as readme_file: README = readme_file.read() install_requires = [ 'click==6.6', 'botocore>=1.5.40,<2.0.0', 'typing==3.5.3.0', 'six>=1.10.0,<2.0.0', 'pip>=9,<10' ] setup( name='chalice', version='1.0.0', description="Microframework", long_description=README, author="James Saryerwinnie", author_email='[email protected]', url='https://github.com/jamesls/chalice', packages=find_packages(exclude=['tests']), install_requires=install_requires, license="Apache License 2.0", package_data={'chalice': ['*.json']}, include_package_data=True, zip_safe=False, keywords='chalice', entry_points={ 'console_scripts': [ 'chalice = chalice.cli:main', ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
#!/usr/bin/env python from setuptools import setup, find_packages with open('README.rst') as readme_file: README = readme_file.read() install_requires = [ 'click==6.6', 'botocore>=1.5.40,<2.0.0', 'typing==3.5.3.0', 'six>=1.10.0,<2.0.0', 'pip>=9,<10' ] setup( name='chalice', version='1.0.0', description="Microframework", long_description=README, author="James Saryerwinnie", author_email='[email protected]', url='https://github.com/jamesls/chalice', packages=find_packages(exclude=['tests']), install_requires=install_requires, license="Apache License 2.0", package_data={'chalice': ['*.json']}, include_package_data=True, zip_safe=False, keywords='chalice', entry_points={ 'console_scripts': [ 'chalice = chalice.cli:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
Fix upgrade script: Check for empty items
/** @namespace H5PUpgrades */ var H5PUpgrades = H5PUpgrades || {}; H5PUpgrades['H5P.Agamotto'] = (function ($) { return { 1: { 3: function (parameters, finished) { // Update image items if (parameters.items) { parameters.items = parameters.items.map( function (item) { // Create new image structure var newImage = { library: 'H5P.Image 1.0', // We avoid using H5P.createUUID since this is an upgrade script and H5P function may change subContentId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(char) { var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8); return newChar.toString(16); }), params: { alt: item.labelText || '', contentName: 'Image', title: item.labelText || '', file: item.image } }; // Compose new item item = { description: item.description, image: newImage, labelText: item.labelText }; return item; }); } finished(null, parameters); } } }; })(H5P.jQuery);
/** @namespace H5PUpgrades */ var H5PUpgrades = H5PUpgrades || {}; H5PUpgrades['H5P.Agamotto'] = (function ($) { return { 1: { 3: function (parameters, finished) { // Update image items parameters.items = parameters.items.map( function (item) { // Create new image structure var newImage = { library: 'H5P.Image 1.0', // We avoid using H5P.createUUID since this is an upgrade script and H5P function may change subContentId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(char) { var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8); return newChar.toString(16); }), params: { alt: item.labelText || '', contentName: 'Image', title: item.labelText || '', file: item.image } }; // Compose new item item = { description: item.description, image: newImage, labelText: item.labelText }; return item; }); finished(null, parameters); } } }; })(H5P.jQuery);
Change getting key method (SAAS-612) Change key text split by '==' to split by whitespace. http://localhost:8001/#/keys/add/
(function() { angular.module('ncsaas') .controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]); function KeyAddController(baseControllerAddClass, keysService, $state) { var controllerScope = this; var Controller = baseControllerAddClass.extend({ init: function() { this.service = keysService; this.controllerScope = controllerScope; this._super(); this.listState = 'profile.details'; }, successRedirect: function() { $state.go('profile.details', {tab: 'keys'}); }, save: function() { if (this.instance.name) { this._super(); } else { if (this.instance.public_key) { var key = this.instance.public_key.split(' '); if (key[2]) { this.instance.name = key[2].trim(); this._super(); } else { this.errors = {name: ['This field may not be blank.']}; } } else { this.errors = {public_key: ['This field may not be blank.']}; } } } }); controllerScope.__proto__ = new Controller(); } })();
(function() { angular.module('ncsaas') .controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]); function KeyAddController(baseControllerAddClass, keysService, $state) { var controllerScope = this; var Controller = baseControllerAddClass.extend({ init: function() { this.service = keysService; this.controllerScope = controllerScope; this._super(); this.listState = 'profile.details'; }, successRedirect: function() { $state.go('profile.details', {tab: 'keys'}); }, save: function() { if (this.instance.name) { this._super(); } else { if (this.instance.public_key) { var key = this.instance.public_key.split('=='); if (key[1]) { this.instance.name = key[1]; this._super(); } else { this.errors = {name: ['This field may not be blank.']}; } } else { this.errors = {public_key: ['This field may not be blank.']}; } } } }); controllerScope.__proto__ = new Controller(); } })();
PUBDEV-2984: Add pyunit test for model_performance(xval=True)
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() print(prostate_gbm.model_performance(xval=True)) # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm()
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def cv_nfolds_gbm(): prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) prostate[1] = prostate[1].asfactor() prostate.summary() prostate_gbm = H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli") prostate_gbm.train(x=list(range(2,9)), y=1, training_frame=prostate) prostate_gbm.show() # Can specify both nfolds >= 2 and validation data at once try: H2OGradientBoostingEstimator(nfolds=5, distribution="bernoulli").train(x=list(range(2,9)), y=1, training_frame=prostate, validation_frame=prostate) assert True except EnvironmentError: assert False, "expected an error" if __name__ == "__main__": pyunit_utils.standalone_test(cv_nfolds_gbm) else: cv_nfolds_gbm()
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC.
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 80', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 72', 'Edge >= 18'] : pkg.browserslist || ['> 1% in AU', 'Firefox ESR', 'IE 11'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 76', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 69', 'Edge >= 18'] : pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
Fix: Add type to param annotation
<?php namespace Joindin\Api\Model; use Joindin\Api\Request; /** * Container for multiple EventCommentReportModel objects */ class PendingTalkClaimModelCollection extends BaseModelCollection { /** @var array|PendingTalkClaimModel[] */ protected $list; protected $total; /** * Take arrays of data and create a collection of models; store metadata * * @param array $data * @param int $total */ public function __construct(array $data, $total) { $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list foreach ($data as $item) { if (!$item instanceof PendingTalkClaimModel) { $item = new PendingTalkClaimModel($item); } $this->list[] = $item; } } /** * Present this collection ready for the output handlers * * This creates the expected output structure, converting each resource * to it's presentable representation and adding the meta fields for totals * and pagination * * @param Request $request * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { $retval = []; // handle the collection first $retval = ['claims' => []]; foreach ($this->list as $item) { $retval['claims'][] = $item->getOutputView($request, $verbose); } // add other fields $retval['meta'] = $this->addPaginationLinks($request); return $retval; } }
<?php namespace Joindin\Api\Model; use Joindin\Api\Request; /** * Container for multiple EventCommentReportModel objects */ class PendingTalkClaimModelCollection extends BaseModelCollection { /** @var array|PendingTalkClaimModel[] */ protected $list; protected $total; /** * Take arrays of data and create a collection of models; store metadata * * @param array $data * @param $total */ public function __construct(array $data, $total) { $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list foreach ($data as $item) { if (!$item instanceof PendingTalkClaimModel) { $item = new PendingTalkClaimModel($item); } $this->list[] = $item; } } /** * Present this collection ready for the output handlers * * This creates the expected output structure, converting each resource * to it's presentable representation and adding the meta fields for totals * and pagination * * @param Request $request * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { $retval = []; // handle the collection first $retval = ['claims' => []]; foreach ($this->list as $item) { $retval['claims'][] = $item->getOutputView($request, $verbose); } // add other fields $retval['meta'] = $this->addPaginationLinks($request); return $retval; } }
Fix warning from React component prop not being camelCased
const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => { if (locations.length >= 2) { locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`; } else if (locations.length === 0) { locations = 'Ikke spesifisert'; } return ( <article className="row"> <div className="col-xs-12 col-md-4"> <a href="/careeropportunity/4/"> <picture> <source srcSet={companyImage.lg} media="(max-width: 992px)" /> <img src={companyImage.md} alt="Firmalogo" /> </picture> </a> </div> <div className="col-xs-12 col-md-8"> <h1> <a href="/careeropportunity/4/">{companyName} - {jobTitle}</a> </h1> <div className="ingress">{ingress}</div> <div className="meta"> <div className="col-md-4"> <p>Type: {jobName}</p> </div> <div className="col-md-4"> <p>Sted: {locations}</p> </div> <div className="col-md-4"> <p>Frist: {deadline}</p> </div> </div> </div> </article> ); }; export default Job;
const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => { if (locations.length >= 2) { locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`; } else if (locations.length === 0) { locations = 'Ikke spesifisert'; } return ( <article className="row"> <div className="col-xs-12 col-md-4"> <a href="/careeropportunity/4/"> <picture> <source srcset={companyImage.lg} media="(max-width: 992px)" /> <img src={companyImage.md} alt="Firmalogo" /> </picture> </a> </div> <div className="col-xs-12 col-md-8"> <h1> <a href="/careeropportunity/4/">{companyName} - {jobTitle}</a> </h1> <div className="ingress">{ingress}</div> <div className="meta"> <div className="col-md-4"> <p>Type: {jobName}</p> </div> <div className="col-md-4"> <p>Sted: {locations}</p> </div> <div className="col-md-4"> <p>Frist: {deadline}</p> </div> </div> </div> </article> ); }; export default Job;
Change the VERSION to 1.1.0.pre
VERSION = (1, 1, 0, 'pre') __version__ = '.'.join(map(str, VERSION)) import logging logger = logging.getLogger('plata') class LazySettings(object): def _load_settings(self): from plata import default_settings from django.conf import settings as django_settings for key in dir(default_settings): if not key.startswith(('PLATA', 'CURRENCIES')): continue setattr(self, key, getattr(django_settings, key, getattr(default_settings, key))) def __getattr__(self, attr): self._load_settings() del self.__class__.__getattr__ return self.__dict__[attr] settings = LazySettings() shop_instance_cache = None def register(instance): logger.debug('Registering shop instance: %s' % instance) global shop_instance_cache shop_instance_cache = instance def shop_instance(): """ This method ensures that all views and URLs are properly loaded, and returns the centrally instantiated :class:`plata.shop.views.Shop` object. """ if not shop_instance_cache: # Load default URL patterns to ensure that the shop # object has been created from django.core.urlresolvers import get_resolver get_resolver(None)._populate() return shop_instance_cache def product_model(): """ Return the product model defined by the ``PLATA_SHOP_PRODUCT`` setting. """ from django.db.models import loading return loading.get_model(*settings.PLATA_SHOP_PRODUCT.split('.'))
VERSION = (1, 0, 0) __version__ = '.'.join(map(str, VERSION)) import logging logger = logging.getLogger('plata') class LazySettings(object): def _load_settings(self): from plata import default_settings from django.conf import settings as django_settings for key in dir(default_settings): if not key.startswith(('PLATA', 'CURRENCIES')): continue setattr(self, key, getattr(django_settings, key, getattr(default_settings, key))) def __getattr__(self, attr): self._load_settings() del self.__class__.__getattr__ return self.__dict__[attr] settings = LazySettings() shop_instance_cache = None def register(instance): logger.debug('Registering shop instance: %s' % instance) global shop_instance_cache shop_instance_cache = instance def shop_instance(): """ This method ensures that all views and URLs are properly loaded, and returns the centrally instantiated :class:`plata.shop.views.Shop` object. """ if not shop_instance_cache: # Load default URL patterns to ensure that the shop # object has been created from django.core.urlresolvers import get_resolver get_resolver(None)._populate() return shop_instance_cache def product_model(): """ Return the product model defined by the ``PLATA_SHOP_PRODUCT`` setting. """ from django.db.models import loading return loading.get_model(*settings.PLATA_SHOP_PRODUCT.split('.'))
Use static method instead of classmethod
# -*- encoding: utf-8 -*- import logging import yaml from collections import namedtuple log = logging.getLogger(__name__) def load(filename): with open(filename) as fp: config = yaml.safe_load(fp) return CfnCliConfig.load(config) class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints environments')): CFNFILE_V1 = 1 CFNFILE_V2 = 2 VERSION_SECTION = 'Version' BLUEPRINT_SECTION = 'Blueprints' ENVIRONMENT_SECTION = 'Environments' @staticmethod def load(config): # load version version = config.get(CfnCliConfig.VERSION_SECTION, CfnCliConfig.CFNFILE_V1) # load blueprint into dict blueprint_section = config.get(CfnCliConfig.BLUEPRINT_SECTION, {}) blueprints = {} for key, val in blueprint_section: blueprints[key] = Blueprint.load(val) # load environment into dict environment_section = config.get(CfnCliConfig.ENVIRONMENT_SECTION, {}) environments = {} for key, val in environment_section: environments[key] = Environment.load(val) return CfnCliConfig(version, blueprints, environments) class Stack(namedtuple('Stack', '')): @staticmethod def load(config): return Stack() class Environment(namedtuple('Environment', '')): @staticmethod def load(config): return Environment() class Blueprint(namedtuple('Blueprint', '')): @staticmethod def load(config): return Blueprint()
# -*- encoding: utf-8 -*- import logging import yaml from collections import namedtuple log = logging.getLogger(__name__) def load(filename): with open(filename) as fp: config = yaml.safe_load(fp) return CfnCliConfig.load(config) class CfnCliConfig(namedtuple('CfnCliConfig', 'version blueprints environments')): CFNFILE_V1 = 1 CFNFILE_V2 = 2 VERSION_SECTION = 'Version' BLUEPRINT_SECTION = 'Blueprints' ENVIRONMENT_SECTION = 'Environments' @classmethod def load(cls, config): # load version version = config.get(cls.VERSION_SECTION, cls.CFNFILE_V1) # load blueprint into dict blueprint_section = config.get(cls.BLUEPRINT_SECTION, {}) blueprints = {} for key, val in blueprint_section: blueprints[key] = Blueprint.load(val) # load environment into dict environment_section = config.get(cls.ENVIRONMENT_SECTION, {}) environments = {} for key, val in environment_section: environments[key] = Environment.load(val) return cls(version, blueprints, environments) class Stack(namedtuple('Stack', '')): @classmethod def load(cls, config): return cls() class Environment(namedtuple('Environment', '')): @classmethod def load(cls, config): return cls() class Blueprint(namedtuple('Blueprint', '')): @classmethod def load(cls, config): return cls()
Use list comp instead of unnecessary dict comp
from framework.tasks.handlers import enqueue_task from framework.archiver.tasks import archive, send_success_message from framework.archiver.utils import ( link_archive_provider, ) from framework.archiver import ( ARCHIVER_SUCCESS, ARCHIVER_FAILURE, ) from framework.archiver.exceptions import ArchiverCopyError from website.project import signals as project_signals @project_signals.after_create_registration.connect def archive_node(src, dst, user): """Blinker listener for registration initiations. Enqueqes an archive task :param src: Node being registered :param dst: registration Node :param user: registration initiator """ link_archive_provider(dst, user) enqueue_task(archive.si(src._id, dst._id, user._id)) @project_signals.archive_callback.connect def archive_callback(dst): """Blinker listener for updates to the archive task. When no tasks are pending, either fail the registration or send a success email :param dst: registration Node """ if not dst.archiving: return pending = [value for value in dst.archived_providers.values() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)] if not pending: dst.archiving = False dst.save() if ARCHIVER_FAILURE in [value['status'] for value in dst.archived_providers.values()]: raise ArchiverCopyError(dst.registered_from, dst, dst.creator, dst.archived_providers) else: send_success_message.delay(dst._id)
from framework.tasks.handlers import enqueue_task from framework.archiver.tasks import archive, send_success_message from framework.archiver.utils import ( link_archive_provider, ) from framework.archiver import ( ARCHIVER_SUCCESS, ARCHIVER_FAILURE, ) from framework.archiver.exceptions import ArchiverCopyError from website.project import signals as project_signals @project_signals.after_create_registration.connect def archive_node(src, dst, user): """Blinker listener for registration initiations. Enqueqes an archive task :param src: Node being registered :param dst: registration Node :param user: registration initiator """ link_archive_provider(dst, user) enqueue_task(archive.si(src._id, dst._id, user._id)) @project_signals.archive_callback.connect def archive_callback(dst): """Blinker listener for updates to the archive task. When no tasks are pending, either fail the registration or send a success email :param dst: registration Node """ if not dst.archiving: return pending = {key: value for key, value in dst.archived_providers.iteritems() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)} if not len(pending): dst.archiving = False dst.save() if ARCHIVER_FAILURE in [value['status'] for value in dst.archived_providers.values()]: raise ArchiverCopyError(dst.registered_from, dst, dst.creator, dst.archived_providers) else: send_success_message.delay(dst._id)
Remove attempt to populate file input
App.extend({ Components: {} }); App.Components.Form = (function ($) { var pub = { name: 'app.Components.Form', events: ['change'], assignFormValue: function (element, value) { var isJqueryObj = element instanceof jQuery; if (!isJqueryObj) { element = $(element); } if (element.is(':checkbox')) { var shouldCheck = value == element.val() || indexOf(element.val(), value) > -1; var alreadyCheck = element.is(':checked'); if (( shouldCheck && !alreadyCheck ) || ( !shouldCheck && alreadyCheck )) { element.trigger('click'); } element.attr('checked', shouldCheck); } else { if (element.files.length > 0) { return; } if (element.is('select')) { element.attr('data-selected', value); } element.val(value); element.trigger('change'); } }, init: function () { } }; /** * Return index an element in array using loose comparison * @param needle * @param haystack * @returns {number} */ function indexOf(needle, haystack) { if (haystack == null) return -1; var size = haystack.length; var current = 0; for (; current < size && haystack[current] != needle; current++) { } return (current == size) ? -1 : current; } return pub; })(jQuery); App.initModule(App.Components.Form);
App.extend({ Components: {} }); App.Components.Form = (function ($) { var pub = { name: 'app.Components.Form', events: ['change'], assignFormValue: function (element, value) { var isJqueryObj = element instanceof jQuery; if (!isJqueryObj) { element = $(element); } if (element.is(':checkbox')) { var shouldCheck = value == element.val() || indexOf(element.val(), value) > -1; var alreadyCheck = element.is(':checked'); if (( shouldCheck && !alreadyCheck ) || ( !shouldCheck && alreadyCheck )) { element.trigger('click'); } element.attr('checked', shouldCheck); } else { if (element.is('select')) { element.attr('data-selected', value); } element.val(value); element.trigger('change'); } }, init: function () { } }; /** * Return index an element in array using loose comparison * @param needle * @param haystack * @returns {number} */ function indexOf(needle, haystack) { if (haystack == null) return -1; var size = haystack.length; var current = 0; for (; current < size && haystack[current] != needle; current++) { } return (current == size) ? -1 : current; } return pub; })(jQuery); App.initModule(App.Components.Form);
Change pypi version to 1.6.14-1
from setuptools import setup, find_packages import client VERSION = client.__version__ setup( name='okpy', version='1.6.14-1', # version=VERSION, author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu', # author_email='', description=('ok.py supports programming projects by running tests, ' 'tracking progress, and assisting in debugging.'), # long_description=long_description, url='https://github.com/Cal-CS-61A-Staff/ok-client', # download_url='https://github.com/Cal-CS-61A-Staff/ok/releases/download/v{}/ok'.format(VERSION), license='Apache License, Version 2.0', keywords=['education', 'autograding'], packages=find_packages(include=[ 'client', 'client.*', ]), package_data={ 'client': ['config.ok'], }, # install_requires=[], entry_points={ 'console_scripts': [ 'ok=client.cli.ok:main', 'ok-publish=client.cli.publish:main', 'ok-lock=client.cli.lock:main', 'ok-test=client.cli.test:main', ], }, classifiers=[ 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup, find_packages import client VERSION = client.__version__ setup( name='okpy', version=VERSION, author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu', # author_email='', description=('ok.py supports programming projects by running tests, ' 'tracking progress, and assisting in debugging.'), # long_description=long_description, url='https://github.com/Cal-CS-61A-Staff/ok-client', # download_url='https://github.com/Cal-CS-61A-Staff/ok/releases/download/v{}/ok'.format(VERSION), license='Apache License, Version 2.0', keywords=['education', 'autograding'], packages=find_packages(include=[ 'client', 'client.*', ]), package_data={ 'client': ['config.ok'], }, # install_requires=[], entry_points={ 'console_scripts': [ 'ok=client.cli.ok:main', 'ok-publish=client.cli.publish:main', 'ok-lock=client.cli.lock:main', 'ok-test=client.cli.test:main', ], }, classifiers=[ 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Fix typo "ech" -> "each"
""" This plugin implements :func:`startTestRun`, setting a test executor (``event.executeTests``) that just collects tests without executing them. To do so it calls result.startTest, result.addSuccess and result.stopTest for each test, without calling the test itself. """ from nose2.events import Plugin from nose2.compat import unittest __unittest = True class CollectOnly(Plugin): """Collect but don't run tests""" configSection = 'collect-only' commandLineSwitch = (None, 'collect-only', 'Collect and output test names; do not run any tests') _mpmode = False def registerInSubprocess(self, event): event.pluginClasses.append(self.__class__) self._mpmode = True def startTestRun(self, event): """Replace ``event.executeTests``""" if self._mpmode: return event.executeTests = self.collectTests def startSubprocess(self, event): event.executeTests = self.collectTests def collectTests(self, suite, result): """Collect tests, but don't run them""" for test in suite: if isinstance(test, unittest.BaseTestSuite): self.collectTests(test, result) continue result.startTest(test) result.addSuccess(test) result.stopTest(test)
""" This plugin implements :func:`startTestRun`, setting a test executor (``event.executeTests``) that just collects tests without executing them. To do so it calls result.startTest, result.addSuccess and result.stopTest for ech test, without calling the test itself. """ from nose2.events import Plugin from nose2.compat import unittest __unittest = True class CollectOnly(Plugin): """Collect but don't run tests""" configSection = 'collect-only' commandLineSwitch = (None, 'collect-only', 'Collect and output test names; do not run any tests') _mpmode = False def registerInSubprocess(self, event): event.pluginClasses.append(self.__class__) self._mpmode = True def startTestRun(self, event): """Replace ``event.executeTests``""" if self._mpmode: return event.executeTests = self.collectTests def startSubprocess(self, event): event.executeTests = self.collectTests def collectTests(self, suite, result): """Collect tests, but don't run them""" for test in suite: if isinstance(test, unittest.BaseTestSuite): self.collectTests(test, result) continue result.startTest(test) result.addSuccess(test) result.stopTest(test)