text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove create device step (not needed?) | from flow import Flow
import logging
from . import settings
LOG = logging.getLogger("flowbot.server")
class Server(object):
"""A connection to Flow."""
def __init__(self):
"""Initialize a flow server instance."""
self.flow = Flow()
self._start_server()
self._setup_account()
self._setup_org()
def _start_server(self):
"""Attempt to start the flow server."""
try:
self.flow.start_up(username=settings.USERNAME)
LOG.info("local account '%s' started", settings.USERNAME)
except Flow.FlowError as start_up_err:
LOG.debug("start_up failed: '%s'", str(start_up_err))
def _setup_account(self):
"""Create an account, if it doesn't already exist."""
try:
self.flow.create_account(
username=settings.USERNAME,
password=settings.PASSWORD
)
except Flow.FlowError as create_account_err:
LOG.debug("Create account failed: '%s'", str(create_account_err))
def _setup_org(self):
""""Join the org if not already a member."""
try:
self.flow.new_org_join_request(oid=settings.ORG_ID)
except Flow.FlowError as org_join_err:
LOG.debug("org join failed: '%s'", str(org_join_err))
| from flow import Flow
import logging
from . import settings
LOG = logging.getLogger("flowbot.server")
class Server(object):
"""A connection to Flow."""
def __init__(self):
"""Initialize a flow server instance."""
self.flow = Flow()
self._start_server()
self._setup_account()
self._setup_device()
self._setup_org()
def _start_server(self):
"""Attempt to start the flow server."""
try:
self.flow.start_up(username=settings.USERNAME)
LOG.info("local account '%s' started", settings.USERNAME)
except Flow.FlowError as start_up_err:
LOG.debug("start_up failed: '%s'", str(start_up_err))
def _setup_account(self):
"""Create an account, if it doesn't already exist."""
try:
self.flow.create_account(
username=settings.USERNAME,
password=settings.PASSWORD
)
except Flow.FlowError as create_account_err:
LOG.debug("Create account failed: '%s'", str(create_account_err))
def _setup_device(self):
"""Create a device if it doesn't already exist."""
try:
self.flow.create_device(
username=settings.USERNAME,
password=settings.PASSWORD
)
LOG.info("local Device for '%s' created", settings.USERNAME)
except Flow.FlowError as create_device_err:
LOG.debug("create_device failed: '%s'", str(create_device_err))
def _setup_org(self):
""""Join the org if not already a member."""
try:
self.flow.new_org_join_request(oid=settings.ORG_ID)
except Flow.FlowError as org_join_err:
LOG.debug("org join failed: '%s'", str(org_join_err))
|
Remove trailing slash b/c invite ID has leading one | package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**
* Base API path
*/
public static final String API_BASE_PATH = BASE_URL + "api";
/**
* WebSocket gateway
*/
public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway";
/**
* The endpoint for accessing user information
*/
public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
/**
* The endpoint for logging in
*/
public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
/**
* The endpoint for logging out
*/
public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
/**
* The endpoint for accessing server information
*/
public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
/**
* The endpoint for accessing channel information
*/
public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
/**
* The endpoint for accepting invites
*/
public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
/**
* The format string for avatar URLs
*/
public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";
}
| package co.phoenixlab.discord.api;
/**
* Contains various useful API URLs and paths
*/
public class ApiConst {
/**
* Utility class
*/
private ApiConst() {
}
/**
* The base URL from which Discord runs
*/
public static final String BASE_URL = "https://discordapp.com/";
/**
* Base API path
*/
public static final String API_BASE_PATH = BASE_URL + "api";
/**
* WebSocket gateway
*/
public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway";
/**
* The endpoint for accessing user information
*/
public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
/**
* The endpoint for logging in
*/
public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
/**
* The endpoint for logging out
*/
public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
/**
* The endpoint for accessing server information
*/
public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
/**
* The endpoint for accessing channel information
*/
public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
/**
* The endpoint for accepting invites
*/
public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite/";
/**
* The format string for avatar URLs
*/
public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";
}
|
Remove usage of deprecated "Symfony\Component\Config\Definition\Builder\TreeBuilder::root()" | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
final class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('sylius_admin');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->arrayNode('notifications')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')
->defaultTrue()
->end()
->integerNode('frequency')
->defaultValue(60)
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
final class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder(): TreeBuilder
{
if (method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('sylius_admin');
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sylius_admin');
}
$rootNode
->children()
->arrayNode('notifications')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')
->defaultTrue()
->end()
->integerNode('frequency')
->defaultValue(60)
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
|
Improve (a tiny bit) validation error message | # coding: utf-8
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}` is allowed').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
| # coding: utf-8
from django.utils.translation import ugettext as _
from rest_framework import serializers
from kpi.constants import (
ASSET_TYPE_COLLECTION,
PERM_DISCOVER_ASSET,
PERM_VIEW_ASSET
)
from kpi.fields import RelativePrefixHyperlinkedRelatedField
from kpi.models import Asset
from kpi.models import UserAssetSubscription
from kpi.models.object_permission import get_anonymous_user, get_objects_for_user
class UserAssetSubscriptionSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
lookup_field='uid',
view_name='userassetsubscription-detail'
)
asset = RelativePrefixHyperlinkedRelatedField(
lookup_field='uid',
view_name='asset-detail',
queryset=Asset.objects.none() # will be set in __init__()
)
uid = serializers.ReadOnlyField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['asset'].queryset = get_objects_for_user(
get_anonymous_user(),
[PERM_VIEW_ASSET, PERM_DISCOVER_ASSET],
Asset
)
class Meta:
model = UserAssetSubscription
lookup_field = 'uid'
fields = ('url', 'asset', 'uid')
def validate_asset(self, asset):
if asset.asset_type != ASSET_TYPE_COLLECTION:
raise serializers.ValidationError(
_('Invalid asset type. Only `{asset_type}`').format(
asset_type=ASSET_TYPE_COLLECTION
)
)
return asset
|
Fix typo in follower restrictions | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, api
class MailFollowers(models.Model):
""" Prevent having too much followers in mail threads.
"""
_inherit = 'mail.followers'
@api.model
def _mail_restrict_follower_selection_get_domain(self, model):
parameter_name = 'mail_restrict_follower_selection.domain'
return self.env['ir.config_parameter'].get_param(
'%s.%s' % (parameter_name, model),
self.env['ir.config_parameter'].get_param(
parameter_name, default='[]')
)
@api.model
def create(self, vals):
"""
Remove partners not in domain selection of module
mail_restrict_follower_selection
"""
model = vals['res_model']
res_id = vals['partner_id']
domain = self._mail_restrict_follower_selection_get_domain(model)
allowed = self.env['res.partner'].search(eval(domain))
if allowed and res_id in allowed.ids:
return super(MailFollowers, self).create(vals)
return self
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, api
class MailFollowers(models.Model):
""" Prevent having too much followers in mail threads.
"""
_inherit = 'mail.followers'
@api.model
def _mail_restrict_follower_selection_get_domain(self, model):
parameter_name = 'mail_restrict_follower_selection.domain'
return self.env['ir.config_parameter'].get_param(
'%s.%s' % (parameter_name, model),
self.env['ir.config_parameter'].get_param(
parameter_name, default='[]')
)
@api.model
def create(self, vals):
"""
Remove partners not in domain selection of module
mail_restrict_follower_selection
"""
model = vals['res_model']
res_id = vals['res_id']
domain = self._mail_restrict_follower_selection_get_domain(model)
allowed = self.env['res.partner'].search(eval(domain))
if allowed and res_id in allowed.ids:
return super(MailFollowers, self).create(vals)
return self
|
Include changelog in package registration. Up version. | # -*- encoding: utf8 -*-
from setuptools import setup, find_packages
import os
read = lambda *names: open(os.path.join(os.path.dirname(__file__), *names)).read()
setup(
name="aspectlib",
version="0.8.0",
url='https://github.com/ionelmc/python-aspectlib',
download_url='',
license='BSD',
description="Aspect-Oriented Programming toolkit.",
long_description="%s\n%s" % (read('README.rst'), read('docs', 'changelog.rst').replace(':obj:', '')),
author='Ionel Cristian Mărieș',
author_email='[email protected]',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
keywords=[
'python', 'aop', 'aspects', 'aspect oriented programming', 'decorators', 'patch', 'monkeypatch', 'weave',
'debug', 'log', 'tests', 'mock'
],
install_requires=[
],
extras_require={
}
)
| # -*- encoding: utf8 -*-
from setuptools import setup, find_packages
import os
setup(
name="aspectlib",
version="0.7.0",
url='https://github.com/ionelmc/python-aspectlib',
download_url='',
license='BSD',
description="Aspect-Oriented Programming toolkit.",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author='Ionel Cristian Mărieș',
author_email='[email protected]',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
keywords=[
'python', 'aop', 'aspects', 'aspect oriented programming', 'decorators', 'patch', 'monkeypatch', 'weave',
'debug', 'log', 'tests', 'mock'
],
install_requires=[
],
extras_require={
}
)
|
Stop favorite click from triggering card click | import React from "react";
import actions from "actions";
import stores from "stores";
// images
import filled_star from "images/filled-star-icon.png";
import empty_star from "images/empty-star-icon.png";
export default React.createClass({
displayName: "CommonBookmark",
toggleFavorite: function(e) {
e.stopPropagation();
e.preventDefault();
var image = this.props.image,
imageBookmark = stores.ImageBookmarkStore.findOne({
"image.id": image.id
});
if (imageBookmark) {
actions.ImageBookmarkActions.removeBookmark({
image: image
});
} else {
actions.ImageBookmarkActions.addBookmark({
image: image
});
}
},
render: function() {
var image = this.props.image,
isFavorited = stores.ImageBookmarkStore.findOne({
"image.id": image.id
}),
img;
if (isFavorited) {
img = (
<img src={filled_star} />
);
} else {
img = (
<img src={empty_star} />
);
}
return (
<a className="bookmark" href="#" onClick={this.toggleFavorite}>
{img}
</a>
);
}
});
| import React from "react";
import actions from "actions";
import stores from "stores";
// images
import filled_star from "images/filled-star-icon.png";
import empty_star from "images/empty-star-icon.png";
export default React.createClass({
displayName: "CommonBookmark",
toggleFavorite: function(e) {
e.preventDefault();
var image = this.props.image,
imageBookmark = stores.ImageBookmarkStore.findOne({
"image.id": image.id
});
if (imageBookmark) {
actions.ImageBookmarkActions.removeBookmark({
image: image
});
} else {
actions.ImageBookmarkActions.addBookmark({
image: image
});
}
},
render: function() {
var image = this.props.image,
isFavorited = stores.ImageBookmarkStore.findOne({
"image.id": image.id
}),
img;
if (isFavorited) {
img = (
<img src={filled_star} />
);
} else {
img = (
<img src={empty_star} />
);
}
return (
<a className="bookmark" href="#" onClick={this.toggleFavorite}>
{img}
</a>
);
}
});
|
Check if file exists in array | <?php
class Kwf_Trl_BuildFileMissingException extends Kwf_Exception
{
public function __construct($message = 'trl build file does not exist')
{
parent::__construct($message);
}
public function getSettingsNonStaticTrlException()
{
$exceptionLocation = null;
foreach ($this->getTrace() as $trace) {
if (isset($trace['file']) && strpos($trace['file'], 'Kwf/Trl.php') === false
&& (
$trace['function'] == 'trlKwf' || $trace['function'] == 'trl'
|| $trace['function'] == 'trlcKwf' || $trace['function'] == 'trlc'
|| $trace['function'] == 'trlpKwf' || $trace['function'] == 'trlp'
|| $trace['function'] == 'trlcpKwf' || $trace['function'] == 'trlcp'
)
) {
$exceptionLocation = $trace;
break;
}
}
if ($exceptionLocation) {
$file = $exceptionLocation['file'];
$line = $exceptionLocation['line'];
return new Kwf_Exception("In getSettings-method only static version of trl is allowed $file:$line");
}
return false;
}
}
| <?php
class Kwf_Trl_BuildFileMissingException extends Kwf_Exception
{
public function __construct($message = 'trl build file does not exist')
{
parent::__construct($message);
}
public function getSettingsNonStaticTrlException()
{
$exceptionLocation = null;
foreach ($this->getTrace() as $trace) {
if (strpos($trace['file'], 'Kwf/Trl.php') === false
&& (
$trace['function'] == 'trlKwf' || $trace['function'] == 'trl'
|| $trace['function'] == 'trlcKwf' || $trace['function'] == 'trlc'
|| $trace['function'] == 'trlpKwf' || $trace['function'] == 'trlp'
|| $trace['function'] == 'trlcpKwf' || $trace['function'] == 'trlcp'
)
) {
$exceptionLocation = $trace;
break;
}
}
if ($exceptionLocation) {
$file = $exceptionLocation['file'];
$line = $exceptionLocation['line'];
return new Kwf_Exception("In getSettings-method only static version of trl is allowed $file:$line");
}
return false;
}
}
|
Fix version numbers of libraries. | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_questionparsing_grammatical',
version='0.4.7',
description='Natural language processing module for the PPP.',
url='https://github.com/ProjetPP/PPP-QuestionParsing-Grammatical',
author='Projet Pensées Profondes',
author_email='[email protected]',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'ppp_datamodel>=0.5,<0.7',
'ppp_libmodule>=0.6,<0.8',
'jsonrpclib-pelix',
'nltk'
],
packages=[
'ppp_questionparsing_grammatical',
'ppp_questionparsing_grammatical.data',
],
)
import sys
if 'install' in sys.argv:
import nltk
nltk.download("wordnet")
| #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_questionparsing_grammatical',
version='0.4.7',
description='Natural language processing module for the PPP.',
url='https://github.com/ProjetPP/PPP-QuestionParsing-Grammatical',
author='Projet Pensées Profondes',
author_email='[email protected]',
license='MIT',
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Development Status :: 1 - Planning',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries',
],
install_requires=[
'ppp_datamodel>=0.5,<0.6',
'ppp_libmodule>=0.6,<0.7',
'jsonrpclib-pelix',
'nltk'
],
packages=[
'ppp_questionparsing_grammatical',
'ppp_questionparsing_grammatical.data',
],
)
import sys
if 'install' in sys.argv:
import nltk
nltk.download("wordnet")
|
Improve error message for message listeners consistency rules. | package poussecafe.environment;
public class MessageListeners {
public void include(MessageListener listener) {
MessageListenerType priority = listener.priority();
if(priority == MessageListenerType.FACTORY) {
if(factoryListener == null) {
factoryListener = listener;
} else {
throw new IllegalArgumentException("There is already a factory listener in " + listener.aggregateRootClass().orElseThrow() + " for message " + listener.messageClass().getName());
}
} else if(priority == MessageListenerType.AGGREGATE) {
if(aggregateListener == null) {
aggregateListener = listener;
} else {
throw new IllegalArgumentException("There is already an aggregate listener in " + listener.aggregateRootClass().orElseThrow() + " for message " + listener.messageClass().getName());
}
} else if(priority == MessageListenerType.REPOSITORY) {
if(repositoryListener == null) {
repositoryListener = listener;
} else {
throw new IllegalArgumentException("There is already a repository listener in " + listener.aggregateRootClass().orElseThrow() + " for message " + listener.messageClass().getName());
}
} else {
throw new UnsupportedOperationException("Unsupported priority " + priority);
}
}
private MessageListener factoryListener;
private MessageListener aggregateListener;
private MessageListener repositoryListener;
}
| package poussecafe.environment;
public class MessageListeners {
public void include(MessageListener listener) {
MessageListenerType priority = listener.priority();
if(priority == MessageListenerType.FACTORY) {
if(factoryListener == null) {
factoryListener = listener;
} else {
throw new IllegalArgumentException("There is already a factory listener for message " + listener.messageClass().getName());
}
} else if(priority == MessageListenerType.AGGREGATE) {
if(aggregateListener == null) {
aggregateListener = listener;
} else {
throw new IllegalArgumentException("There is already a aggregate listener for message " + listener.messageClass().getName());
}
} else if(priority == MessageListenerType.REPOSITORY) {
if(repositoryListener == null) {
repositoryListener = listener;
} else {
throw new IllegalArgumentException("There is already a repository listener for message " + listener.messageClass().getName());
}
} else {
throw new UnsupportedOperationException("Unsupported priority " + priority);
}
}
private MessageListener factoryListener;
private MessageListener aggregateListener;
private MessageListener repositoryListener;
}
|
Use os.name to detect OS
This is consistent with the rest of the code. | #!/usr/bin/env python
"""Setup script for MemeGen."""
import os
import logging
import setuptools
from memegen import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + '\n' + CHANGELOG
def load_requirements():
"""Exclude specific requirements based on platform."""
requirements = []
for line in open("requirements.txt").readlines():
line = line.strip()
name = line.split('=')[0].strip()
if os.name == 'nt':
if name in ['psycopg2', 'gunicorn']:
logging.warning("Skipped requirement: %s", line)
continue
requirements.append(line)
return requirements
setuptools.setup(
name=__project__,
version=__version__,
description="The open source meme generator.",
url='https://github.com/jacebrowning/memegen',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=(DESCRIPTION),
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
],
install_requires=load_requirements(),
)
| #!/usr/bin/env python
"""Setup script for MemeGen."""
import sys
import logging
import setuptools
from memegen import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
DESCRIPTION = "<placeholder>"
else:
DESCRIPTION = README + '\n' + CHANGELOG
def load_requirements():
"""Exclude specific requirements based on platform."""
requirements = []
for line in open("requirements.txt").readlines():
name = line.split('=')[0].strip()
if sys.platform == 'win32':
if name in ['psycopg2', 'gunicorn']:
logging.warning("Skipped requirement: %s", line)
continue
requirements.append(line)
return requirements
setuptools.setup(
name=__project__,
version=__version__,
description="The open source meme generator.",
url='https://github.com/jacebrowning/memegen',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=(DESCRIPTION),
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
],
install_requires=load_requirements(),
)
|
Add check for used invites | <?php
namespace mpcmf\modules\authex\controllers;
use mpcmf\modules\authex\mappers\inviteMapper;
use mpcmf\modules\moduleBase\controllers\controllerBase;
use mpcmf\modules\moduleBase\exceptions\mapperException;
use mpcmf\system\helper\io\codes;
use mpcmf\system\pattern\singleton;
/**
* Class inviteController
*
* Invite system
*
*
* @generated by mpcmf/codeManager
*
* @package mpcmf\modules\authex\controllers;
* @date 2015-10-01 12:35:13
*
* @author Dmitry Emelyanov <[email protected]>
*/
class inviteController
extends controllerBase
{
use singleton;
public function _invite($invite)
{
try {
inviteMapper::getInstance()->getBy([
inviteMapper::FIELD__INVITE => $invite,
inviteMapper::FIELD__USED => false,
]);
} catch (mapperException $mapperException) {
$message = $mapperException->getMessage();
if (mb_strpos($message, 'not found') === false) {
return self::error($mapperException->getMessage(), $mapperException->getCode(), codes::RESPONSE_CODE_NOT_FOUND);
}
return self::nothing([]);
}
$this->getSlim()->redirectTo('/authex/user/register', ['invite' => $invite]);
return self::nothing([]);
}
} | <?php
namespace mpcmf\modules\authex\controllers;
use mpcmf\modules\authex\mappers\inviteMapper;
use mpcmf\modules\moduleBase\controllers\controllerBase;
use mpcmf\modules\moduleBase\exceptions\mapperException;
use mpcmf\system\helper\io\codes;
use mpcmf\system\pattern\singleton;
/**
* Class inviteController
*
* Invite system
*
*
* @generated by mpcmf/codeManager
*
* @package mpcmf\modules\authex\controllers;
* @date 2015-10-01 12:35:13
*
* @author Dmitry Emelyanov <[email protected]>
*/
class inviteController
extends controllerBase
{
use singleton;
public function _invite($invite)
{
try {
inviteMapper::getInstance()->getBy([
inviteMapper::FIELD__INVITE => $invite
]);
} catch (mapperException $mapperException) {
$message = $mapperException->getMessage();
if (mb_strpos($message, 'not found') === false) {
return self::error($mapperException->getMessage(), $mapperException->getCode(), codes::RESPONSE_CODE_NOT_FOUND);
}
return self::nothing([]);
}
$this->getSlim()->redirectTo('/authex/user/register', ['invite' => $invite]);
return self::nothing([]);
}
} |
Fix CS failure for docblock line length | <?php
declare(strict_types=1);
namespace PhpSchool\PhpWorkshop\Result;
use PhpSchool\PhpWorkshop\Check\CheckInterface;
/**
* A failure result representing the situation where there were function usage requirements
* and they were not met.
*/
class FunctionRequirementsFailure implements FailureInterface
{
use ResultTrait;
/**
* @var array<array{function: string, line: int}>
*/
private $bannedFunctions;
/**
* @var array<int, string>
*/
private $missingFunctions;
/**
* @param CheckInterface $check The check that produced this result.
* @param array<array{function: string, line: int}> $bannedFunctions Functions that were used, but were banned.
* @param array<int, string> $missingFunctions Functions that were not used, but were required.
*/
public function __construct(CheckInterface $check, array $bannedFunctions, array $missingFunctions)
{
$this->check = $check;
$this->bannedFunctions = $bannedFunctions;
$this->missingFunctions = $missingFunctions;
}
/**
* Get the list of functions that were used, but were banned.
*
* @return array<array{function: string, line: int}>
*/
public function getBannedFunctions(): array
{
return $this->bannedFunctions;
}
/**
* Get the list of functions that were not used, but were required.
*
* @return array<int, string>
*/
public function getMissingFunctions(): array
{
return $this->missingFunctions;
}
}
| <?php
declare(strict_types=1);
namespace PhpSchool\PhpWorkshop\Result;
use PhpSchool\PhpWorkshop\Check\CheckInterface;
/**
* A failure result representing the situation where there were function usage requirements
* and they were not met.
*/
class FunctionRequirementsFailure implements FailureInterface
{
use ResultTrait;
/**
* @var array<array{function: string, line: int}>
*/
private $bannedFunctions;
/**
* @var array<int, string>
*/
private $missingFunctions;
/**
* @param CheckInterface $check The check that produced this result.
* @param array<array{function: string, line: int}> $bannedFunctions A list of functions that were used, but were banned.
* @param array<int, string> $missingFunctions A list of functions that were not used, but were required.
*/
public function __construct(CheckInterface $check, array $bannedFunctions, array $missingFunctions)
{
$this->check = $check;
$this->bannedFunctions = $bannedFunctions;
$this->missingFunctions = $missingFunctions;
}
/**
* Get the list of functions that were used, but were banned.
*
* @return array<array{function: string, line: int}>
*/
public function getBannedFunctions(): array
{
return $this->bannedFunctions;
}
/**
* Get the list of functions that were not used, but were required.
*
* @return array<int, string>
*/
public function getMissingFunctions(): array
{
return $this->missingFunctions;
}
}
|
jf-tooltip-on-overflow: Use the root dir element as the target, not the actual event target. | /*
USAGE EXAMPLE:
<jf-grid-filter
filter-grid="gridOptions" //the name of the grid (grid options)
filter-field="fieldName" //the name of the field that should be filtered
filter-on-change> //optional - don't use a button for filtering, filter on every change
</jf-grid-filter>
*/
export function jfTooltipOnOverflow() {
return {
restrict: 'A',
scope: {
},
link: ($scope, $element) => {
$($element).on('mouseenter',(e)=>{
let target = $($element);
let targetContent = target.text().trim();
if (target[0].scrollWidth > target.innerWidth()) {
if (!target.hasClass('tooltipstered')) {
target.tooltipster({
animation: 'fade',
trigger: 'hover',
onlyOne: 'true',
interactive: 'true',
position: 'bottom',
theme: 'tooltipster-default bottom',
content: targetContent
});
target.tooltipster('show');
}
else {
target.tooltipster('enable');
if (target.tooltipster('content') != targetContent)
target.tooltipster('content', targetContent);
}
}
else if (target.hasClass('tooltipstered'))
target.tooltipster('disable');
});
$scope.$on('$destroy', () => {
$($element).off('mouseenter');
$($element).off('mouseleave');
});
}
};
}
| /*
USAGE EXAMPLE:
<jf-grid-filter
filter-grid="gridOptions" //the name of the grid (grid options)
filter-field="fieldName" //the name of the field that should be filtered
filter-on-change> //optional - don't use a button for filtering, filter on every change
</jf-grid-filter>
*/
export function jfTooltipOnOverflow() {
return {
restrict: 'A',
scope: {
},
link: ($scope, $element) => {
$($element).on('mouseenter',(e)=>{
let target = $(e.target);
let targetContent = target.text().trim();
if (target[0].scrollWidth > target.innerWidth()) {
if (!target.hasClass('tooltipstered')) {
target.tooltipster({
animation: 'fade',
trigger: 'hover',
onlyOne: 'true',
interactive: 'true',
position: 'bottom',
theme: 'tooltipster-default bottom',
content: targetContent
});
target.tooltipster('show');
}
else {
target.tooltipster('enable');
if (target.tooltipster('content') != targetContent)
target.tooltipster('content', targetContent);
}
}
else if (target.hasClass('tooltipstered'))
target.tooltipster('disable');
});
$scope.$on('$destroy', () => {
$($element).off('mouseenter');
$($element).off('mouseleave');
});
}
};
}
|
Add an optional second parameter to cache, used to conditionaly enable/disable caching | <?php namespace Gchaincl\LaravelFragmentCaching;
class ViewServiceProvider extends \Illuminate\View\ViewServiceProvider
{
protected $defered = false;
public function register()
{
parent::register();
$this->registerEnvironment();
$this->registerBladeExtensions();
}
public function registerEnvironment()
{
$this->app->bindShared('view', function($app) {
$resolver = $app['view.engine.resolver'];
$finder = $app['view.finder'];
$env = new Factory($resolver, $finder, $app['events']);
$env->setContainer($app);
$env->share('app', $app);
return $env;
});
}
protected function registerBladeExtensions()
{
$blade = $this->app['view']
->getEngineResolver()
->resolve('blade')
->getCompiler();
$blade->extend(function($view, $compiler) {
$pattern = $compiler->createMatcher('cache');
return preg_replace($pattern, '$1' . $this->cacheTemplate(), $view);
});
$blade->extend(function($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endcache');
return preg_replace($pattern, '$1<?php }); ?>', $view);
});
}
private function cacheTemplate()
{
return <<<'EOF'
<?php
$__fc_vars = get_defined_vars();
echo $__env->cache($2, $3, function() use($__fc_vars) {
extract($__fc_vars);
// Cached Content goes below this
?>
EOF;
}
}
| <?php namespace Gchaincl\LaravelFragmentCaching;
class ViewServiceProvider extends \Illuminate\View\ViewServiceProvider
{
protected $defered = false;
public function register()
{
parent::register();
$this->registerEnvironment();
$this->registerBladeExtensions();
}
public function registerEnvironment()
{
$this->app->bindShared('view', function($app) {
$resolver = $app['view.engine.resolver'];
$finder = $app['view.finder'];
$env = new Factory($resolver, $finder, $app['events']);
$env->setContainer($app);
$env->share('app', $app);
return $env;
});
}
protected function registerBladeExtensions()
{
$blade = $this->app['view']
->getEngineResolver()
->resolve('blade')
->getCompiler();
$blade->extend(function($view, $compiler) {
$pattern = $compiler->createMatcher('cache');
return preg_replace($pattern, '$1' . $this->cacheTemplate(), $view);
});
$blade->extend(function($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endcache');
return preg_replace($pattern, '$1<?php }); ?>', $view);
});
}
private function cacheTemplate()
{
return <<<'EOF'
<?php
$__fc_vars = get_defined_vars();
echo $__env->cache($2, function() use($__fc_vars) {
extract($__fc_vars);
// Cached Content goes below this
?>
EOF;
}
}
|
Fix the error that change page after creating project | (function() {
'use strict';
angular
.module('vmsFrontend')
.controller('CreateProjectController', CreateProjectController);
/** @ngInject */
function CreateProjectController(
$log,
$state,
$translate,
project,
projectHyperlink,
PERMISSION_OPTIONS,
FROALA_OPTIONS
) {
var vm = this;
vm.permissionOptions = PERMISSION_OPTIONS;
vm.froalaOptions = FROALA_OPTIONS;
vm.hyperlinks = [
{
name: '',
link: ''
}
];
vm.create = function() {
vm.alert = [];
project
.create(vm.project)
.then(function(value) {
$log.debug(value);
var projectId = value.id;
storeHyperlinks(projectId);
})
.catch(function(alert) {
vm.alert.push(alert);
});
};
function storeHyperlinks(projectId) {
projectHyperlink
.create(projectId, vm.hyperlinks)
.then(function() {
$log.debug("storeHyperlinks() success");
$log.debug("projectId = " + projectId);
$state.go('projectDetail', {
id: projectId
});
})
.catch(function() {
$log.debug("storeHyperlinks() failure");
})
}
}
})();
| (function() {
'use strict';
angular
.module('vmsFrontend')
.controller('CreateProjectController', CreateProjectController);
/** @ngInject */
function CreateProjectController(
$log,
$state,
$translate,
project,
projectHyperlink,
PERMISSION_OPTIONS,
FROALA_OPTIONS
) {
var vm = this;
vm.permissionOptions = PERMISSION_OPTIONS;
vm.froalaOptions = FROALA_OPTIONS;
vm.hyperlinks = [
{
name: '',
link: ''
}
];
vm.create = function() {
vm.alert = [];
project
.create(vm.project)
.then(function(value) {
$log.debug(value);
var projectId = value.data.id;
storeHyperlinks(projectId);
})
.catch(function(alert) {
vm.alert.push(alert);
});
};
function storeHyperlinks(projectId) {
projectHyperlink
.create(projectId, vm.hyperlinks)
.then(function() {
$log.debug("storeHyperlinks() success");
$log.debug("projectId = " + projectId);
$state.go('projectDetail', {
id: projectId
});
})
.catch(function() {
$log.debug("storeHyperlinks() failure");
})
}
}
})();
|
Add additional property to pass to weatherCard. | import React, {Component} from 'react';
import $ from 'jquery';
import CurrentWeatherCard from './CurrentWeatherCard';
export default class App extends Component {
constructor(){
super()
this.state = {
location:'',
responseData: null,
currentData: null,
forecastData: null,
hourlyData: null,
};
}
handleInput(e) {
this.setState({
location: e.target.value,
})
}
handleSubmit(){
const currentLocation = this.state.location
$.get(`http://api.wunderground.com/api/878e77b9c3411d19/hourly/conditions/forecast10day/q/${currentLocation}.json`).then((data)=> {
this.handleData(data)
})
}
handleData(weatherData){
const keys = Object.keys(weatherData)
this.setState({
location:'',
responseData:weatherData[keys[0]],
currentData:weatherData[keys[1]],
forecastData:weatherData[keys[2]],
hourlyData:weatherData[keys[3]],
})
}
render() {
return (
<div>
<navbar>
<input type="text" value={this.state.location} onChange={this.handleInput.bind(this)}/>
<input type="submit" onClick={this.handleSubmit.bind(this)}/>
</navbar>
<h1 className="welcomeHeader">Weathrly</h1>
<CurrentWeatherCard currentData={this.state.currentData} forecastData={this.state.forecastData}/>
</div>
)
}
}
| import React, {Component} from 'react';
import $ from 'jquery';
import CurrentWeatherCard from './CurrentWeatherCard';
export default class App extends Component {
constructor(){
super()
this.state = {
location:'',
responseData: null,
currentData: null,
forecastData: null,
hourlyData: null,
};
}
handleInput(e) {
this.setState({
location: e.target.value,
})
}
handleSubmit(){
const currentLocation = this.state.location
$.get(`http://api.wunderground.com/api/878e77b9c3411d19/hourly/conditions/forecast10day/q/${currentLocation}.json`).then((data)=> {
this.handleData(data)
})
}
handleData(weatherData){
const keys = Object.keys(weatherData)
this.setState({
location:'',
responseData:weatherData[keys[0]],
currentData:weatherData[keys[1]],
forecastData:weatherData[keys[2]],
hourlyData:weatherData[keys[3]],
})
}
render() {
return (
<div>
<navbar>
<input type="text" value={this.state.location} onChange={this.handleInput.bind(this)}/>
<input type="submit" onClick={this.handleSubmit.bind(this)}/>
</navbar>
<h1 className="welcomeHeader">Weathrly</h1>
<CurrentWeatherCard weatherData={this.state.weatherData}/>
</div>
)
}
}
|
Update RenameFileStorage method to be 1.11 compatible | import hashlib
import itertools
import os
import time
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from storages.backends.s3boto3 import S3Boto3Storage
DjangoStorage = S3Boto3Storage if settings.AWS_ACCESS_KEY_ID else FileSystemStorage
class RenameFileStorage(DjangoStorage):
"""Subclass Django's file system storage to add our file naming
conventions."""
def get_available_name(self, name, max_length=None):
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
# Set file_root to something we like: clean and all ascii
md5_sub = hashlib.md5(file_root.encode('utf8')).hexdigest()[0:6]
file_root = time.strftime('%Y-%m-%d-%H-%M-%S-',
time.localtime()) + md5_sub
name = os.path.join(dir_name, file_root + file_ext)
# If the filename already exists, add an underscore and a number
# (before the file extension, if one exists) to the filename until
# the generated filename doesn't exist.
count = itertools.count(1)
while self.exists(name):
# file_ext includes the dot.
name = os.path.join(dir_name, "%s_%s%s" %
(file_root, count.next(), file_ext))
return name
| import hashlib
import itertools
import os
import time
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from storages.backends.s3boto3 import S3Boto3Storage
DjangoStorage = S3Boto3Storage if settings.AWS_ACCESS_KEY_ID else FileSystemStorage
class RenameFileStorage(DjangoStorage):
"""Subclass Django's file system storage to add our file naming
conventions."""
def get_available_name(self, name):
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
# Set file_root to something we like: clean and all ascii
md5_sub = hashlib.md5(file_root.encode('utf8')).hexdigest()[0:6]
file_root = time.strftime('%Y-%m-%d-%H-%M-%S-',
time.localtime()) + md5_sub
name = os.path.join(dir_name, file_root + file_ext)
# If the filename already exists, add an underscore and a number
# (before the file extension, if one exists) to the filename until
# the generated filename doesn't exist.
count = itertools.count(1)
while self.exists(name):
# file_ext includes the dot.
name = os.path.join(dir_name, "%s_%s%s" %
(file_root, count.next(), file_ext))
return name
|
Fix assistant get key database | function normalizeName (name) {
return capitalizeFirstLetter(name.replace(/\s+/g, ''));
}
function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function uncapitalizeFirstLetter (string) {
return string.charAt(0).toLowerCase() + string.slice(1);
}
function getKeyAndUnit (value) {
let valueId = ' ';
let measureUnit = '';
const val = uncapitalizeFirstLetter(value);
switch (val) {
case 'temperature':
valueId = val;
measureUnit = ' centigrade degrees';
break;
case 'city':
case 'weather':
valueId = val;
break;
case 'humidity':
valueId = val;
measureUnit = ' %';
break;
case 'pressure':
valueId = val;
measureUnit = ' Pa';
break;
case 'sea level pressure':
valueId = 'sealevel_pressure';
measureUnit = ' Pa';
break;
case 'altitude':
valueId = val;
measureUnit = ' m';
break;
case 'wind velocity':
valueId = 'wind_kph';
measureUnit = ' kph';
break;
}
return {
valueId: valueId,
measureUnit: measureUnit
}
}
module.exports = {
normalizeName,
getKeyAndUnit
}; | function normalizeName (name) {
return capitalizeFirstLetter(name.replace(/\s+/g, ''));
}
function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getKeyAndUnit (value) {
let valueId = ' ';
let measureUnit = '';
switch (value) {
case 'temperature':
valueId = value;
measureUnit = ' centigrade degrees';
break;
case 'city':
case 'weather':
valueId = value;
break;
case 'humidity':
valueId = value;
measureUnit = ' %';
break;
case 'pressure':
valueId = value;
measureUnit = ' Pa';
break;
case 'sea level pressure':
valueId = 'sealevel_pressure';
measureUnit = ' Pa';
break;
case 'altitude':
valueId = value;
measureUnit = ' m';
break;
case 'wind velocity':
valueId = 'wind_kph';
measureUnit = ' kph';
break;
}
return {
valueId: valueId,
measureUnit: measureUnit
}
}
module.exports = {
normalizeName,
getKeyAndUnit
}; |
Disable more plugins to make it work again.
Will fix venues parsing later.
Signed-off-by: Ville Valkonen <[email protected]> | # -*- coding: utf-8 -*-
# Execute this file to see what plugins will be loaded.
# Implementation leans to Lex Toumbourou's example:
# https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/
import os
import pkgutil
import sys
from typing import List
from venues.abstract_venue import AbstractVenue
def load_venue_plugins() -> List[AbstractVenue]:
"""
Read plugin directory and load found plugins.
Variable "blocklist" can be used to exclude loading certain plugins.
"""
blocklist = ["plugin_tiketti", "plugin_telakka", "plugin_lutakko", "plugin_yotalo"]
found_blocked = list()
loadedplugins = list()
pluginspathabs = os.path.join(os.path.dirname(__file__), "venues")
for loader, plugname, ispkg in \
pkgutil.iter_modules(path=[pluginspathabs]):
if plugname in sys.modules or plugname == "abstract_venue":
continue
if plugname in blocklist:
found_blocked.append(plugname.lstrip("plugin_"))
continue
plugpath = f"venues.{plugname}"
loadplug = __import__(plugpath, fromlist=[plugname])
classname = plugname.split("_")[1].title()
loadedclass = getattr(loadplug, classname)
instance = loadedclass()
loadedplugins.append(instance)
print(f"Loaded plugin: {instance.get_venue_name()}")
print("Blocked plugins: {}.\n".format(", ".join(found_blocked[1:])))
return loadedplugins
| # -*- coding: utf-8 -*-
# Execute this file to see what plugins will be loaded.
# Implementation leans to Lex Toumbourou's example:
# https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/
import os
import pkgutil
import sys
from typing import List
from venues.abstract_venue import AbstractVenue
def load_venue_plugins() -> List[AbstractVenue]:
"""
Read plugin directory and load found plugins.
Variable "blocklist" can be used to exclude loading certain plugins.
"""
blocklist = ["plugin_tiketti", "plugin_telakka"]
found_blocked = list()
loadedplugins = list()
pluginspathabs = os.path.join(os.path.dirname(__file__), "venues")
for loader, plugname, ispkg in \
pkgutil.iter_modules(path=[pluginspathabs]):
if plugname in sys.modules or plugname == "abstract_venue":
continue
if plugname in blocklist:
found_blocked.append(plugname.lstrip("plugin_"))
continue
plugpath = f"venues.{plugname}"
loadplug = __import__(plugpath, fromlist=[plugname])
classname = plugname.split("_")[1].title()
loadedclass = getattr(loadplug, classname)
instance = loadedclass()
loadedplugins.append(instance)
print(f"Loaded plugin: {instance.get_venue_name()}")
print("Blocked plugins: {}.\n".format(", ".join(found_blocked[1:])))
return loadedplugins
|
Fix typo on apiKey Variable | <?php
namespace Benwilkins\FCM;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;
/**
* Class FcmChannel.
*/
class FcmChannel
{
/**
* @const The API URL for Firebase
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @var string
*/
private $apikey;
/**
* @param Client $client
*/
public function __construct(Client $client, $apiKey)
{
$this->client = $client;
$this->apiKey = $apiKey;
}
/**
* @param mixed $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
/** @var FcmMessage $message */
$message = $notification->toFcm($notifiable);
if (is_null($message->getTo())) {
if (! $to = $notifiable->routeNotificationFor('fcm')) {
return;
}
$message->to($to);
}
$response = $this->client->post(self::API_URI, [
'headers' => [
'Authorization' => 'key='.$this->apiKey,
'Content-Type' => 'application/json',
],
'body' => $message->formatData(),
]);
return \GuzzleHttp\json_decode($response->getBody(), true);
}
}
| <?php
namespace Benwilkins\FCM;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;
/**
* Class FcmChannel.
*/
class FcmChannel
{
/**
* @const The API URL for Firebase
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @var string
*/
private $apikey;
/**
* @param Client $client
*/
public function __construct(Client $client, $apiKey)
{
$this->client = $client;
$this->apiKey = $apiKey;
}
/**
* @param mixed $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
/** @var FcmMessage $message */
$message = $notification->toFcm($notifiable);
if (is_null($message->getTo())) {
if (! $to = $notifiable->routeNotificationFor('fcm')) {
return;
}
$message->to($to);
}
$response = $this->client->post(self::API_URI, [
'headers' => [
'Authorization' => 'key='.$this->apikey,
'Content-Type' => 'application/json',
],
'body' => $message->formatData(),
]);
return \GuzzleHttp\json_decode($response->getBody(), true);
}
}
|
Allow smaller pictures to be declared as valid pictures | <?php
namespace Movim\Task;
use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;
class CheckSmallPicture extends Engine {
private $_client;
public function __construct()
{
$engine = parent::start();
$browser = new Browser($engine->_loop);
$this->_client = $browser->withOptions([
'timeout' => 2
]);
}
public function run($url)
{
return $this->_client->head($url)
->then(function (ResponseInterface $response) {
$length = $response->getHeader('content-length');
$size = 300000;
if($length) {
$length = (int)$length[0];
$type = (string)$response->getHeader('content-type')[0];
$typearr = explode('/', $type);
return ($typearr[0] == 'image'
&& $length <= $size
&& $length >= 5000);
}
return false;
},
function (\Exception $error) {
return false;
})
->always(function() { writeOut(); });
}
}
| <?php
namespace Movim\Task;
use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;
class CheckSmallPicture extends Engine {
private $_client;
public function __construct()
{
$engine = parent::start();
$browser = new Browser($engine->_loop);
$this->_client = $browser->withOptions([
'timeout' => 2
]);
}
public function run($url)
{
return $this->_client->head($url)
->then(function (ResponseInterface $response) {
$length = $response->getHeader('content-length');
$size = 300000;
if($length) {
$length = (int)$length[0];
$type = (string)$response->getHeader('content-type')[0];
$typearr = explode('/', $type);
return ($typearr[0] == 'image'
&& $length <= $size
&& $length >= 10000);
}
return false;
},
function (\Exception $error) {
return false;
})
->always(function() { writeOut(); });
}
}
|
Add custom exception logic to the Directory class
If an empty string was passed to the Directory class, then an exception
needs to be raised as all of its methods assume a value for the path. | """Contains a Directory class to represent real directories"""
from ..base import _BaseFileAndDirectoryInterface
from ..exceptions import InvalidDirectoryValueError
class Directory(_BaseFileAndDirectoryInterface):
"""A class that groups together the (meta)data and behavior of
directories"""
def __init__(self, path):
"""
Construct the object
Parameters:
path -- (str) where the directory is (or will be) located at. An
exception is raised if the path refers to a file, and also if an
empty string is given.
"""
if not path:
# No point in continuing since the methods of this class assume
# that a path will be given upon instantiation.
raise InvalidDirectoryValueError("No directory path was given")
return
# Special Methods
def __repr__(self):
pass
def __str__(self):
pass
# Properties
@property
def name(self):
pass
@property
def path(self):
pass
@property
def exists(self):
pass
@property
def created_on(self):
pass
@property
def size(self):
pass
@property
def parent(self):
pass
@property
def owner(self):
pass
@property
def group(self):
pass
# Regular Methods
def get_parent(self):
pass
def create(self):
pass
def get_permissions(self):
pass
def change_permissions(self):
pass
def chmod(self):
pass
def change_owner(self):
pass
def change_group(self):
pass
def copy(self):
pass
def move(self):
pass
def rename(self):
pass
def remove(self):
pass | """Contains a Directory class to represent real directories"""
from ..base import _BaseFileAndDirectoryInterface
class Directory(_BaseFileAndDirectoryInterface):
"""A class that groups together the (meta)data and behavior of
directories"""
def __init__(self, path):
"""
Construct the object
Parameters:
path -- (str) where the directory is (or will be) located at. An
exception is raised if the path refers to a file, and also if an
empty string is given.
"""
return
# Special Methods
def __repr__(self):
pass
def __str__(self):
pass
# Properties
@property
def name(self):
pass
@property
def path(self):
pass
@property
def exists(self):
pass
@property
def created_on(self):
pass
@property
def size(self):
pass
@property
def parent(self):
pass
@property
def owner(self):
pass
@property
def group(self):
pass
# Regular Methods
def get_parent(self):
pass
def create(self):
pass
def get_permissions(self):
pass
def change_permissions(self):
pass
def chmod(self):
pass
def change_owner(self):
pass
def change_group(self):
pass
def copy(self):
pass
def move(self):
pass
def rename(self):
pass
def remove(self):
pass |
Enable or disable an inline in accordance with the type of article | $(document).ready(function () {
var $id_type = $('#id_type');
$id_type.each(function() {
if($(this).val() == 'p'){
$('[id^="publishedinperiodical"]').parents('._inline-group').show();
$('[id^="publishedinevent"]').parents('._inline-group').hide();
} else if($(this).val() == 'e'){
$('[id^="publishedinperiodical"]').parents('._inline-group').hide();
$('[id^="publishedinevent"]').parents('._inline-group').show();
} else{
$('[id^="publishedinperiodical"]').parents('._inline-group').hide();
$('[id^="publishedinevent"]').parents('._inline-group').hide();
}
});
$id_type.change(function(){
if($(this).val() == 'p'){
$('[id^="publishedinperiodical"]').parents('._inline-group').show();
$('[id^="publishedinevent"]').parents('._inline-group').hide();
} else if($(this).val() == 'e'){
$('[id^="publishedinperiodical"]').parents('._inline-group').hide();
$('[id^="publishedinevent"]').parents('._inline-group').show();
} else{
$('[id^="publishedinperiodical"]').parents('._inline-group').hide();
$('[id^="publishedinevent"]').parents('._inline-group').hide();
}
});
});
| $(document).ready(function () {
var $id_type = $('[id$=type]');
$id_type.each(function() {
if($(this).val() == 'p'){
$('[id$=periodical]').parents('.row').show();
$('[id$=date]').parents('.row').show();
$('[id$=event]').parents('.row').hide();
} else if($(this).val() == 'e'){
$('[id$=event]').parents('.row').show();
$('[id$=periodical]').parents('.row').hide();
$('[id$=date]').parents('.row').hide();
} else{
$('[id$=periodical]').parents('.row').hide();
$('[id$=event]').parents('.row').hide();
$('[id$=date]').parents('.row').hide();
}
});
$id_type.change(function(){
if($(this).val() == 'p'){
$('[id$=periodical]').parents('.row').show();
$('[id$=date]').parents('.row').show();
$('[id$=event]').parents('.row').hide();
} else if($(this).val() == 'e'){
$('[id$=event]').parents('.row').show();
$('[id$=periodical]').parents('.row').hide();
$('[id$=date]').parents('.row').hide();
} else{
$('[id$=periodical]').parents('.row').hide();
$('[id$=event]').parents('.row').hide();
$('[id$=date]').parents('.row').hide();
}
});
});
|
Add ID & HASH in CardController |
// ----------------------------------------------------------------
// Card Class
class CardModel extends SwitchModel {
constructor({
name,
lsKeyView,
triggerSelector,
switchSelector,
hash = null
} = {}) {
super({
name: name,
lsKeyView: lsKeyView,
triggerSelector: triggerSelector,
switchSelector: switchSelector
});
this.NAME = name;
this.HASH = hash;
this.CARD_TBODY = '#card-area tbody';
this.$CARD_TBODY = $(this.CARD_TBODY);
}
}
class CardView extends SwitchView {
constructor(_model = new CardModel()) {
super(_model);
}
}
// ----------------------------------------------------------------
// Controller
class CardController extends CommonController {
constructor(_obj) {
super(_obj);
this.model = new CardModel(_obj);
this.view = new CardView(this.model);
this.ID = null;
this.HASH = null;
}
setUser(_id = null, _hash = null) {
this.ID = _id;
this.HASH = _hash;
}
}
// ----------------------------------------------------------------
// Event
class CardEvent extends CommonEvent {
constructor({
name = 'Card Event'
} = {})
{
super({
name: name
});
this.NAME = name;
this.CONTROLLER = new CardController({
name: 'Card Switch',
lsKeyView: 'card',
triggerSelector: '#action-card',
switchSelector: '#card-area'
});
}
}
|
// ----------------------------------------------------------------
// Card Class
class CardModel extends SwitchModel {
constructor({
name,
lsKeyView,
triggerSelector,
switchSelector,
hash = null
} = {}) {
super({
name: name,
lsKeyView: lsKeyView,
triggerSelector: triggerSelector,
switchSelector: switchSelector
});
this.NAME = name;
this.HASH = hash;
this.CARD_TBODY = '#card-area tbody';
this.$CARD_TBODY = $(this.CARD_TBODY);
}
}
class CardView extends SwitchView {
constructor(_model = new CardModel()) {
super(_model);
}
}
// ----------------------------------------------------------------
// Controller
class CardController extends CommonController {
constructor(_obj) {
super(_obj);
this.model = new CardModel(_obj);
this.view = new CardView(this.model);
}
setUser(_id = null, _hash = null) {
this.ID = _id;
this.HASH = _hash;
}
}
// ----------------------------------------------------------------
// Event
class CardEvent extends CommonEvent {
constructor({
name = 'Card Event'
} = {})
{
super({
name: name
});
this.NAME = name;
this.CONTROLLER = new CardController({
name: 'Card Switch',
lsKeyView: 'card',
triggerSelector: '#action-card',
switchSelector: '#card-area'
});
}
}
|
Add option for spatial correlation | import numpy as np
from scipy.sparse import coo_matrix
from sklearn.base import BaseEstimator
import scipy as sp
class PearsonCorrelation(BaseEstimator):
"""Pearson correlation estimator
"""
def __init__(self, assume_centered=False, spatial=False):
self.assume_centered = assume_centered
self.spatial = spatial
def fit(self, X, y=None, connectivity=None):
""" Compute Pearson correlation coefficient
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training data, where n_samples is the number of samples and
n_features is the number of features.
y : not used, present for API consistence purpose.
Returns
-------
self : object
Returns self.
"""
if connectivity is None:
self.covariance_ = np.corrcoef(X, rowvar=0)
else:
# We suppose connectivity as coo but most of this code would work
# with dense matrix
rows, cols = connectivity.nonzero()
values = np.zeros(rows.shape)
for i, (r, c) in enumerate(zip(rows, cols)):
if self.spatial:
corr = sp.stats.pearsonr(np.dot(X[:, r], X),
np.dot(X[:, c], X))[0]
else:
corr = sp.stats.pearsonr(X[:, r], X[:, c])[0]
if not np.isnan(corr):
values[i] = corr
self.covariance_ = coo_matrix((values, (rows, cols)))
return self
| import numpy as np
from scipy.sparse import coo_matrix
from sklearn.base import BaseEstimator
class PearsonCorrelation(BaseEstimator):
"""Pearson correlation estimator
"""
def __init__(self, assume_centered=False):
self.assume_centered = assume_centered
def fit(self, X, y=None, connectivity=None):
""" Compute Pearson correlation coefficient
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training data, where n_samples is the number of samples and
n_features is the number of features.
y : not used, present for API consistence purpose.
Returns
-------
self : object
Returns self.
"""
if connectivity is None:
self.covariance_ = np.corrcoef(X, rowvar=0)
else:
# We suppose connectivity as coo but most of this code would work
# with dense matrix
rows, cols = connectivity.nonzero()
values = np.zeros(rows.shape)
for i, (r, c) in enumerate(zip(rows, cols)):
corr = np.corrcoef(X[r], X[c])
if not np.isnan(corr):
values[i] = corr
self.covariance_ = coo_matrix((values, (rows, cols)))
return self
|
Update annotations count when setting status from dropdown | import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
class CreateStatusMutation extends Relay.Mutation {
getMutation() {
return Relay.QL`mutation createStatus {
createStatus
}`;
}
getFatQuery() {
var query = '';
switch (this.props.parent_type) {
case 'source':
query = Relay.QL`fragment on CreateStatusPayload { statusEdge, source { annotations, id } }`;
break;
case 'media':
query = Relay.QL`fragment on CreateStatusPayload { statusEdge, media { annotations, id, last_status, annotations_count } }`;
break;
}
return query;
}
getVariables() {
var status = this.props.annotation;
var vars = { status: status.status, annotated_id: status.annotated_id + '', annotated_type: status.annotated_type };
if (Checkdesk.context.project) {
vars.context_type = 'Project';
vars.context_id = Checkdesk.context.project.dbid.toString();
}
return vars;
}
getConfigs() {
var fieldIds = {};
fieldIds[this.props.parent_type] = this.props.annotated.id;
return [
{
type: 'RANGE_ADD',
parentName: this.props.parent_type,
parentID: this.props.annotated.id,
connectionName: 'annotations',
edgeName: 'statusEdge',
rangeBehaviors: {
'': 'prepend'
}
},
{
type: 'FIELDS_CHANGE',
fieldIDs: fieldIds
}
];
}
}
export default CreateStatusMutation;
| import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
class CreateStatusMutation extends Relay.Mutation {
getMutation() {
return Relay.QL`mutation createStatus {
createStatus
}`;
}
getFatQuery() {
var query = '';
switch (this.props.parent_type) {
case 'source':
query = Relay.QL`fragment on CreateStatusPayload { statusEdge, source { annotations, id } }`;
break;
case 'media':
query = Relay.QL`fragment on CreateStatusPayload { statusEdge, media { annotations, id, last_status } }`;
break;
}
return query;
}
getVariables() {
var status = this.props.annotation;
var vars = { status: status.status, annotated_id: status.annotated_id + '', annotated_type: status.annotated_type };
if (Checkdesk.context.project) {
vars.context_type = 'Project';
vars.context_id = Checkdesk.context.project.dbid.toString();
}
return vars;
}
getConfigs() {
var fieldIds = {};
fieldIds[this.props.parent_type] = this.props.annotated.id;
return [
{
type: 'RANGE_ADD',
parentName: this.props.parent_type,
parentID: this.props.annotated.id,
connectionName: 'annotations',
edgeName: 'statusEdge',
rangeBehaviors: {
'': 'prepend'
}
},
{
type: 'FIELDS_CHANGE',
fieldIDs: fieldIds
}
];
}
}
export default CreateStatusMutation;
|
Use github URL and official license name. | from setuptools import setup, find_packages
version = '1.9'
setup(name='jarn.viewdoc',
version=version,
description='Python documentation viewer',
long_description=open('README.rst').read() + '\n' +
open('CHANGES.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='view rest rst package docs rst2html',
author='Stefan H. Holek',
author_email='[email protected]',
url='https://github.com/Jarn/jarn.viewdoc',
license='BSD-2-Clause',
packages=find_packages(),
namespace_packages=['jarn'],
include_package_data=True,
zip_safe=False,
test_suite='jarn.viewdoc.tests',
install_requires=[
'setuptools',
'docutils',
],
entry_points={
'console_scripts': 'viewdoc=jarn.viewdoc.viewdoc:main',
},
)
| from setuptools import setup, find_packages
version = '1.9'
setup(name='jarn.viewdoc',
version=version,
description='Python documentation viewer',
long_description=open('README.rst').read() + '\n' +
open('CHANGES.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='view rest rst package docs rst2html',
author='Stefan H. Holek',
author_email='[email protected]',
url='https://pypi.python.org/pypi/jarn.viewdoc',
license='BSD 2-clause',
packages=find_packages(),
namespace_packages=['jarn'],
include_package_data=True,
zip_safe=False,
test_suite='jarn.viewdoc.tests',
install_requires=[
'setuptools',
'docutils',
],
entry_points={
'console_scripts': 'viewdoc=jarn.viewdoc.viewdoc:main',
},
)
|
Increase coordinate in building fixtures | <?php
namespace AppBundle\DataFixtures\ORM;
use AppBundle\Entity\Building;
use AppBundle\Entity\Category;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadBuildingData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function load(ObjectManager $manager)
{
$countCategories = count($manager->getRepository(Category::class)->findAll());
for ($i = 0; $i < $countCategories; $i++) {
for ($j = 0; $j < 3; $j++) {
$building = new Building();
$building->setStreetName('Street ' . $i); // Count of street is equal to count of category
$building->setBuildingNumber($j); //For 3 buildings per street
$building->setCoordinateX(rand(-10000, 10000));
$building->setCoordinateY(rand(-10000, 10000));
$manager->persist($building);
$manager->flush();
}
}
}
public function getOrder()
{
return 2;
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
} | <?php
namespace AppBundle\DataFixtures\ORM;
use AppBundle\Entity\Building;
use AppBundle\Entity\Category;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadBuildingData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function load(ObjectManager $manager)
{
$countCategories = count($manager->getRepository(Category::class)->findAll());
for ($i = 0; $i < $countCategories; $i++) {
for ($j = 0; $j < 3; $j++) {
$building = new Building();
$building->setStreetName('Street ' . $i); // Count of street is equal to count of category
$building->setBuildingNumber($j); //For 3 buildings per street
$building->setCoordinateX(rand(-1000, 1000));
$building->setCoordinateY(rand(-1000, 1000));
$manager->persist($building);
$manager->flush();
}
}
}
public function getOrder()
{
return 2;
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
} |
Fix issue identified by Psalm | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\TextUI\XmlConfiguration;
use function sprintf;
use PHPUnit\Util\Exception as UtilException;
use PHPUnit\Util\Xml;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class Migrator
{
/**
* @throws MigrationBuilderException
* @throws MigrationException
* @throws Exception
* @throws UtilException
*/
public function migrate(string $filename): string
{
$oldXsdFilename = (new SchemaFinder)->find('9.2');
$configurationDocument = Xml::loadFile(
$filename,
false,
true,
true
);
$validationResult = Xml::validate($configurationDocument, $oldXsdFilename);
if ($validationResult->hasValidationErrors()) {
throw new Exception(
sprintf(
'"%s" is not a valid PHPUnit 9.2 XML configuration file:%s',
$filename,
$validationResult->asString()
)
);
}
foreach ((new MigrationBuilder)->build('9.2') as $migration) {
$migration->migrate($configurationDocument);
}
$configurationDocument->formatOutput = true;
$configurationDocument->preserveWhiteSpace = false;
return $configurationDocument->saveXML();
}
}
| <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\TextUI\XmlConfiguration;
use function sprintf;
use PHPUnit\Util\Xml;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class Migrator
{
/**
* @throws MigrationBuilderException
* @throws MigrationException
* @throws Exception
* @throws \PHPUnit\Framework\Exception
*/
public function migrate(string $filename): string
{
$oldXsdFilename = (new SchemaFinder)->find('9.2');
$configurationDocument = Xml::loadFile(
$filename,
false,
true,
true
);
$validationResult = Xml::validate($configurationDocument, $oldXsdFilename);
if ($validationResult->hasValidationErrors()) {
throw new Exception(
sprintf(
'"%s" is not a valid PHPUnit 9.2 XML configuration file:%s',
$filename,
$validationResult->asString()
)
);
}
foreach ((new MigrationBuilder)->build('9.2') as $migration) {
$migration->migrate($configurationDocument);
}
$configurationDocument->formatOutput = true;
$configurationDocument->preserveWhiteSpace = false;
return $configurationDocument->saveXML();
}
}
|
Fix warning on module not found for moment locale | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: path.resolve(__dirname, 'app/Resources/assets/js/app.js')
},
output: {
path: path.resolve(__dirname, 'web/builds'),
filename: 'bundle.js',
publicPath: '/builds/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: 'babel-loader'
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
use: "url-loader"
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
resolve: {
alias: {
fonts: path.resolve(__dirname, 'web/fonts'),
jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'),
moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js')
}
}
};
| const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: path.resolve(__dirname, 'app/Resources/assets/js/app.js')
},
output: {
path: path.resolve(__dirname, 'web/builds'),
filename: 'bundle.js',
publicPath: '/builds/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: 'babel-loader'
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
use: "url-loader"
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
}),
],
resolve: {
alias: {
fonts: path.resolve(__dirname, 'web/fonts'),
jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'),
moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js')
}
}
};
|
Remove any tooltip on pane change
(there is no JS event triggered that would remove the tooltip when the action comes from Android) | // created to start cleaning up "window" interaction
//
window.show = function(id) {
window.hideall();
if (typeof android !== 'undefined' && android && android.switchToPane) {
android.switchToPane(id);
}
switch(id) {
case 'full':
window.chat.show('full');
break;
case 'compact':
window.chat.show('compact');
break;
case 'public':
window.chat.show('public');
break;
case 'faction':
window.chat.show('faction');
break;
case 'debug':
window.debug.console.show();
break;
case 'map':
window.smartphone.mapButton.click();
$('#portal_highlight_select').show();
$('#farm_level_select').show();
break;
case 'info':
window.smartphone.sideButton.click();
break;
default:
window.smartphone.mapButton.click();
break;
}
}
window.hideall = function() {
$('#chatcontrols, #chat, #chatinput, #sidebartoggle, #scrollwrapper, #updatestatus, #portal_highlight_select').hide();
$('#farm_level_select').hide();
$('#map').css('visibility', 'hidden');
$('.ui-tooltip').remove();
}
| // created to start cleaning up "window" interaction
//
window.show = function(id) {
window.hideall();
if (typeof android !== 'undefined' && android && android.switchToPane) {
android.switchToPane(id);
}
switch(id) {
case 'full':
window.chat.show('full');
break;
case 'compact':
window.chat.show('compact');
break;
case 'public':
window.chat.show('public');
break;
case 'faction':
window.chat.show('faction');
break;
case 'debug':
window.debug.console.show();
break;
case 'map':
window.smartphone.mapButton.click();
$('#portal_highlight_select').show();
$('#farm_level_select').show();
break;
case 'info':
window.smartphone.sideButton.click();
break;
default:
window.smartphone.mapButton.click();
break;
}
}
window.hideall = function() {
$('#chatcontrols, #chat, #chatinput, #sidebartoggle, #scrollwrapper, #updatestatus, #portal_highlight_select').hide();
$('#farm_level_select').hide();
$('#map').css('visibility', 'hidden');
}
|
Fix code climate style issues | var AjaxErrorMessageObj = function() {
this.$flash = $('#ajax-error-message');
this.$flash_text = $('#ajax-error-message-text');
this.$flash_close = $('#ajax-error-message > .ajax-error-dismiss');
this.init();
};
AjaxErrorMessageObj.prototype = {
init: function() {
this.$flash_close
.off('click')
.on('click', this.on_close_click.bind(this));
},
display: function(text) {
if (text) {
this.set_text(text);
} else {
this.set_default_text();
}
this.show();
},
on_close_click: function(e) {
e.preventDefault();
this.hide();
},
set_text: function(text) {
this.$flash_text.text(text);
},
set_default_text: function() {
this.$flash_text.text(
'Something went wrong with that request. Please try again.'
);
},
show: function() {
this.$flash.addClass('visible');
},
hide: function() {
this.$flash.removeClass('visible');
}
};
$(document).on('ready page:load', function() {
window.AjaxErrorMessage = new AjaxErrorMessageObj();
});
| AjaxErrorMessageObj = function() {
this.$flash = $('#ajax-error-message');
this.$flash_text = $('#ajax-error-message-text');
this.$flash_close = $('#ajax-error-message > .ajax-error-dismiss');
this.init();
}
AjaxErrorMessageObj.prototype = {
init: function() {
this.$flash_close
.off('click')
.on('click', this.on_close_click.bind(this));
},
display: function(text) {
if (text) {
this.set_text(text);
} else {
this.set_default_text();
}
this.show();
},
on_close_click: function(e) {
e.preventDefault();
this.hide();
},
set_text: function(text) {
this.$flash_text.text(text);
},
set_default_text: function() {
this.$flash_text.text(
'Something went wrong with that request. Please try again.'
);
},
show: function() {
this.$flash.addClass('visible');
},
hide: function() {
this.$flash.removeClass('visible');
}
}
$(document).on('ready page:load', function() {
window.AjaxErrorMessage = new AjaxErrorMessageObj;
});
|
Undo accidental restriction of test suite | var should = require('should');
var webdriverio = require('webdriverio');
var selenium = require('selenium-standalone');
var fs = require('fs');
var path = require('path');
var client = webdriverio.remote({
logLevel: 'command',
desiredCapabilities: {
browserName: 'phantomjs'
}
});
describe('Clientside validation', function() {
this.timeout(30000);
before(function(done){
selenium.install(
{
logger: function (message) {
console.log(message);
}
},
function (err) {
if (err) return done(err);
selenium.start(function() {
done();
});
}
);
});
it('should display a summary of errors when submitting an incomplete form', function(done) {
client
.init()
.url('http://localhost:3000/components/elements/land-registry/clientside-form-validation/demo/')
.setValue('#full-name', 'WebdriverIO')
.click('#submit')
.element('.error-summary')
.call(done);
// .screenshot()
// .then(function(data) {
// var binaryData = new Buffer(data.value, 'base64').toString('binary');
// fs.writeFileSync(path.join(process.cwd(), '/.tmp/screenshot.png'), binaryData, 'binary');
// })
});
after(function(done) {
done();
});
});
| var should = require('should');
var webdriverio = require('webdriverio');
var selenium = require('selenium-standalone');
var fs = require('fs');
var path = require('path');
var client = webdriverio.remote({
logLevel: 'command',
desiredCapabilities: {
browserName: 'phantomjs'
}
});
describe.only('Clientside validation', function() {
this.timeout(30000);
before(function(done){
selenium.install(
{
logger: function (message) {
console.log(message);
}
},
function (err) {
if (err) return done(err);
selenium.start(function() {
done();
});
}
);
});
it('should display a summary of errors when submitting an incomplete form', function(done) {
client
.init()
.url('http://localhost:3000/components/elements/land-registry/clientside-form-validation/demo/')
.setValue('#full-name', 'WebdriverIO')
.click('#submit')
.element('.error-summary')
.call(done);
// .screenshot()
// .then(function(data) {
// var binaryData = new Buffer(data.value, 'base64').toString('binary');
// fs.writeFileSync(path.join(process.cwd(), '/.tmp/screenshot.png'), binaryData, 'binary');
// })
});
after(function(done) {
done();
});
});
|
Install requires pytest 3.6 or greater | import os
import io
from setuptools import setup, find_packages
cwd = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(cwd, 'README.rst'), encoding='utf-8') as fd:
long_description = fd.read()
setup(
name='pytest-tornado',
version='0.5.0',
description=('A py.test plugin providing fixtures and markers '
'to simplify testing of asynchronous tornado applications.'),
long_description=long_description,
url='https://github.com/eugeniy/pytest-tornado',
author='Eugeniy Kalinin',
author_email='[email protected]',
maintainer='Vidar Tonaas Fauske',
maintainer_email='[email protected]',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development',
'Topic :: Software Development :: Testing',
],
keywords=('pytest py.test tornado async asynchronous '
'testing unit tests plugin'),
packages=find_packages(exclude=["tests.*", "tests"]),
install_requires=['pytest>=3.6', 'tornado>=4'],
entry_points={
'pytest11': ['tornado = pytest_tornado.plugin'],
},
)
| import os
import io
from setuptools import setup, find_packages
cwd = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(cwd, 'README.rst'), encoding='utf-8') as fd:
long_description = fd.read()
setup(
name='pytest-tornado',
version='0.5.0',
description=('A py.test plugin providing fixtures and markers '
'to simplify testing of asynchronous tornado applications.'),
long_description=long_description,
url='https://github.com/eugeniy/pytest-tornado',
author='Eugeniy Kalinin',
author_email='[email protected]',
maintainer='Vidar Tonaas Fauske',
maintainer_email='[email protected]',
license='Apache License, Version 2.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development',
'Topic :: Software Development :: Testing',
],
keywords=('pytest py.test tornado async asynchronous '
'testing unit tests plugin'),
packages=find_packages(exclude=["tests.*", "tests"]),
install_requires=['pytest', 'tornado>=4'],
entry_points={
'pytest11': ['tornado = pytest_tornado.plugin'],
},
)
|
:hammer: Fix for a source-map warning | const path = require('path');
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "public/")
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "awesome-typescript-loader"
},
{
test: /\.js$/,
use: "source-map-loader",
exclude: /node_modules/,
enforce: "pre"
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/,
use: 'url-loader'
}
]
}
};
| const path = require('path');
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "public/")
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "awesome-typescript-loader"
},
{
test: /\.js$/,
use: "source-map-loader",
enforce: "pre"
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/,
use: 'url-loader'
}
]
}
};
|
Convert results to a string before printing | #!/usr/bin/env python
import argparse
import sys
import logging
import elasticsearch
import elasticsearch.helpers
ES_NODES = 'uct2-es-door.mwt2.org'
VERSION = '0.1'
SOURCE_INDEX = '.kibana'
TARGET_INDEX = 'osg-connect-kibana'
def get_es_client():
""" Instantiate DB client and pass connection back """
return elasticsearch.Elasticsearch(hosts=ES_NODES,
retry_on_timeout=True,
max_retries=10,
timeout=300)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Reindex events from ' +
'.kibana ' +
'to osg-connect-kibana')
args = parser.parse_args(sys.argv[1:])
client = get_es_client()
results = elasticsearch.helpers.reindex(client,
SOURCE_INDEX,
TARGET_INDEX,
scroll='30m')
sys.stdout.write(str(results))
| #!/usr/bin/env python
import argparse
import sys
import logging
import elasticsearch
import elasticsearch.helpers
ES_NODES = 'uct2-es-door.mwt2.org'
VERSION = '0.1'
SOURCE_INDEX = '.kibana'
TARGET_INDEX = 'osg-connect-kibana'
def get_es_client():
""" Instantiate DB client and pass connection back """
return elasticsearch.Elasticsearch(hosts=ES_NODES,
retry_on_timeout=True,
max_retries=10,
timeout=300)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Reindex events from ' +
'.kibana ' +
'to osg-connect-kibana')
args = parser.parse_args(sys.argv[1:])
client = get_es_client()
results = elasticsearch.helpers.reindex(client,
SOURCE_INDEX,
TARGET_INDEX,
scroll='30m')
sys.stdout.write(results)
|
Comment has incorrect indentation level 8, expected is 0, indentation should be the same level as line 11. [CommentsIndentation] | package pl.grzeslowski.jsupla.server.ents;
import pl.grzeslowski.jsupla.server.SuplaChannel;
public abstract class SuplaConnection<T> {
private final T t;
private final SuplaChannel channel;
public SuplaConnection(final T t, final SuplaChannel channel) {
// TODO
// this.request = requireNonNull(request);
// this.channel = requireNonNull(channel);
this.t = t;
this.channel = channel;
}
public T value() {
return t;
}
public SuplaChannel getChannel() {
return channel;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SuplaConnection)) {
return false;
}
final SuplaConnection<?> that = (SuplaConnection<?>) o;
if (!t.equals(that.t)) return false;
return getChannel().equals(that.getChannel());
}
@Override
public int hashCode() {
int result = t.hashCode();
result = 31 * result + getChannel().hashCode();
return result;
}
@Override
public String toString() {
return "SuplaConnection{" +
"t=" + t +
", channel=" + channel +
'}';
}
}
| package pl.grzeslowski.jsupla.server.ents;
import pl.grzeslowski.jsupla.server.SuplaChannel;
public abstract class SuplaConnection<T> {
private final T t;
private final SuplaChannel channel;
public SuplaConnection(final T t, final SuplaChannel channel) {
// TODO
// this.request = requireNonNull(request);
// this.channel = requireNonNull(channel);
this.t = t;
this.channel = channel;
}
public T value() {
return t;
}
public SuplaChannel getChannel() {
return channel;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SuplaConnection)) {
return false;
}
final SuplaConnection<?> that = (SuplaConnection<?>) o;
if (!t.equals(that.t)) return false;
return getChannel().equals(that.getChannel());
}
@Override
public int hashCode() {
int result = t.hashCode();
result = 31 * result + getChannel().hashCode();
return result;
}
@Override
public String toString() {
return "SuplaConnection{" +
"t=" + t +
", channel=" + channel +
'}';
}
}
|
Allow newer requests. Still to try out and find any issues. | from setuptools import setup, find_packages
from ckanext.qa import __version__
setup(
name='ckanext-qa',
version=__version__,
description='Quality Assurance plugin for CKAN',
long_description='',
classifiers=[],
keywords='',
author='Open Knowledge Foundation',
author_email='[email protected]',
url='http://ckan.org/wiki/Extensions',
license='mit',
packages=find_packages(exclude=['tests']),
namespace_packages=['ckanext', 'ckanext.qa'],
include_package_data=True,
zip_safe=False,
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests>=1.1.0',
'python-magic==0.4.6',
'xlrd>=0.8.0',
'messytables>=0.8',
],
tests_require=[
'nose',
'mock',
],
entry_points='''
[paste.paster_command]
qa=ckanext.qa.commands:QACommand
[ckan.plugins]
qa=ckanext.qa.plugin:QAPlugin
[ckan.celery_task]
tasks=ckanext.qa.celery_import:task_imports
''',
)
| from setuptools import setup, find_packages
from ckanext.qa import __version__
setup(
name='ckanext-qa',
version=__version__,
description='Quality Assurance plugin for CKAN',
long_description='',
classifiers=[],
keywords='',
author='Open Knowledge Foundation',
author_email='[email protected]',
url='http://ckan.org/wiki/Extensions',
license='mit',
packages=find_packages(exclude=['tests']),
namespace_packages=['ckanext', 'ckanext.qa'],
include_package_data=True,
zip_safe=False,
install_requires=[
'celery==2.4.2',
'kombu==2.1.3',
'kombu-sqlalchemy==1.1.0',
'SQLAlchemy>=0.6.6',
'requests==1.1.0',
'python-magic==0.4.6',
'xlrd>=0.8.0',
'messytables>=0.8',
],
tests_require=[
'nose',
'mock',
],
entry_points='''
[paste.paster_command]
qa=ckanext.qa.commands:QACommand
[ckan.plugins]
qa=ckanext.qa.plugin:QAPlugin
[ckan.celery_task]
tasks=ckanext.qa.celery_import:task_imports
''',
)
|
Update blog admin index page | @extends('templates.base')
@section('title')
Blog Admin
@stop
@section('body')
<h1>Blog Admin</h1>
<a href="{{ action('BlogAdminController@getPost') }}"><h4>Create post</h4></a>
<h4>Posts</h4>
<div class="col-md-8 col-lg-6">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Title <small>Click to edit</small></th>
<th>Date</th>
<th>Status</th>
<th>Link</th>
</tr>
@foreach($posts as $post)
<tr>
<td>{{{ $post->id }}}</td>
<td><a href="{{ action('BlogAdminController@getPost', array($post->id)) }}">{{{ $post->title }}}</a></td>
<td>{{{ $post->created_at }}}</td>
<td>{{{ $post->deleted ? 'Hidden' : 'Visible' }}}</td>
<td>@if (!$post->deleted)
<a href="{{ action('BlogController@getPost', array($post->id)) }}">View</a>
@endif </td>
</tr>
@endforeach
</table>
</div>
@stop | @extends('templates.base')
@section('title')
Blog Admin
@stop
@section('body')
<h1>Blog Admin</h1>
<a href="{{ action('BlogAdminController@getPost') }}"><h4>Create post</h4></a>
<h4>Posts</h4>
<div class="col-md-8 col-lg-6">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Title <small>Click to edit</small></th>
<th>Date</th>
<th>Status</th>
<th>Link</th>
</tr>
@foreach($posts as $post)
<tr>
<td>{{{ $post->id }}}</td>
<td><a href="{{ action('BlogAdminController@getPost', array($post->id)) }}">{{{ $post->title }}}</a></td>
<td>{{{ $post->created_at }}}</td>
<td>{{{ $post->deleted ? 'Hidden' : 'Visible' }}}</td>
<td>@if (!$post->deleted)
<a href="{{ action('BlogController@getPost', array($post->id)) }}">View</a>
@endif</td>
</tr>
@endforeach
</table>
</div>
@stop |
Print a quit message when shutting down a bot | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_with_port.split(":")[1])
self.startBotFactory(server, port, channels)
GlobalVars.bothandler = self
reactor.run()
def startBotFactory(self, server, port, channels):
if server in self.botfactories:
print "Already on server '{}'.".format(server)
return False
print "Joining server '{}'.".format(server)
botfactory = HubbotFactory(server, port, channels)
self.botfactories[server] = botfactory
return True
def stopBotFactory(self, server, quitmessage="ohok"):
quitmessage = quitmessage.encode("utf-8")
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
print "Shutting down bot for server '{}'".format(server)
self.botfactories[server].protocol.quit(quitmessage)
self.unregisterFactory(server)
def unregisterFactory(self, server):
if server in self.botfactories:
del self.botfactories[server]
if len(self.botfactories)==0:
print "No more running bots, shutting down."
reactor.callLater(2.0, reactor.stop)
if __name__=="__main__":
bothandler = BotHandler()
| from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_with_port.split(":")[1])
self.startBotFactory(server, port, channels)
GlobalVars.bothandler = self
reactor.run()
def startBotFactory(self, server, port, channels):
if server in self.botfactories:
print "Already on server '{}'.".format(server)
return False
print "Joining server '{}'.".format(server)
botfactory = HubbotFactory(server, port, channels)
self.botfactories[server] = botfactory
return True
def stopBotFactory(self, server, quitmessage="ohok"):
quitmessage = quitmessage.encode("utf-8")
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
self.botfactories[server].protocol.quit(quitmessage)
self.unregisterFactory(server)
def unregisterFactory(self, server):
if server in self.botfactories:
del self.botfactories[server]
if len(self.botfactories)==0:
print "No more running bots, shutting down."
reactor.callLater(2.0, reactor.stop)
if __name__=="__main__":
bothandler = BotHandler()
|
Installation: Enable the routing bundles to your kernel | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Doctrine\Bundle\PHPCRBundle\DoctrinePHPCRBundle(),
new Acme\BasicCmsBundle\AcmeBasicCmsBundle(),
new Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(),
new Symfony\Cmf\Bundle\RoutingAutoBundle\CmfRoutingAutoBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Doctrine\Bundle\PHPCRBundle\DoctrinePHPCRBundle(),
new Acme\BasicCmsBundle\AcmeBasicCmsBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Fix tests issues with namespaces changes |
function runTests(testType, BABYLON, GUI, INSPECTOR) {
console.log("running tests");
describe(testType + ' module tests', function () {
it("should have the dependencies loaded", function () {
assert.isDefined(BABYLON, "BABYLON should be defined");
assert.isDefined(GUI, "GUI should be defined");
assert.isDefined(INSPECTOR, "INSPECTOR should be defined");
// GLTF2 has migrated to BABYLON
// assert.isDefined(BABYLON.GLTF2, "BABYLON.GLTF2 should be defined");
})
var subject;
/**
* Create a nu engine subject before each test.
*/
beforeEach(function () {
subject = new BABYLON.NullEngine({
renderHeight: 256,
renderWidth: 256,
textureSize: 256,
deterministicLockstep: false,
lockstepMaxSteps: 1
});
});
/**
* This test is more an integration test than a regular unit test but highlights how to rely
* on the BABYLON.NullEngine in order to create complex test cases.
*/
describe('#GLTF', function () {
it('should load BoomBox GLTF', function (done) {
mocha.timeout(10000);
var scene = new BABYLON.Scene(subject);
BABYLON.SceneLoader.Append("/Playground/scenes/BoomBox/", "BoomBox.gltf", scene, function () {
scene.meshes.length.should.be.equal(2);
scene.materials.length.should.be.equal(1);
scene.multiMaterials.length.should.be.equal(0);
done();
});
});
});
});
} |
function runTests(testType, BABYLON, GUI, INSPECTOR) {
console.log("running tests");
describe(testType + ' module tests', function () {
it("should have the dependencies loaded", function () {
assert.isDefined(BABYLON);
assert.isDefined(GUI);
assert.isDefined(INSPECTOR);
assert.isDefined(BABYLON.GLTF2);
})
var subject;
/**
* Create a nu engine subject before each test.
*/
beforeEach(function () {
subject = new BABYLON.NullEngine({
renderHeight: 256,
renderWidth: 256,
textureSize: 256,
deterministicLockstep: false,
lockstepMaxSteps: 1
});
});
/**
* This test is more an integration test than a regular unit test but highlights how to rely
* on the BABYLON.NullEngine in order to create complex test cases.
*/
describe('#GLTF', function () {
it('should load BoomBox GLTF', function (done) {
mocha.timeout(10000);
var scene = new BABYLON.Scene(subject);
BABYLON.SceneLoader.Append("/Playground/scenes/BoomBox/", "BoomBox.gltf", scene, function () {
scene.meshes.length.should.be.equal(2);
scene.materials.length.should.be.equal(1);
scene.multiMaterials.length.should.be.equal(0);
done();
});
});
});
});
} |
Fix issue with post with no tag | import needle from 'needle';
import { SiteConf, getDate } from 'base';
export const postsApiHandler = (req, res) => {
needle('get', SiteConf.PostsApi)
.then(resp => {
const data = resp.body;
const filter = req.params.filter;
const pagination = data.meta.pagination;
const posts = PostList(data.posts, filter);
const result = { posts, pagination };
res.json(result);
})
.catch(err => {
console.log(333, err);
res.status(500).json(err);
});
};
export const PostList = (posts, filter) => {
return posts.filter((post) => {
const reg = new RegExp(`^(.+?)${ SiteConf.postOpeningSplitChar }`);
const result = reg.exec(post.html);
if (result) post.opening = result[1];
else {
let i = 0;
let max = SiteConf.postOpeningChars;
const words = post.html.split(' ');
post.opening = '';
for (i; i <= max ; i++) {
post.opening += `${words[i]} `;
}
post.opening += '...</p>';
}
post.html = null;
post.markdown = null;
post.published_at = getDate(post.published_at);
if (filter) {
if (post.tags[0] && post.tags[0].slug === filter.split(':')[1]) return post;
else return false;
}
else return post;
}
);
};
| import needle from 'needle';
import { SiteConf, getDate } from 'base';
export const postsApiHandler = (req, res) => {
needle('get', SiteConf.PostsApi)
.then(resp => {
const data = resp.body;
const filter = req.params.filter;
const pagination = data.meta.pagination;
const posts = PostList(data.posts, filter);
const result = { posts, pagination };
res.json(result);
})
.catch(err => {
console.log(333, err);
res.status(500).json(err);
});
};
export const PostList = (posts, filter) => {
return posts.filter((post) => {
const reg = new RegExp(`^(.+?)${ SiteConf.postOpeningSplitChar }`);
const result = reg.exec(post.html);
if (result) post.opening = result[1];
else {
let i = 0;
let max = SiteConf.postOpeningChars;
const words = post.html.split(' ');
post.opening = '';
for (i; i <= max ; i++) {
post.opening += `${words[i]} `;
}
post.opening += '...</p>';
}
post.html = null;
post.markdown = null;
post.published_at = getDate(post.published_at);
if (filter && post.tags[0]) {
if (post.tags[0].slug === filter.split(':')[1]) return post;
else return false;
}
else return post;
}
);
};
|
Fix undefined XHR state on reload success |
function adminHandleFieldType(e) {
if (ADMIN_FIELD_TIMEOUT)
clearTimeout(ADMIN_FIELD_TIMEOUT);
ADMIN_FIELD_TIMEOUT = setTimeout(function () {
$(e.target).trigger({
type: 'change',
_typing: true
});
}, 200);
}
function adminHandlePaneStep(e, name) {
name = $(e.target).closest('[data-pane]').attr('data-pane');
if (e.target.name == 'step-ok')
paneGoto(name, ADMIN_PANES[name].last);
else if (e.target.name == 'step-prev' && ADMIN_PANES[name].active > 1)
paneGoto(name, ADMIN_PANES[name].active - 1);
else if (e.target.name == 'step-next' && ADMIN_PANES[name].active < ADMIN_PANES[name].count)
paneGoto(name, ADMIN_PANES[name].active + 1);
}
function adminReloadServer() {
ADMIN_RELOAD_TIMEOUT = setTimeout(function () {
overlayCreate('loader', {
message: $.t('main.mesg_server_loading')
});
}, 500);
return $.ajax({
url: urlPrefix + '/reload',
type: 'GET'
}).always(function (xhr) {
if (ADMIN_RELOAD_TIMEOUT)
clearTimeout(ADMIN_RELOAD_TIMEOUT);
overlayDestroy('loader');
if (!xhr)
window.location.reload(true);
});
}
|
function adminHandleFieldType(e) {
if (ADMIN_FIELD_TIMEOUT)
clearTimeout(ADMIN_FIELD_TIMEOUT);
ADMIN_FIELD_TIMEOUT = setTimeout(function () {
$(e.target).trigger({
type: 'change',
_typing: true
});
}, 200);
}
function adminHandlePaneStep(e, name) {
name = $(e.target).closest('[data-pane]').attr('data-pane');
if (e.target.name == 'step-ok')
paneGoto(name, ADMIN_PANES[name].last);
else if (e.target.name == 'step-prev' && ADMIN_PANES[name].active > 1)
paneGoto(name, ADMIN_PANES[name].active - 1);
else if (e.target.name == 'step-next' && ADMIN_PANES[name].active < ADMIN_PANES[name].count)
paneGoto(name, ADMIN_PANES[name].active + 1);
}
function adminReloadServer() {
ADMIN_RELOAD_TIMEOUT = setTimeout(function () {
overlayCreate('loader', {
message: $.t('main.mesg_server_loading')
});
}, 500);
return $.ajax({
url: urlPrefix + '/reload',
type: 'GET'
}).always(function ($deferred) {
if (ADMIN_RELOAD_TIMEOUT)
clearTimeout(ADMIN_RELOAD_TIMEOUT);
overlayDestroy('loader');
if ($deferred.state() == "resolved")
window.location.reload(true);
});
}
|
Update CloVal to allow for specifying multiple parameters | from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
|
Fix Radio: Use find, select does not return all inputs.
getValue didn't work | var $ = require('jQuery');
var fieldRegistry = require('kwf/frontend-form/field-registry');
var Field = require('kwf/frontend-form/field/field');
var kwfExtend = require('kwf/extend');
var Radio = kwfExtend(Field, {
initField: function() {
this.el.find('input').each((function(index, input) {
$(input).on('click', (function() {
this.el.trigger('kwfUp-form-change', this.getValue());
}).bind(this));
}).bind(this));
},
getValue: function() {
var ret = null;
this.el.find('input').each(function(index, input) {
if (input.checked) {
ret = input.value;
}
});
return ret;
},
clearValue: function() {
this.el.select('input').each(function(index, input) {
input.checked = false;
});
},
setValue: function(value) {
this.el.select('input').each(function(index, input) {
if (input.value == value) {
input.checked = true;
} else {
input.checked = false;
}
});
}
});
fieldRegistry.register('kwfFormFieldRadio', Radio);
module.exports = Radio;
| var $ = require('jQuery');
var fieldRegistry = require('kwf/frontend-form/field-registry');
var Field = require('kwf/frontend-form/field/field');
var kwfExtend = require('kwf/extend');
var Radio = kwfExtend(Field, {
initField: function() {
this.el.find('input').each((function(index, input) {
$(input).on('click', (function() {
this.el.trigger('kwfUp-form-change', this.getValue());
}).bind(this));
}).bind(this));
},
getValue: function() {
var ret = null;
this.el.select('input').each(function(index, input) {
if (input.checked) {
ret = input.value;
}
});
return ret;
},
clearValue: function() {
this.el.select('input').each(function(index, input) {
input.checked = false;
});
},
setValue: function(value) {
this.el.select('input').each(function(index, input) {
if (input.value == value) {
input.checked = true;
} else {
input.checked = false;
}
});
}
});
fieldRegistry.register('kwfFormFieldRadio', Radio);
module.exports = Radio;
|
Fix some of the !mdn bugs | <?php
namespace Ciarand\PhilipPlugin;
use Philip\AbstractPlugin as BasePlugin;
use Philip\IRC\Response;
use Guzzle\Http\Client;
class MdnPlugin extends BasePlugin
{
public function init()
{
$client = new Client("http://www.google.com");
$endpoint = "/search?btnI&q=site:developer.mozilla.org+";
$this->bot->onChannel(
"/^!mdn (.*)$/",
function ($event) use ($client, $endpoint) {
$source = $event->getRequest()->getSource();
$caller = $event->getRequest()->getSendingUser();
list($query) = $event->getMatches();
$link = $client
// We only want a head request
->head($url = ($endpoint . urlencode($query)))
// Send it
->send()
// Grab the URL
->getEffectiveUrl();
if ($url === $link) {
$message = "{$caller}: No results found";
} else {
$message = "{$caller}: {$link}";
}
$event->addResponse(Response::msg($source, $message));
}
);
}
public function getName()
{
return "MdnPlugin";
}
}
| <?php
namespace Ciarand\PhilipPlugin;
use Philip\AbstractPlugin as BasePlugin;
use Philip\IRC\Response;
use Guzzle\Http\Client;
class MdnPlugin extends BasePlugin
{
protected $guzzleClient;
public function init()
{
$client = new Client("http://www.google.com");
$endpoint = "/search?btnI&q=mdn+";
$this->bot->onChannel(
"/^!mdn (.*)$/",
function ($event) use ($client, $endpoint) {
$source = $event->getRequest()->getSource();
list($query) = $event->getMatches();
$message = $client
// We only want a head request
->head($endpoint . urlencode($query))
// Send it
->send()
// Grab the URL
->getEffectiveUrl();
$event->addResponse(Response::msg($source, $message));
}
);
}
public function getName()
{
return "MdnPlugin";
}
}
|
Fix error messages in get_fans | import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError(
'shape must be tuple. Actual type: {}'.format(type(shape)))
if len(shape) < 2:
raise ValueError(
'shape must be of length >= 2. Actual shape: {}'.format(shape))
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
| import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError('shape must be tuple')
if len(shape) < 2:
raise ValueError('shape must be of length >= 2: shape={}', shape)
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
|
Move team guard check to the actual use case | <?php namespace Mpociot\Teamwork\Traits;
/**
* This file is part of Teamwork
*
* @license MIT
* @package Teamwork
*/
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
/**
* Class UsedByTeams
* @package Mpociot\Teamwork\Traits
*/
trait UsedByTeams
{
/**
* Boot the global scope
*/
protected static function bootUsedByTeams()
{
static::addGlobalScope('team', function (Builder $builder) {
static::teamGuard();
$builder->where($builder->getQuery()->from . '.team_id', auth()->user()->currentTeam->getKey());
});
static::saving(function (Model $model) {
if (!isset($model->team_id)) {
static::teamGuard();
$model->team_id = auth()->user()->currentTeam->getKey();
}
});
}
/**
* @param Builder $query
* @return mixed
*/
public function scopeAllTeams(Builder $query)
{
return $query->withoutGlobalScope('team');
}
/**
* @return mixed
*/
public function team()
{
return $this->belongsTo(Config::get('teamwork.team_model'));
}
/**
* @throws Exception
*/
protected static function teamGuard()
{
if (auth()->guest() || !auth()->user()->currentTeam) {
throw new Exception('No authenticated user with selected team present.');
}
}
}
| <?php namespace Mpociot\Teamwork\Traits;
/**
* This file is part of Teamwork
*
* @license MIT
* @package Teamwork
*/
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
/**
* Class UsedByTeams
* @package Mpociot\Teamwork\Traits
*/
trait UsedByTeams
{
/**
* Boot the global scope
*/
protected static function bootUsedByTeams()
{
static::addGlobalScope('team', function (Builder $builder) {
static::teamGuard();
$builder->where($builder->getQuery()->from . '.team_id', auth()->user()->currentTeam->getKey());
});
static::saving(function (Model $model) {
static::teamGuard();
if (!isset($model->team_id)) {
$model->team_id = auth()->user()->currentTeam->getKey();
}
});
}
/**
* @param Builder $query
* @return mixed
*/
public function scopeAllTeams(Builder $query)
{
return $query->withoutGlobalScope('team');
}
/**
* @return mixed
*/
public function team()
{
return $this->belongsTo(Config::get('teamwork.team_model'));
}
/**
* @throws Exception
*/
protected static function teamGuard()
{
if (auth()->guest() || !auth()->user()->currentTeam) {
throw new Exception('No authenticated user with selected team present.');
}
}
}
|
Add url rewrite for if a product is added below a grouped product | <?php
class GroupedProduct_CatalogueProduct extends DataExtension {
private static $has_one = array(
"ProductGroup" => "Product"
);
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab(
"Root.Settings",
DropdownField::create(
"ProductGroupID",
_t("GroupedProduct.AddToGroup", "Add this product to a group"),
Product::get()
->filter("ClassName", "GroupedProduct")
->map()
)->setEmptyString(_t("GroupedProduct.SelectProduct", "Select a Product"))
);
// If this is a child product, remove some fields we don't need
if($this->owner->ProductGroupID) {
$fields->removeByName("Content");
$fields->removeByName("Metadata");
$fields->removeByName("Related");
$fields->removeByName("Categories");
$fields->removeByName("TaxRate");
}
}
public function onBeforeWrite() {
if($this->owner->ProductGroupID) {
$group = $this->owner->ProductGroup();
// Set the URL for this product to include the parent URL
$this->owner->URLSegment = $group->URLSegment . "-" . Convert::raw2url($this->owner->Title);
// Set the base price
if(!$this->owner->BasePrice)
$this->owner->BasePrice = $group->BasePrice;
}
}
}
| <?php
class GroupedProduct_CatalogueProduct extends DataExtension {
private static $has_one = array(
"ProductGroup" => "Product"
);
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab(
"Root.Settings",
DropdownField::create(
"ProductGroupID",
_t("GroupedProduct.AddToGroup", "Add this product to a group"),
Product::get()
->filter("ClassName", "GroupedProduct")
->map()
)->setEmptyString(_t("GroupedProduct.SelectProduct", "Select a Product"))
);
// If this is a child product, remove some fields we don't need
if($this->owner->ProductGroupID) {
$fields->removeByName("Content");
$fields->removeByName("Metadata");
$fields->removeByName("Related");
$fields->removeByName("Categories");
$fields->removeByName("TaxRate");
}
}
public function onBeforeWrite() {
if($this->owner->ProductGroupID && !$this->owner->BasePrice)
$this->owner->BasePrice = $this->owner->ProductGroup()->BasePrice;
}
}
|
Add some more placeholder text. | @extends('layouts.default')
@section('title')
Contact · Indiana Real Estate Exchangors, Inc.
@stop
@section('content')
<div class="content-block">
{{ Form::open(array('url' => 'contact')) }}
<dl class="form">
<dt class="input-label">
<label for="name">Name:</label>
</dt>
<dd >
<input type="text" name="contact[name]" id="name" autofocus placeholder="Your Name"/>
</dd>
<dt class="input-label">
<label for="email">E-Mail:</label>
</dt>
<dd>
<input type="email" name="contact[email]" id="email" required placeholder="[email protected]" />
</dd>
<dt class="input-label">
<label for="subject">Subject:</label>
</dt>
<dd>
<input type="text" name="contact[subject]" id="subject" placeholder="Subject of Contact Request (Can be left blank)." />
</dd>
<dt class="input-label">
<label for="comments">Body:</label>
</dt>
<dd>
<textarea name="contact[comments]" id="comments" required placeholder="Details about your contact request."></textarea>
</dd>
</dl>
<div class="form-actions">
<input type="reset" value="Clear"> <input type="submit" value="Submit">
</div>
{{ Form::close() }}
</div>
@stop
| @extends('layouts.default')
@section('title')
Contact · Indiana Real Estate Exchangors, Inc.
@stop
@section('content')
<div class="content-block">
{{ Form::open(array('url' => 'contact')) }}
<dl class="form">
<dt class="input-label">
<label for="name">Name:</label>
</dt>
<dd >
<input type="text" name="contact[name]" id="name" autofocus />
</dd>
<dt class="input-label">
<label for="email">E-Mail:</label>
</dt>
<dd>
<input type="email" name="contact[email]" id="email" required placeholder="[email protected]" />
</dd>
<dt class="input-label">
<label for="subject">Subject:</label>
</dt>
<dd>
<input type="text" name="contact[subject]" id="subject" />
</dd>
<dt class="input-label">
<label for="comments">Body:</label>
</dt>
<dd>
<textarea name="contact[comments]" id="comments" required></textarea>
</dd>
</dl>
<div class="form-actions">
<input type="reset" value="Clear"> <input type="submit" value="Submit">
</div>
{{ Form::close() }}
</div>
@stop
|
Stop grabbing password when there is no username | """Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
| """Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
Make AllTests.php without any checkstyle error | <?php
/**
* AllTests file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeTestLoader', 'TestSuite');
/**
* AllTests class
*
* This test group will run all tests.
*
* @package Cake.Test.Case
*/
class AllTests extends PHPUnit_Framework_TestSuite
{
/**
* Suite define the tests for this suite
*/
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('All Tests');
$path = TESTS . 'Case' . DS;
$config['app'] = 1;
$tests = CakeTestLoader::generateTestList($config);
foreach ($tests as $test) {
if ($test != 'AllTests') {
$suite->addTestFile($path . $test . 'Test.php');
}
}
return $suite;
}
}
| <?php
/**
* AllTests file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeTestLoader', 'TestSuite');
/**
* AllTests class
*
* This test group will run all tests.
*
* @package Cake.Test.Case
*/
class AllTests extends PHPUnit_Framework_TestSuite {
/**
* Suite define the tests for this suite
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Tests');
$path = TESTS . 'Case' . DS;
$config['app'] = 1;
$tests = CakeTestLoader::generateTestList($config);
foreach ($tests as $test) {
if ($test != 'AllTests') {
$suite->addTestFile($path . $test . 'Test.php');
}
}
return $suite;
}
}
|
Use csync groups when doing a global update. | <?php
class SV_Csync2StreamWrapper_CsyncConfig
{
public function __construct()
{
//setlocale(LC_CTYPE, "en_US.UTF-8");
//$this->debug_log
//$this->csync_database = "/var/lib/csync2";
}
public $deferred_count = 0;
public $deferred_commit_bulk = false;
public $deferred_paths = array();
public $deferred_files = array();
public $csync2_binary = "/usr/sbin/csync2";
public $csync_database = ""; //= "/var/lib/csync2";
public $debug_mode = false;
public $debug_log = "";// = "/var/www/html/error.log";
public $csync_groups = array('www_code', 'www_data', 'www_templates');
public $www_code = 'www_code';
public $www_data = 'www_data';
public $www_templates = 'www_templates';
protected $_installed = false;
public function isInstalled()
{
return $this->_installed;
}
public function setInstalled($_installed)
{
$this->_installed = $_installed;
}
protected static $_instance;
public static function getInstance()
{
if (!self::$_instance)
{
self::$_instance = new self();
}
return self::$_instance;
}
} | <?php
class SV_Csync2StreamWrapper_CsyncConfig
{
public function __construct()
{
//setlocale(LC_CTYPE, "en_US.UTF-8");
//$this->debug_log
//$this->csync_database = "/var/lib/csync2";
}
public $deferred_count = 0;
public $deferred_commit_bulk = false;
public $deferred_paths = array();
public $deferred_files = array();
public $csync2_binary = "/usr/sbin/csync2";
public $csync_database = ""; //= "/var/lib/csync2";
public $debug_mode = false;
public $debug_log = "";// = "/var/www/html/error.log";
public $csync_groups = array();
public $www_code = 'www_code';
public $www_data = 'www_data';
public $www_templates = 'www_templates';
protected $_installed = false;
public function isInstalled()
{
return $this->_installed;
}
public function setInstalled($_installed)
{
$this->_installed = $_installed;
}
protected static $_instance;
public static function getInstance()
{
if (!self::$_instance)
{
self::$_instance = new self();
}
return self::$_instance;
}
} |
Return default full block bounding box for blocks that don't have one | package com.elmakers.mine.bukkit.utility.platform.modern;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
import org.bukkit.util.VoxelShape;
import com.elmakers.mine.bukkit.utility.BoundingBox;
import com.elmakers.mine.bukkit.utility.platform.Platform;
public class ModernCompatibilityUtils extends com.elmakers.mine.bukkit.utility.platform.v1_16.CompatibilityUtils {
public ModernCompatibilityUtils(Platform platform) {
super(platform);
}
@Override
public Collection<BoundingBox> getBoundingBoxes(Block block) {
VoxelShape voxelShape = block.getCollisionShape();
Collection<org.bukkit.util.BoundingBox> boxes = voxelShape.getBoundingBoxes();
if (boxes.isEmpty()) {
return super.getBoundingBoxes(block);
}
List<BoundingBox> converted = new ArrayList<>(boxes.size());
Vector center = block.getLocation().toVector();
for (org.bukkit.util.BoundingBox bukkitBB : boxes) {
converted.add(new BoundingBox(center,
bukkitBB.getMinX(), bukkitBB.getMaxX(),
bukkitBB.getMinY(), bukkitBB.getMaxY(),
bukkitBB.getMinZ(), bukkitBB.getMaxZ())
);
}
return converted;
}
}
| package com.elmakers.mine.bukkit.utility.platform.modern;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
import org.bukkit.util.VoxelShape;
import com.elmakers.mine.bukkit.utility.BoundingBox;
import com.elmakers.mine.bukkit.utility.platform.Platform;
public class ModernCompatibilityUtils extends com.elmakers.mine.bukkit.utility.platform.v1_16.CompatibilityUtils {
public ModernCompatibilityUtils(Platform platform) {
super(platform);
}
@Override
public Collection<BoundingBox> getBoundingBoxes(Block block) {
VoxelShape voxelShape = block.getCollisionShape();
Collection<org.bukkit.util.BoundingBox> boxes = voxelShape.getBoundingBoxes();
List<BoundingBox> converted = new ArrayList<>(boxes.size());
Vector center = block.getLocation().toVector();
for (org.bukkit.util.BoundingBox bukkitBB : boxes) {
converted.add(new BoundingBox(center,
bukkitBB.getMinX(), bukkitBB.getMaxX(),
bukkitBB.getMinY(), bukkitBB.getMaxY(),
bukkitBB.getMinZ(), bukkitBB.getMaxZ())
);
}
return converted;
}
}
|
Remove dependency on JQuery for binding/triggering hashchange/pushstate events | /**
* model/fancy/location.js
*/
function changePathGen (method) {
return function changePath(path) {
root.history[method + 'State'](EMPTY_OBJECT, '', path);
window.dispatchEvent(new root.Event(method + 'state'));
};
}
models.location = baseModel.extend({
/**
* Example:
* var loc = tbone.models.location.make();
* T(function () {
* console.log('the hash is ' + loc('hash'));
* });
* loc('hash', '#this-is-the-new-hash');
*/
initialize: function initialize() {
var self = this;
var recentlyChanged;
function update (ev) {
var changed = self('hash') !== location.hash ||
self('search') !== location.search ||
self('pathname') !== location.pathname;
if (changed) {
self('hash', location.hash);
self('pathname', location.pathname);
self('search', location.search);
recentlyChanged = true;
}
}
window.addEventListener('hashchange', update);
window.addEventListener('popstate', update);
window.addEventListener('pushstate', update);
window.addEventListener('replacestate', update);
update();
autorun(function initializeAutorun() {
var pathname = self('pathname');
var search = self('search');
var hash = self('hash');
if (!recentlyChanged) {
self.pushPath(pathname + (search || '') + (hash ? '#' + hash : ''));
}
recentlyChanged = false;
});
},
pushPath: changePathGen('push'),
replacePath: changePathGen('replace')
});
| /**
* model/fancy/location.js
*/
function changePathGen (method) {
return function changePath(path) {
root.history[method + 'State'](EMPTY_OBJECT, '', path);
$(root).trigger(method + 'state');
};
}
models.location = baseModel.extend({
/**
* Example:
* var loc = tbone.models.location.make();
* T(function () {
* console.log('the hash is ' + loc('hash'));
* });
* loc('hash', '#this-is-the-new-hash');
*/
initialize: function initialize() {
var self = this;
var recentlyChanged;
function update (ev) {
var changed = self('hash') !== location.hash ||
self('search') !== location.search ||
self('pathname') !== location.pathname;
if (changed) {
self('hash', location.hash);
self('pathname', location.pathname);
self('search', location.search);
recentlyChanged = true;
}
}
$(root).bind('hashchange popstate pushstate replacestate', update);
update();
autorun(function initializeAutorun() {
var pathname = self('pathname');
var search = self('search');
var hash = self('hash');
if (!recentlyChanged) {
self.pushPath(pathname + (search || '') + (hash ? '#' + hash : ''));
}
recentlyChanged = false;
});
},
pushPath: changePathGen('push'),
replacePath: changePathGen('replace')
});
|
Fix default value if plugin is not configured | const suffixToRemove = 'Container';
function addDisplayNameStatement(t, varName) {
const pos = varName.indexOf(suffixToRemove);
const displayName = 0 < pos ? varName.substring(0, pos) : varName;
// <VAR>.displayName = '<VAR>';
return t.expressionStatement( //
t.assignmentExpression('=', //
t.memberExpression(t.identifier(varName), t.identifier('displayName')), // <VAR>.displayName
t.stringLiteral(displayName)));
}
export default function build({types: t}) {
return {
visitor: {
VariableDeclaration(path, state) {
if (1 === path.node.declarations.length) {
const declarator = path.node.declarations[0];
if (t.isIdentifier(declarator.id)) {
const varName = declarator.id.name;
const initExpression = declarator.init;
const {methodName = 'reactStamp'} = state.opts;
if (methodName && t.isCallExpression(initExpression)) {
let callee = initExpression.callee;
if (t.isMemberExpression(initExpression.callee)) {
callee = callee.object.callee;
}
if (callee && methodName === callee.name) {
const statementPath = t.isExportNamedDeclaration(path.parentPath) ? path.parentPath : path;
statementPath.insertAfter(addDisplayNameStatement(t, varName));
}
}
}
}
}
}
};
}
| const suffixToRemove = 'Container';
function addDisplayNameStatement(t, varName) {
const pos = varName.indexOf(suffixToRemove);
const displayName = 0 < pos ? varName.substring(0, pos) : varName;
// <VAR>.displayName = '<VAR>';
return t.expressionStatement( //
t.assignmentExpression('=', //
t.memberExpression(t.identifier(varName), t.identifier('displayName')), // <VAR>.displayName
t.stringLiteral(displayName)));
}
export default function build({types: t}) {
return {
visitor: {
VariableDeclaration(path, state) {
if (1 === path.node.declarations.length) {
const declarator = path.node.declarations[0];
if (t.isIdentifier(declarator.id)) {
const varName = declarator.id.name;
const initExpression = declarator.init;
const {methodName} = state.opts;
if (t.isCallExpression(initExpression)) {
let callee = initExpression.callee;
if (t.isMemberExpression(initExpression.callee)) {
callee = callee.object.callee;
}
if (callee && methodName === callee.name) {
const statementPath = t.isExportNamedDeclaration(path.parentPath) ? path.parentPath : path;
statementPath.insertAfter(addDisplayNameStatement(t, varName));
}
}
}
}
}
}
};
}
|
Add more detail to unmarshalling errors | package com.dottydingo.hyperion.service.marshall;
import com.dottydingo.hyperion.exception.BadRequestException;
import com.dottydingo.hyperion.exception.InternalException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.io.OutputStream;
/**
*/
public class EndpointMarshaller
{
private ObjectMapper objectMapper;
public EndpointMarshaller()
{
try
{
objectMapper = new ObjectMapperBuilder().getObject();
}
catch (Exception ignore){}
}
public void setObjectMapper(ObjectMapper objectMapper)
{
this.objectMapper = objectMapper;
}
public <T> T unmarshall(InputStream inputStream, Class<T> type)
{
try
{
return objectMapper.readValue(inputStream,type);
}
catch (Exception e)
{
throw new BadRequestException(String.format("Error unmarshalling request: %s",e.getMessage()),e);
}
}
public <T> void marshall(OutputStream outputStream, T value)
{
try
{
objectMapper.writeValue(outputStream,value);
}
catch(Exception e)
{
throw new InternalException("Error marhsalling response.",e);
}
}
}
| package com.dottydingo.hyperion.service.marshall;
import com.dottydingo.hyperion.exception.BadRequestException;
import com.dottydingo.hyperion.exception.InternalException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.io.OutputStream;
/**
*/
public class EndpointMarshaller
{
private ObjectMapper objectMapper;
public EndpointMarshaller()
{
try
{
objectMapper = new ObjectMapperBuilder().getObject();
}
catch (Exception ignore){}
}
public void setObjectMapper(ObjectMapper objectMapper)
{
this.objectMapper = objectMapper;
}
public <T> T unmarshall(InputStream inputStream, Class<T> type)
{
try
{
return objectMapper.readValue(inputStream,type);
}
catch (Exception e)
{
throw new BadRequestException("Error unmarshalling request.",e);
}
}
public <T> void marshall(OutputStream outputStream, T value)
{
try
{
objectMapper.writeValue(outputStream,value);
}
catch(Exception e)
{
throw new InternalException("Error marhsalling response.",e);
}
}
}
|
Make the AppStore an app again (visible in the app store)
We are doing this as the appstore will become the new appshare home page | function listApps(args) {
/*
is_app(true)
created_timestamp(-1)
base_component_id("listApps")
display_name("App Store")
description('App to list all the apps')
load_once_from_file(true)
*/
Vue.component('list_apps',{
template: `<div >
<div class="card-columns">
<div class="card" style="width: 20rem;" v-for="item in apps">
<img v-if='item.logo_url'
v-bind:src='item.logo_url'
style='width: 100%;'
v-on:click='document.location="/?goto=" + item.display_name + "&time=" + new Date().getTime();return false;'
></img>
<div class="card-body">
<h4 class="card-title">{{item.display_name}}</h4>
<p class="card-text"></p>
<a v-bind:href='"/?goto=" + item.display_name + "&time=" + new Date().getTime()' class="btn btn-primary">Run</a>
</div>
</div>
</div>
</div>`,
data: function() {
return {
apps: []
}},
mounted: function() {
this.search()
},
methods: {
search: async function() {
this.apps = await callApp({ driver_name: "systemFunctions", method_name:"get_apps_list"}, { }) }
}
})
return {name: "list_apps"}
}
| function listApps(args) {
/*
created_timestamp(-1)
base_component_id("listApps")
display_name("App Store")
description('App to list all the apps')
load_once_from_file(true)
*/
Vue.component('list_apps',{
template: `<div >
<div class="card-columns">
<div class="card" style="width: 20rem;" v-for="item in apps">
<img v-if='item.logo_url'
v-bind:src='item.logo_url'
style='width: 100%;'
v-on:click='document.location="/?goto=" + item.display_name + "&time=" + new Date().getTime();return false;'
></img>
<div class="card-body">
<h4 class="card-title">{{item.display_name}}</h4>
<p class="card-text"></p>
<a v-bind:href='"/?goto=" + item.display_name + "&time=" + new Date().getTime()' class="btn btn-primary">Run</a>
</div>
</div>
</div>
</div>`,
data: function() {
return {
apps: []
}},
mounted: function() {
this.search()
},
methods: {
search: async function() {
this.apps = await callApp({ driver_name: "systemFunctions", method_name:"get_apps_list"}, { }) }
}
})
return {name: "list_apps"}
}
|
Remove unused import because Travis is picky | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
from framework.tasks.utils import logged
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
|
Update test codes to fit test target. | package net.folab.fo.jast;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AstWriterTest {
private AstWriter writer;
@Before
public void setUp() throws Exception {
writer = new AstWriter();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSetName() throws InstantiationException, IllegalAccessException {
Class<?> generatedClass;
byte[] bytecode;
String name;
Object obj;
// - - -
name = "MainClass";
new ClassDeclaration(name).accept(writer);
bytecode = writer.toByteArray();
generatedClass = defineClass(name, bytecode);
assertThat(generatedClass.getName(), is(name));
obj = generatedClass.newInstance();
assertThat(obj, is(not(nullValue())));
// - - -
name = "foo.MainClass";
writer = new AstWriter();
new ClassDeclaration(name).accept(writer);
bytecode = writer.toByteArray();
generatedClass = defineClass(name, bytecode);
assertThat(generatedClass.getName(), is(name));
obj = generatedClass.newInstance();
assertThat(obj, is(not(nullValue())));
}
public static Class<?> defineClass(String name, byte[] bytecode) {
return new ByteArrayClassLoader().defineClass(name, bytecode);
}
}
| package net.folab.fo.jast;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstVisitor;
import net.folab.fo.jast.AstWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AstWriterTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSetName() throws InstantiationException, IllegalAccessException {
AstVisitor av;
Class<?> generatedClass;
byte[] bytecode;
String name;
Object obj;
// - - -
name = "MainClass";
av = new AstWriter();
new ClassDeclaration(name).accept(av);
bytecode = av.toByteArray();
generatedClass = defineClass(name, bytecode);
assertThat(generatedClass.getName(), is(name));
obj = generatedClass.newInstance();
assertThat(obj, is(not(nullValue())));
// - - -
name = "foo.MainClass";
av = new AstWriter();
new ClassDeclaration(name).accept(av);
bytecode = av.toByteArray();
generatedClass = defineClass(name, bytecode);
assertThat(generatedClass.getName(), is(name));
obj = generatedClass.newInstance();
assertThat(obj, is(not(nullValue())));
}
public static Class<?> defineClass(String name, byte[] bytecode) {
return new ByteArrayClassLoader().defineClass(name, bytecode);
}
}
|
Remove unneeded debug cod
e | """Provide a class to load and parse the help file and
Provide a simple interface for retrieving help entries"""
import json
import os
class HelpManager(object):
_help_dict = {}
_last_modified = 0
@staticmethod
def get_help(lang, key):
""" Retrieve a given commands help text with given language.
:param lang: ISO 639-1 language code specifying language to try to retrieve
:param key: name of the command
:return: description in `lang` for `key`
"""
if os.path.getmtime('help.json') > HelpManager._last_modified:
HelpManager.load_help()
lang = lang.lower()
key = key.lower()
if lang not in HelpManager._help_dict:
print(f"[ERROR] tried to access `_help_dict[{lang}]`")
lang = 'en'
if key not in HelpManager._help_dict[lang]:
print(f"[ERROR] tried to access `_help_dict[{lang}][{key}]`")
return None
return HelpManager._help_dict[lang][key]
@staticmethod
def load_help():
try:
with open('help.json', 'r', encoding='utf-8') as infile:
HelpManager._help_dict = json.load(infile)
HelpManager._last_modified = os.path.getmtime('help.json')
except OSError as ex:
print("[ERROR] Cannot find `help.json`")
print(ex)
| """Provide a class to load and parse the help file and
Provide a simple interface for retrieving help entries"""
import json
import os
class HelpManager(object):
_help_dict = {}
_last_modified = 0
@staticmethod
def get_help(lang, key):
""" Retrieve a given commands help text with given language.
:param lang: ISO 639-1 language code specifying language to try to retrieve
:param key: name of the command
:return: description in `lang` for `key`
"""
if os.path.getmtime('help.json') > HelpManager._last_modified:
HelpManager.load_help()
lang = lang.lower()
key = key.lower()
if lang not in HelpManager._help_dict:
print(f"[ERROR] tried to access `_help_dict[{lang}]`")
lang = 'en'
if key not in HelpManager._help_dict[lang]:
print(f"[ERROR] tried to access `_help_dict[{lang}][{key}]`")
return None
return HelpManager._help_dict[lang][key]
@staticmethod
def load_help():
try:
with open('help.json', 'r', encoding='utf-8') as infile:
HelpManager._help_dict = json.load(infile)
HelpManager._last_modified = os.path.getmtime('help.json')
except OSError as ex:
print("[ERROR] Cannot find `help.json`")
print(ex)
print(HelpManager._help_dict)
|
Fix firefox Date.parse() problem with iso dates | 'use strict';
angular.module('stockApp')
.factory('bitcoinData', function ($http, YAHOO_API, BITCOIN_CSV) {
var bitcoinData = {
yql: function () {
var query = 'select * from csv where url = "' + BITCOIN_CSV + '"';
// yql config
var FORMAT = 'json';
var ENV = 'store://datatables.org/alltableswithkeys';
return $http.get(YAHOO_API + '?q=' + query + '&format=' + FORMAT + '&env=' + ENV);
},
get: function () {
return this.yql().then(function (yql) {
var array = [];
var i = 0;
angular.forEach(yql.data.query.results.row, function (value) {
if (i++ > 0) {
var date = new Date(value.col0.replace(/-/g, '/')).getTime();
var price = parseFloat(value.col3);
this.push([date, price]);
}
}, array);
var serie = {
name: 'Bitcoin in USD',
color: '#A80000',
data: array,
tooltip: {
valueDecimals: 2
}
};
return serie;
});
}
};
return bitcoinData;
});
| 'use strict';
angular.module('stockApp')
.factory('bitcoinData', function ($http, YAHOO_API, BITCOIN_CSV) {
var bitcoinData = {
yql: function () {
var query = 'select * from csv where url = "' + BITCOIN_CSV + '"';
// yql config
var FORMAT = 'json';
var ENV = 'store://datatables.org/alltableswithkeys';
return $http.get(YAHOO_API + '?q=' + query + '&format=' + FORMAT + '&env=' + ENV);
},
get: function () {
return this.yql().then(function (yql) {
var array = [];
var i = 0;
angular.forEach(yql.data.query.results.row, function (value) {
if (i++ > 0) {
var date = new Date(value.col0).getTime();
var price = parseFloat(value.col3);
this.push([date, price]);
}
}, array);
var serie = {
name: 'Bitcoin in USD',
color: '#A80000',
data: array,
tooltip: {
valueDecimals: 2
}
};
return serie;
});
}
};
return bitcoinData;
});
|
Fix SectionLayoutRenderer blockMap prop type. | import React, { Component, PropTypes } from 'react';
import { ContentLayoutEngine, BlockTypeMap } from '../index';
export default class SectionLayoutRenderer extends Component {
static renderBlocks(blocks, blockMap) {
if (!blocks && !blocks.length) {
return null;
}
// Merge user supplied content blocks with default set.
let mergedBlockMap = BlockTypeMap;
if (blockMap) {
mergedBlockMap = {
...BlockTypeMap,
...blockMap
}
}
return blocks.map((block, index) => { // eslint-disable-line arrow-body-style
if (!block.blockType) {
return null;
}
return (!block.edit) ? React.cloneElement(
mergedBlockMap[block.blockType].element,
{
...block,
key: `block-${index}`,
},
) : undefined;
});
}
render() {
const { section, blockMap, ...rest } = this.props;
return (
<ContentLayoutEngine
{...rest}
layout={section.layout}
blocks={section.contentBlocks}
>
{SectionLayoutRenderer.renderBlocks(section.contentBlocks, blockMap)}
</ContentLayoutEngine>
);
}
}
SectionLayoutRenderer.propTypes = {
section: PropTypes.shape({
contentBlocks: PropTypes.arrayOf(
PropTypes.shape({
blockType: PropTypes.string.isRequired,
content: PropTypes.string,
id: PropTypes.string.isRequired,
}),
).isRequired,
layout: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
value: PropTypes.string,
}),
).isRequired,
}),
blockMap: PropTypes.object
}; | import React, { Component, PropTypes } from 'react';
import { ContentLayoutEngine, BlockTypeMap } from '../index';
export default class SectionLayoutRenderer extends Component {
static renderBlocks(blocks, blockMap) {
if (!blocks && !blocks.length) {
return null;
}
// Merge user supplied content blocks with default set.
let mergedBlockMap = BlockTypeMap;
if (blockMap) {
mergedBlockMap = {
...BlockTypeMap,
...blockMap
}
}
return blocks.map((block, index) => { // eslint-disable-line arrow-body-style
if (!block.blockType) {
return null;
}
return (!block.edit) ? React.cloneElement(
mergedBlockMap[block.blockType].element,
{
...block,
key: `block-${index}`,
},
) : undefined;
});
}
render() {
const { section, blockMap, ...rest } = this.props;
return (
<ContentLayoutEngine
{...rest}
layout={section.layout}
blocks={section.contentBlocks}
>
{SectionLayoutRenderer.renderBlocks(section.contentBlocks, blockMap)}
</ContentLayoutEngine>
);
}
}
SectionLayoutRenderer.propTypes = {
section: PropTypes.shape({
contentBlocks: PropTypes.arrayOf(
PropTypes.shape({
blockType: PropTypes.string.isRequired,
content: PropTypes.string,
id: PropTypes.string.isRequired,
}),
).isRequired,
layout: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
value: PropTypes.string,
}),
).isRequired,
}),
blockMap: PropTypes.array
}; |
Load value from json field as string. | import json
import copy
from django import forms
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
class JSONEditorWidget(forms.Widget):
template_name = 'django_json_editor/django_json_editor.html'
def __init__(self, schema, collapsed=True):
super().__init__()
self._schema = schema
self._collapsed = collapsed
def render(self, name, value, attrs=None):
if callable(self._schema):
schema = self._schema(self)
else:
schema = copy.copy(self._schema)
schema['title'] = ' '
schema['options'] = {'collapsed': int(self._collapsed)}
context = {
'name': name,
'schema': schema,
'data': value,
}
return mark_safe(render_to_string(self.template_name, context))
class Media:
css = {'all': (
'django_json_editor/bootstrap/css/bootstrap.min.css',
'django_json_editor/fontawesome/css/font-awesome.min.css',
'django_json_editor/style.css',
)}
js = (
'django_json_editor/jquery/jquery.min.js',
'django_json_editor/bootstrap/js/bootstrap.min.js',
'django_json_editor/jsoneditor/jsoneditor.min.js',
)
| import json
import copy
from django import forms
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
class JSONEditorWidget(forms.Widget):
template_name = 'django_json_editor/django_json_editor.html'
def __init__(self, schema, collapsed=True):
super().__init__()
self._schema = schema
self._collapsed = collapsed
def render(self, name, value, attrs=None):
if callable(self._schema):
schema = self._schema(self)
else:
schema = copy.copy(self._schema)
schema['title'] = ' '
schema['options'] = {'collapsed': int(self._collapsed)}
context = {
'name': name,
'schema': schema,
'data': json.loads(value),
}
return mark_safe(render_to_string(self.template_name, context))
class Media:
css = {'all': (
'django_json_editor/bootstrap/css/bootstrap.min.css',
'django_json_editor/fontawesome/css/font-awesome.min.css',
'django_json_editor/style.css',
)}
js = (
'django_json_editor/jquery/jquery.min.js',
'django_json_editor/bootstrap/js/bootstrap.min.js',
'django_json_editor/jsoneditor/jsoneditor.min.js',
)
|
Mark workspace app related properties as deprecated | package com.github.seratch.jslack.api.methods.response.oauth;
import com.github.seratch.jslack.api.methods.SlackApiResponse;
import lombok.Data;
import java.util.List;
@Data
public class OAuthAccessResponse implements SlackApiResponse {
private boolean ok;
private String warning;
private String error;
private String needed;
private String provided;
private String tokenType;
private String accessToken;
private String scope;
private String enterpriseId;
private String teamName;
private String teamId;
private String userId;
private IncomingWebhook incomingWebhook;
private Bot bot;
@Data
public static class IncomingWebhook {
private String url;
private String channel;
private String channelId;
private String configurationUrl;
}
@Data
public static class Bot {
private String botUserId;
private String botAccessToken;
}
@Deprecated // for workspace apps
private AuthorizingUser authorizingUser;
@Deprecated // for workspace apps
private InstallerUser installerUser;
@Deprecated // for workspace apps
private Scopes scopes;
@Deprecated
@Data
public static class AuthorizingUser {
private String userId;
private String appHome;
}
@Deprecated
@Data
public static class InstallerUser {
private String userId;
private String appHome;
}
@Deprecated
@Data
public static class Scopes {
private List<String> appHome;
private List<String> team;
private List<String> channel;
private List<String> group;
private List<String> mpim;
private List<String> im;
private List<String> user;
}
}
| package com.github.seratch.jslack.api.methods.response.oauth;
import com.github.seratch.jslack.api.methods.SlackApiResponse;
import lombok.Data;
import java.util.List;
@Data
public class OAuthAccessResponse implements SlackApiResponse {
private boolean ok;
private String warning;
private String error;
private String needed;
private String provided;
private String tokenType;
private String accessToken;
private String scope;
private String enterpriseId;
private String teamName;
private String teamId;
private String userId;
private IncomingWebhook incomingWebhook;
private Bot bot;
private AuthorizingUser authorizingUser;
private InstallerUser installerUser;
@Deprecated // for workspace apps
private Scopes scopes;
@Data
public static class IncomingWebhook {
private String url;
private String channel;
private String channelId;
private String configurationUrl;
}
@Data
public static class Bot {
private String botUserId;
private String botAccessToken;
}
@Data
public static class AuthorizingUser {
private String userId;
private String appHome;
}
@Data
public static class InstallerUser {
private String userId;
private String appHome;
}
@Data
public static class Scopes {
private List<String> appHome;
private List<String> team;
private List<String> channel;
private List<String> group;
private List<String> mpim;
private List<String> im;
private List<String> user;
}
}
|
Remove ember 1.10 testing scenario | /*jshint node:true*/
function scenario(emberVersion) {
return {
name: 'ember-' + emberVersion,
bower: {
dependencies: {
'ember': '~' + emberVersion + '.0'
},
resolutions: {
'ember': '~' + emberVersion + '.0'
}
}
};
}
module.exports = {
scenarios: [
scenario('1.11'),
scenario('1.12'),
scenario('1.13'),
scenario('2.0'),
scenario('2.1'),
scenario('2.2'),
scenario('2.3'),
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
| /*jshint node:true*/
function scenario(emberVersion) {
return {
name: 'ember-' + emberVersion,
bower: {
dependencies: {
'ember': '~' + emberVersion + '.0'
},
resolutions: {
'ember': '~' + emberVersion + '.0'
}
}
};
}
module.exports = {
scenarios: [
scenario('1.10'),
scenario('1.11'),
scenario('1.12'),
scenario('1.13'),
scenario('2.0'),
scenario('2.1'),
scenario('2.2'),
scenario('2.3'),
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
|
Implement new methods for entify phone verified | <?php
namespace Listabierta\Bundle\MunicipalesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PhoneVerified
*
* @ORM\Entity
* @ORM\Table(name="phone_verified")
*/
class PhoneVerified
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $phone;
/**
* @var string
*/
private $email;
/**
* @var \DateTime
*/
private $timestamp;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set phone
*
* @param string $phone
* @return PhoneVerified
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set email
*
* @param string $email
* @return PhoneVerified
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set timestamp
*
* @param \DateTime $timestamp
* @return PhoneVerified
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
return $this;
}
/**
* Get timestamp
*
* @return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
}
| <?php
namespace Listabierta\Bundle\MunicipalesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PhoneVerified
*/
class PhoneVerified
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $phone;
/**
* @var \DateTime
*/
private $timestamp;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set phone
*
* @param string $phone
* @return PhoneVerified
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set timestamp
*
* @param \DateTime $timestamp
* @return PhoneVerified
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
return $this;
}
/**
* Get timestamp
*
* @return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
}
|
Convert invalid hyphens to underscores for Android | // Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
const _ = require("lodash");
const xml = require("xml");
module.exports = def => {
const o = {
resources: def
.get("props")
.map(prop => {
const key = (() => {
switch (prop.get("type")) {
case "color":
return "color";
case "size":
return "dimen";
case "number":
return "integer";
case "string":
return "string";
default:
return "property";
}
})();
return {
[key]: [
{
_attr: {
name: _.toUpper(prop.get("name")).replace(/[-]/g, "_"),
category: prop.get("category")
}
},
prop.get("value")
]
};
})
.toJS()
};
return xml(o, {
indent: " ",
declaration: true
});
};
| // Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
const _ = require("lodash");
const xml = require("xml");
module.exports = def => {
const o = {
resources: def
.get("props")
.map(prop => {
const key = (() => {
switch (prop.get("type")) {
case "color":
return "color";
case "size":
return "dimen";
case "number":
return "integer";
case "string":
return "string";
default:
return "property";
}
})();
return {
[key]: [
{
_attr: {
name: _.toUpper(prop.get("name")),
category: prop.get("category")
}
},
prop.get("value")
]
};
})
.toJS()
};
return xml(o, {
indent: " ",
declaration: true
});
};
|
Use json instead of simplejson
Signed-off-by: Jan Dvořák <[email protected]> | #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['KeaAgent']
from os import system
from twisted.python import log
from json import dump, load
from adminator.kea import generate_kea_config, DEFAULTS
class KeaAgent(object):
def __init__(self, db, template=None, output=None, signal=None):
self.db = db
if template is not None:
log.msg('Reading Template {}'.format(template))
with open(template) as fp:
self.template = load(fp)
else:
self.template = DEFAULTS
self.output = output or '/etc/kea/kea.conf'
self.signal = signal or 'keactrl reload'
def start(self):
self.update()
def notify(self, event):
log.msg('Database Notification: {}'.format(event.channel))
if event.channel == 'dhcp':
self.update()
def update(self):
log.msg('Generating Configuration')
config = generate_kea_config(self.db, self.template)
log.msg('Writing: {}'.format(self.output))
with open(self.output, 'w') as fp:
dump(config, fp)
log.msg('Executing: {}'.format(self.signal))
system(self.signal)
# vim:set sw=4 ts=4 et:
| #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['KeaAgent']
from os import system
from twisted.python import log
from simplejson import dump, load
from adminator.kea import generate_kea_config, DEFAULTS
class KeaAgent(object):
def __init__(self, db, template=None, output=None, signal=None):
self.db = db
if template is not None:
log.msg('Reading Template {}'.format(template))
with open(template) as fp:
self.template = load(fp)
else:
self.template = DEFAULTS
self.output = output or '/etc/kea/kea.conf'
self.signal = signal or 'keactrl reload'
def start(self):
self.update()
def notify(self, event):
log.msg('Database Notification: {}'.format(event.channel))
if event.channel == 'dhcp':
self.update()
def update(self):
log.msg('Generating Configuration')
config = generate_kea_config(self.db, self.template)
log.msg('Writing: {}'.format(self.output))
with open(self.output, 'w') as fp:
dump(config, fp)
log.msg('Executing: {}'.format(self.signal))
system(self.signal)
# vim:set sw=4 ts=4 et:
|
Add test to removeCleanApiParameter method | package io.searchbox.indices;
import io.searchbox.action.Action;
import org.junit.Test;
import java.net.URLDecoder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class StatsTest {
@Test
public void testBasicUriGeneration() {
Stats stats = new Stats.Builder().addIndex("twitter").build();
assertEquals("GET", stats.getRestMethodName());
assertEquals("twitter/_stats", stats.getURI());
}
@Test
public void equalsReturnsTrueForSameIndex() {
Stats stats1 = new Stats.Builder().addIndex("twitter").build();
Stats stats1Duplicate = new Stats.Builder().addIndex("twitter").build();
assertEquals(stats1, stats1Duplicate);
}
@Test
public void equalsReturnsFalseForDifferentIndex() {
Stats stats1 = new Stats.Builder().addIndex("twitter").build();
Stats stats2 = new Stats.Builder().addIndex("myspace").build();
assertNotEquals(stats1, stats2);
}
@Test
public void testUriGenerationWithStatsFields() throws Exception {
Action action = new Stats.Builder()
.flush(true)
.indexing(true)
.search(true, "group1", "group2")
.build();
assertEquals("_all/_stats/flush,indexing,search?groups=group1,group2", URLDecoder.decode(action.getURI()));
}
@Test
public void testUriGenerationWhenRemovingStatsFields() throws Exception {
Action action = new Stats.Builder()
.flush(true)
.indexing(true)
.indexing(false)
.build();
assertEquals("_all/_stats/flush", URLDecoder.decode(action.getURI()));
}
} | package io.searchbox.indices;
import io.searchbox.action.Action;
import org.junit.Test;
import java.net.URLDecoder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class StatsTest {
@Test
public void testBasicUriGeneration() {
Stats stats = new Stats.Builder().addIndex("twitter").build();
assertEquals("GET", stats.getRestMethodName());
assertEquals("twitter/_stats", stats.getURI());
}
@Test
public void equalsReturnsTrueForSameIndex() {
Stats stats1 = new Stats.Builder().addIndex("twitter").build();
Stats stats1Duplicate = new Stats.Builder().addIndex("twitter").build();
assertEquals(stats1, stats1Duplicate);
}
@Test
public void equalsReturnsFalseForDifferentIndex() {
Stats stats1 = new Stats.Builder().addIndex("twitter").build();
Stats stats2 = new Stats.Builder().addIndex("myspace").build();
assertNotEquals(stats1, stats2);
}
@Test
public void testUriGenerationWithStatsFields() throws Exception {
Action action = new Stats.Builder()
.flush(true)
.indexing(true)
.search(true, "group1", "group2")
.build();
assertEquals("_all/_stats/flush,indexing,search?groups=group1,group2", URLDecoder.decode(action.getURI()));
}
} |
Fix pressurised water render in copper tanks. | package mariculture.core.render;
import mariculture.core.tile.TileTankBlock;
import net.minecraftforge.fluids.FluidStack;
public class RenderCopperTank extends RenderBase {
public RenderCopperTank() {}
@Override
public void renderBlock() {
if (!isItem()) {
TileTankBlock tank = (TileTankBlock) world.getTileEntity(x, y, z);
if (tank != null) if (tank.tank.getFluidAmount() > 0) {
FluidStack fluid = tank.tank.getFluid();
if (fluid != null) {
double height = fluid.amount * 1D / tank.getCapacity();
setTexture(fluid.getFluid().getStillIcon());
if(fluid.getFluid().getBlock() != null) {
setTexture(fluid.getFluid().getBlock().getIcon(world, x, y, z, 0));
}
if(fluid.getFluid().isGaseous()) {
renderFluidBlock(0, 1 - height, 0, 1, 1, 1);
} else {
renderFluidBlock(0, 0, 0, 1, height, 1);
}
}
}
}
setTexture(block);
renderBlock(-0.01D, -0.01D, -0.01D, 1.01D, 1.01D, 1.01D);
}
}
| package mariculture.core.render;
import mariculture.core.tile.TileTankBlock;
import net.minecraftforge.fluids.FluidStack;
public class RenderCopperTank extends RenderBase {
public RenderCopperTank() {}
@Override
public void renderBlock() {
if (!isItem()) {
TileTankBlock tank = (TileTankBlock) world.getTileEntity(x, y, z);
if (tank != null) if (tank.tank.getFluidAmount() > 0) {
FluidStack fluid = tank.tank.getFluid();
if (fluid != null) {
double height = fluid.amount * 1D / tank.getCapacity();
setTexture(fluid.getFluid().getIcon());
if(fluid.getFluid().isGaseous()) {
renderFluidBlock(0, 1 - height, 0, 1, 1, 1);
} else {
renderFluidBlock(0, 0, 0, 1, height, 1);
}
}
}
}
setTexture(block);
renderBlock(-0.01D, -0.01D, -0.01D, 1.01D, 1.01D, 1.01D);
}
}
|
Add return to replies so they don't get called multiple times | const logger = require('./logger');
module.exports = (
userService,
themeService,
clientService
) => {
return (templateName, getView, postHandler) => async (request, reply, source, error) => {
if (error && error.output.statusCode === 404) {
return reply(error);
}
try {
const client = await clientService.findById(request.query.client_id);
let user = null;
if (request.auth.isAuthenticated) {
user = request.auth.strategy === 'email_token'
? request.auth.credentials.user
: await userService.findById(request.auth.credentials.accountId());
}
const render = async e => {
const viewContext = getView(user, client, request, e);
const template = await themeService.renderThemedTemplate(request.query.client_id, templateName, viewContext);
if (template) {
return reply(template);
} else {
return reply.view(templateName, viewContext);
}
}
if (!error && request.method === 'post') {
error = await postHandler(request, reply, user, client, render);
} else {
await render(error);
}
} catch(e) {
return reply(e);
}
};
};
module.exports['@singleton'] = true;
module.exports['@require'] = [
'user/user-service',
'theme/theme-service',
'client/client-service',
];
| const logger = require('./logger');
module.exports = (
userService,
themeService,
clientService
) => {
return (templateName, getView, postHandler) => async (request, reply, source, error) => {
if (error && error.output.statusCode === 404) {
reply(error);
}
try {
const client = await clientService.findById(request.query.client_id);
let user = null;
if (request.auth.isAuthenticated) {
user = request.auth.strategy === 'email_token'
? request.auth.credentials.user
: await userService.findById(request.auth.credentials.accountId());
}
const render = async e => {
const viewContext = getView(user, client, request, e);
const template = await themeService.renderThemedTemplate(request.query.client_id, templateName, viewContext);
if (template) {
reply(template);
} else {
reply.view(templateName, viewContext);
}
}
if (!error && request.method === 'post') {
error = await postHandler(request, reply, user, client, render);
} else {
await render(error);
}
} catch(e) {
reply(e);
}
};
};
module.exports['@singleton'] = true;
module.exports['@require'] = [
'user/user-service',
'theme/theme-service',
'client/client-service',
];
|
Add object creation methods for Message | import json
class Message:
def __init__(self, sender, message_type, content=None):
self.message = {
'sender': sender,
'type': message_type,
'content': content
}
def __str__(self):
return json.dumps(self.message)
def __repr__(self):
return "Message: %s" % self
@classmethod
def from_json(self, json_dict):
# TODO: missing attributes parsing
return Message(json_dict['sender'], json_dict['type'], json_dict['content'])
@classmethod
def from_string(self, json_str):
return Message.from_json(json.loads(json_str))
@property
def sender(self):
return self.message['sender']
@property
def type(self):
return self.message['type']
@property
def content(self):
return self.message['content']
class MessengerMeta(type):
def __new__(cls, clsname, supercls, attr_dict):
clsobj = super().__new__(cls, clsname, supercls, attr_dict)
if 'no_parameter_messages' not in attr_dict:
raise AttributeError("no_parameter_messages attribute must be defined")
for name, content in attr_dict['no_parameter_messages'].items():
fullname, body = MessengerMeta.get_method(name, content)
setattr(clsobj, fullname, body)
return clsobj
@staticmethod
def get_method(name, content):
def method(self):
return Message(self.sender, content)
return 'build_{}_message'.format(name), method
class Messenger(metaclass=MessengerMeta):
no_parameter_messages = {}
def __init__(self, sender: str):
self.sender = sender
| import json
class Message:
def __init__(self, sender, message_type, content=None):
self.message = {
'sender': sender,
'type': message_type,
'content': content
}
def __str__(self):
return json.dumps(self.message)
def __repr__(self):
return "Message: %s" % self
@property
def sender(self):
return self.message['sender']
@property
def type(self):
return self.message['type']
@property
def content(self):
return self.message['content']
class MessengerMeta(type):
def __new__(cls, clsname, supercls, attr_dict):
clsobj = super().__new__(cls, clsname, supercls, attr_dict)
if 'no_parameter_messages' not in attr_dict:
raise AttributeError("no_parameter_messages attribute must be defined")
for name, content in attr_dict['no_parameter_messages'].items():
fullname, body = MessengerMeta.get_method(name, content)
setattr(clsobj, fullname, body)
return clsobj
@staticmethod
def get_method(name, content):
def method(self):
return Message(self.sender, content)
return 'build_{}_message'.format(name), method
class Messenger(metaclass=MessengerMeta):
no_parameter_messages = {}
def __init__(self, sender: str):
self.sender = sender
|
NOJIRA: Clarify comments on how to configure the demo. | /*
Copyright 2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.
You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/
/*global jQuery*/
var demo = demo || {};
(function ($) {
var getUrlParameter = function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results === null) {
return "";
} else {
return results[1];
}
};
demo.setup = function () {
var objectId = getUrlParameter("objectId");
var opts = {};
/*
The CollectionObjectDAO default options are suitable for testing on a local machine.
To configure the demo to run on a particular server, set the baseUrl option to reference
the URL for the application layer, as shown in the following sample:
opts.dao = {
type: "cspace.collectionObjectDAO",
options: {
baseUrl: "http://localhost:8080/chain/"
}
};
*/
if (objectId) {
opts.objectId = objectId;
}
cspace.objectEntry(".csc-object-entry-container", opts);
};
})(jQuery);
| /*
Copyright 2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.
You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/
/*global jQuery*/
var demo = demo || {};
(function ($) {
var getUrlParameter = function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results === null) {
return "";
} else {
return results[1];
}
};
demo.setup = function () {
var objectId = getUrlParameter("objectId");
var opts = {
// TEMPORARY 2009-06-10:
// To test on a local server with the chain application, uncomment this option block:
/*
dao: {
type: "cspace.collectionObjectDAO",
options: {
baseUrl: "http://localhost:8080/chain/"
}
}
*/
};
if (objectId) {
opts.objectId = objectId;
}
cspace.objectEntry(".csc-object-entry-container", opts);
};
})(jQuery);
|
:green_heart: Set SL currency to 1 | const karmaDefault = require('./karma.default');
module.exports = config => {
// Browsers to run on Sauce Labs
const customLaunchers = {
'SL_Chrome': {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 10',
version: 'latest'
},
'SL_Edge': {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
version: 'latest'
},
'SL_FireFox': {
base: 'SauceLabs',
browserName: 'firefox',
platform: 'Windows 10',
version: 'latest'
}
};
config.set(Object.assign({}, karmaDefault(config), {
// Webpack please don't spam the console when running in karma!
webpackServer: { noInfo: true },
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
sauceLabs: {
testName: 'Angular lazy load images',
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY,
startConnect: false
},
captureTimeout: 120000,
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
singleRun: true,
concurrency: 1,
autoWatch: false
}));
};
| const karmaDefault = require('./karma.default');
module.exports = config => {
// Browsers to run on Sauce Labs
const customLaunchers = {
'SL_Chrome': {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 10',
version: 'latest'
},
'SL_Edge': {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
version: 'latest'
},
'SL_FireFox': {
base: 'SauceLabs',
browserName: 'firefox',
platform: 'Windows 10',
version: 'latest'
}
};
config.set(Object.assign({}, karmaDefault(config), {
// Webpack please don't spam the console when running in karma!
webpackServer: { noInfo: true },
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
sauceLabs: {
testName: 'Angular lazy load images',
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY,
startConnect: false
},
captureTimeout: 120000,
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
singleRun: true,
autoWatch: false
}));
};
|
Rename it to Hermes2D GUI | """ The Acme Lab application. """
# Standard library imports.
from logging import DEBUG
# Enthought library imports.
from enthought.envisage.ui.workbench.api import WorkbenchApplication
from enthought.pyface.api import AboutDialog, ImageResource, SplashScreen
class Acmelab(WorkbenchApplication):
""" The Acme Lab application. """
#### 'IApplication' interface #############################################
# The application's globally unique Id.
id = 'acme.acmelab'
#### 'WorkbenchApplication' interface #####################################
# Branding information.
#
# The icon used on window title bars etc.
icon = ImageResource('acmelab.ico')
# The name of the application (also used on window title bars etc).
name = 'Hermes2D GUI'
###########################################################################
# 'WorkbenchApplication' interface.
###########################################################################
def _about_dialog_default(self):
""" Trait initializer. """
about_dialog = AboutDialog(
parent = self.workbench.active_window.control,
image = ImageResource('about')
)
return about_dialog
def _splash_screen_default(self):
""" Trait initializer. """
splash_screen = SplashScreen(
image = ImageResource('splash'),
show_log_messages = True,
log_level = DEBUG
)
return splash_screen
#### EOF ######################################################################
| """ The Acme Lab application. """
# Standard library imports.
from logging import DEBUG
# Enthought library imports.
from enthought.envisage.ui.workbench.api import WorkbenchApplication
from enthought.pyface.api import AboutDialog, ImageResource, SplashScreen
class Acmelab(WorkbenchApplication):
""" The Acme Lab application. """
#### 'IApplication' interface #############################################
# The application's globally unique Id.
id = 'acme.acmelab'
#### 'WorkbenchApplication' interface #####################################
# Branding information.
#
# The icon used on window title bars etc.
icon = ImageResource('acmelab.ico')
# The name of the application (also used on window title bars etc).
name = 'Acme Lab'
###########################################################################
# 'WorkbenchApplication' interface.
###########################################################################
def _about_dialog_default(self):
""" Trait initializer. """
about_dialog = AboutDialog(
parent = self.workbench.active_window.control,
image = ImageResource('about')
)
return about_dialog
def _splash_screen_default(self):
""" Trait initializer. """
splash_screen = SplashScreen(
image = ImageResource('splash'),
show_log_messages = True,
log_level = DEBUG
)
return splash_screen
#### EOF ######################################################################
|
Fix compatibility with API v19
- use Interpolator from v7 support library instead of using the APIv21 version | package com.reidzeibel.animatedlistadapter.utils;
import android.content.Context;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
/**
* Created by RidwanAditama on 16/01/2017.
*/
public class AnimUtils {
private AnimUtils() { }
private static Interpolator fastOutSlowIn;
private static Interpolator fastOutLinearIn;
private static Interpolator linearOutSlowIn;
private static Interpolator linear;
public static Interpolator getFastOutSlowInInterpolator(Context context) {
if (fastOutSlowIn == null) {
fastOutSlowIn = new FastOutSlowInInterpolator();
}
return fastOutSlowIn;
}
public static Interpolator getFastOutLinearInInterpolator(Context context) {
if (fastOutLinearIn == null) {
fastOutLinearIn = new FastOutLinearInInterpolator();
}
return fastOutLinearIn;
}
public static Interpolator getLinearOutSlowInInterpolator(Context context) {
if (linearOutSlowIn == null) {
linearOutSlowIn = new LinearOutSlowInInterpolator();
}
return linearOutSlowIn;
}
public static Interpolator getLinearInterpolator() {
if (linear == null) {
linear = new LinearInterpolator();
}
return linear;
}
}
| package com.reidzeibel.animatedlistadapter.utils;
import android.content.Context;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
/**
* Created by RidwanAditama on 16/01/2017.
*/
public class AnimUtils {
private AnimUtils() { }
private static Interpolator fastOutSlowIn;
private static Interpolator fastOutLinearIn;
private static Interpolator linearOutSlowIn;
private static Interpolator linear;
public static Interpolator getFastOutSlowInInterpolator(Context context) {
if (fastOutSlowIn == null) {
fastOutSlowIn = AnimationUtils.loadInterpolator(context,
android.R.interpolator.fast_out_slow_in);
}
return fastOutSlowIn;
}
public static Interpolator getFastOutLinearInInterpolator(Context context) {
if (fastOutLinearIn == null) {
fastOutLinearIn = AnimationUtils.loadInterpolator(context,
android.R.interpolator.fast_out_linear_in);
}
return fastOutLinearIn;
}
public static Interpolator getLinearOutSlowInInterpolator(Context context) {
if (linearOutSlowIn == null) {
linearOutSlowIn = AnimationUtils.loadInterpolator(context,
android.R.interpolator.linear_out_slow_in);
}
return linearOutSlowIn;
}
public static Interpolator getLinearInterpolator() {
if (linear == null) {
linear = new LinearInterpolator();
}
return linear;
}
}
|
Add docstring to load() method | """Facility to load plugins."""
import sys
import os
from importlib import import_module
class StraightPluginLoader(object):
"""Performs the work of locating and loading straight plugins.
This looks for plugins in every location in the import path.
"""
def _findPluginFilePaths(self, namespace):
already_seen = set()
# Look in each location in the path
for path in sys.path:
# Within this, we want to look for a package for the namespace
namespace_rel_path = namespace.replace(".", os.path.sep)
namespace_path = os.path.join(path, namespace_rel_path)
if os.path.exists(namespace_path):
for possible in os.listdir(namespace_path):
base, ext = os.path.splitext(possible)
if base == '__init__' or ext != '.py':
continue
if base not in already_seen:
already_seen.add(base)
yield os.path.join(namespace, possible)
def _findPluginModules(self, namespace):
for filepath in self._findPluginFilePaths(namespace):
path_segments = list(filepath.split(os.path.sep))
path_segments = [p for p in path_segments if p]
path_segments[-1] = os.path.splitext(path_segments[-1])[0]
import_path = '.'.join(path_segments)
yield import_module(import_path)
def load(self, namespace):
"""Load all modules found in a namespace"""
modules = self._findPluginModules(namespace)
return list(modules)
| """Facility to load plugins."""
import sys
import os
from importlib import import_module
class StraightPluginLoader(object):
"""Performs the work of locating and loading straight plugins.
This looks for plugins in every location in the import path.
"""
def _findPluginFilePaths(self, namespace):
already_seen = set()
# Look in each location in the path
for path in sys.path:
# Within this, we want to look for a package for the namespace
namespace_rel_path = namespace.replace(".", os.path.sep)
namespace_path = os.path.join(path, namespace_rel_path)
if os.path.exists(namespace_path):
for possible in os.listdir(namespace_path):
base, ext = os.path.splitext(possible)
if base == '__init__' or ext != '.py':
continue
if base not in already_seen:
already_seen.add(base)
yield os.path.join(namespace, possible)
def _findPluginModules(self, namespace):
for filepath in self._findPluginFilePaths(namespace):
path_segments = list(filepath.split(os.path.sep))
path_segments = [p for p in path_segments if p]
path_segments[-1] = os.path.splitext(path_segments[-1])[0]
import_path = '.'.join(path_segments)
yield import_module(import_path)
def load(self, namespace):
modules = self._findPluginModules(namespace)
return list(modules)
|
Add height/width URL parameters only if not templated | window.Slapdash = window.Slapdash || {};
Slapdash.Util = {
_urlTemplates: {
height: '%height%',
width: '%width%'
},
debug: function(msg){
if (console && console.log) console.log('Slapdash [DEBUG]: ' + msg);
},
showError: function(err){
alert(err);
},
getSize: function(x){
return (Slapdash.Config.spanSize * x) +
(Slapdash.Config.spanMargin * (x - 1));
},
getUrl: function(graph,layoutElement){
var url = graph.baseUrl + graph.url,
width = Slapdash.Util.getSize(layoutElement[0]),
height = Slapdash.Util.getSize(layoutElement[1]);
params = graph.parameters;
if (graph.templateUrl){
url = url.replace(Slapdash.Util._urlTemplates.height, height);
url = url.replace(Slapdash.Util._urlTemplates.width, width);
}
else {
_.extend(params, {width:width, height:height});
}
url += (url.indexOf("?") >= 0) ? "&" : "?";
url += $.param(params);
return url;
}
} | window.Slapdash = window.Slapdash || {};
Slapdash.Util = {
_urlTemplates: {
height: '%height%',
width: '%width%'
},
debug: function(msg){
if (console && console.log) console.log('Slapdash [DEBUG]: ' + msg);
},
showError: function(err){
alert(err);
},
getSize: function(x){
return (Slapdash.Config.spanSize * x) +
(Slapdash.Config.spanMargin * (x - 1));
},
getUrl: function(graph,layoutElement){
var url = graph.baseUrl + graph.url,
width = Slapdash.Util.getSize(layoutElement[0]),
height = Slapdash.Util.getSize(layoutElement[1]);
params = _.extend({},graph.parameters,{width:width,height:height});
url += (url.indexOf("?") >= 0) ? "&" : "?";
url += $.param(params);
if (graph.templateUrl){
url = url.replace(Slapdash.Util._urlTemplates.height, height);
url = url.replace(Slapdash.Util._urlTemplates.width, width);
}
return url;
}
} |
Use non-breaking space when book field is null. | /**
* Book page
*/
define([
"underscore",
"backbone"
],
function(_, Backbone) {
var BookPage = Backbone.View.extend({
render: function() {
// Fill out existing structure.
var fieldsStandardText = ["title", "isbn", "publisher", "notesPublic", "notesPrivate"],
authors, fieldValue;
_.each(fieldsStandardText, function(field) {
// Use non-breaking space when field is null.
if (this.model.has(field)) {
fieldValue = this.model.get(field);
} else {
fieldValue = " ";
}
this.$("#book-" + field).html(fieldValue);
}, this);
// Show either author or authors rows.
authors = this.model.get("authors");
if (!_.isArray(authors) || authors.length === 0) {
// Hide both.
this.$(".author, .authors").hide();
} else {
// REFACTOR: use just one line, if simply using text for multiple authors.
if (authors.length === 1) {
this.$(".authors").hide();
this.$(".author").show();
this.$(".author.ui-block-b div").html(authors[0]);
} else {
this.$(".author").hide();
this.$(".authors").show();
this.$(".authors.ui-block-b div").html(authors.join(", "));
}
}
// Private?
this.$("#book-public").html(
this.model.get("public") ? "Yes" : "No"
);
return this;
}
});
return BookPage;
});
| /**
* Book page
*/
define([
"underscore",
"backbone"
],
function(_, Backbone) {
var BookPage = Backbone.View.extend({
render: function() {
// Fill out existing structure.
var fieldsStandardText = ["title", "isbn", "publisher", "notesPublic", "notesPrivate"],
authors;
_.each(fieldsStandardText, function(field) {
this.$("#book-" + field).html(this.model.get(field));
}, this);
// Show either author or authors rows.
authors = this.model.get("authors");
if (!_.isArray(authors) || authors.length === 0) {
// Hide both.
this.$(".author, .authors").hide();
} else {
// REFACTOR: use just one line, if simply using text for multiple authors.
if (authors.length === 1) {
this.$(".authors").hide();
this.$(".author").show();
this.$(".author.ui-block-b div").html(authors[0]);
} else {
this.$(".author").hide();
this.$(".authors").show();
this.$(".authors.ui-block-b div").html(authors.join(", "));
}
}
// Private?
this.$("#book-public").html(
this.model.get("public") ? "Yes" : "No"
);
return this;
}
});
return BookPage;
});
|
Add metadata.tables to mock db. | from flexmock import flexmock
from flask.ext.storage import MockStorage
from flask_uploads import init
class TestCase(object):
added_objects = []
committed_objects = []
created_objects = []
deleted_objects = []
def setup_method(self, method, resizer=None):
init(db_mock, MockStorage, resizer)
self.db = db_mock
self.Storage = MockStorage
self.storage = MockStorage()
self.resizer = resizer
def teardown_method(self, method):
# Empty the stacks.
TestCase.added_objects[:] = []
TestCase.committed_objects[:] = []
TestCase.created_objects[:] = []
TestCase.deleted_objects[:] = []
class MockModel(object):
def __init__(self, **kw):
TestCase.created_objects.append(self)
for key, val in kw.iteritems():
setattr(self, key, val)
db_mock = flexmock(
Column=lambda *a, **kw: ('column', a, kw),
Integer=('integer', [], {}),
Unicode=lambda *a, **kw: ('unicode', a, kw),
Model=MockModel,
metadata=flexmock(tables={}),
session=flexmock(
add=TestCase.added_objects.append,
commit=lambda: TestCase.committed_objects.extend(
TestCase.added_objects + TestCase.deleted_objects
),
delete=TestCase.deleted_objects.append,
),
)
| from flexmock import flexmock
from flask.ext.storage import MockStorage
from flask_uploads import init
class TestCase(object):
added_objects = []
committed_objects = []
created_objects = []
deleted_objects = []
def setup_method(self, method, resizer=None):
init(db_mock, MockStorage, resizer)
self.db = db_mock
self.Storage = MockStorage
self.storage = MockStorage()
self.resizer = resizer
def teardown_method(self, method):
# Empty the stacks.
TestCase.added_objects[:] = []
TestCase.committed_objects[:] = []
TestCase.created_objects[:] = []
TestCase.deleted_objects[:] = []
class MockModel(object):
def __init__(self, **kw):
TestCase.created_objects.append(self)
for key, val in kw.iteritems():
setattr(self, key, val)
db_mock = flexmock(
Column=lambda *a, **kw: ('column', a, kw),
Integer=('integer', [], {}),
Unicode=lambda *a, **kw: ('unicode', a, kw),
Model=MockModel,
session=flexmock(
add=TestCase.added_objects.append,
commit=lambda: TestCase.committed_objects.extend(
TestCase.added_objects + TestCase.deleted_objects
),
delete=TestCase.deleted_objects.append,
),
)
|
Add absolute path for including autoloader | <?php
require_once(__DIR__.'/../../../../../public/Bootstrap.php');
//require_once('Bootstrap.php');
/**
* Error logging
*
* default error log path for process "/var/log/httpd/error_log"
* to change error log path:
* ini_set('error_log', "/var/www/vhosts/dev/api-test/logs/error_log");
*/
// Get pass-in Multiprocess Object
$multiProcess = $argv[1];
$multiProcess = unserialize(base64_decode($multiProcess));
// Fork each single process contain in multiprocess
foreach( $multiProcess->getProcesses() as $name => $process ){
// Inject service manager to each process
$process->setServiceManager($sm);
// Fork process
$pid = pcntl_fork();
if($pid == -1) {
// TODO: throw exception
exit("Error forking...\n");
}
// In child process
else if($pid == 0) {
/**
* Set the Process title
* Terminal Command to check process
* ps -ef | grep "Fork Process"
* watch 'ps -ef | grep "Fork Process"'
*/
$class = get_class($process);
cli_set_process_title("Fork Process CLASS:[{$class}] - NAME:[{$name}].");
try{
$process->run();
}catch(Exception $e){
throw $e;
//echo "Executing process [$name]\r\n";
}
exit();
}
}
| <?php
require_once('Bootstrap.php');
/**
* Error logging
*
* default error log path for process "/var/log/httpd/error_log"
* to change error log path:
* ini_set('error_log', "/var/www/vhosts/dev/api-test/logs/error_log");
*/
// Get pass-in Multiprocess Object
$multiProcess = $argv[1];
$multiProcess = unserialize(base64_decode($multiProcess));
// Fork each single process contain in multiprocess
foreach( $multiProcess->getProcesses() as $name => $process ){
// Inject service manager to each process
$process->setServiceManager($sm);
// Fork process
$pid = pcntl_fork();
if($pid == -1) {
// TODO: throw exception
exit("Error forking...\n");
}
// In child process
else if($pid == 0) {
/**
* Set the Process title
* Terminal Command to check process
* ps -ef | grep "Fork Process"
* watch 'ps -ef | grep "Fork Process"'
*/
$class = get_class($process);
cli_set_process_title("Fork Process CLASS:[{$class}] - NAME:[{$name}].");
try{
$process->run();
}catch(Exception $e){
throw $e;
//echo "Executing process [$name]\r\n";
}
exit();
}
}
|
Update blueprints to support addons | module.exports = {
afterInstall: function () {
return this.addPackagesToProject([
{name: 'redux', target: '^3.4.0'},
{name: 'redux-thunk', target: '^2.0.1'}
])
.then(() => {
return this.addAddonsToProject({
packages: [
{name: 'ember-browserify', target: '^1.1.12'},
{name: 'ember-bunsen-core', target: '0.15.0'},
{name: 'ember-frost-core', target: '^1.1.3'},
{name: 'ember-frost-fields', target: '^4.0.0'},
{name: 'ember-frost-tabs', target: '^5.0.0'},
{name: 'ember-getowner-polyfill', target: '^1.0.1'},
{name: 'ember-lodash-shim', target: '^1.0.0'},
{name: 'ember-prop-types', target: '^3.0.2'},
{name: 'ember-redux', target: '^1.0.0'},
{name: 'ember-sortable', target: '^1.8.1'}
]
})
})
.then(() => {
const isAddon = this.project.isEmberCLIAddon()
const pathPrefix = isAddon ? 'tests/dummy/' : ''
return this.insertIntoFile(
`${pathPrefix}app/styles/app.scss`,
"@import './ember-frost-bunsen';"
)
})
},
normalizeEntityName: function () {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
}
}
| module.exports = {
afterInstall: function () {
return this.addPackagesToProject([
{name: 'redux', target: '^3.4.0'},
{name: 'redux-thunk', target: '^2.0.1'}
])
.then(() => {
return this.addAddonsToProject({
packages: [
{name: 'ember-browserify', target: '^1.1.12'},
{name: 'ember-bunsen-core', target: '0.15.0'},
{name: 'ember-frost-core', target: '^1.1.3'},
{name: 'ember-frost-fields', target: '^4.0.0'},
{name: 'ember-frost-tabs', target: '^5.0.0'},
{name: 'ember-getowner-polyfill', target: '^1.0.1'},
{name: 'ember-lodash-shim', target: '^1.0.0'},
{name: 'ember-prop-types', target: '^3.0.2'},
{name: 'ember-redux', target: '^1.0.0'},
{name: 'ember-sortable', target: '^1.8.1'}
]
})
})
.then(() => {
return this.insertIntoFile(
'app/styles/app.scss',
"@import './ember-frost-bunsen';"
)
})
},
normalizeEntityName: function () {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
}
}
|
Fix for vm list ordering | $(function() {
$("form :button").each(function(){
var button = $(this);
if ($(button).attr('id') == 'cancel') {
$(button).click(function(e){
e.preventDefault();
history.back();
});
}
else {
$(button).click(function(e){
var buttonId = $(button).attr('id');
if (typeof buttonId !== 'undefined') {
e.preventDefault();
var form = $(this).closest('form');
var originalActionUrl = $(form).attr('action');
if ($(form).valid()) {
if (buttonId == "plan" || buttonId == "apply") {
$('#myModal').modal('toggle');
}
var submit = true;
if (buttonId.startsWith('delete')) {
submit = confirm('Do you really want to delete this item?');
if (submit) {
$('#myModal').modal('toggle');
}
}
if (submit) {
$(form).attr('action', originalActionUrl + "/" + buttonId);
$(form).submit();
$(form).attr('action', originalActionUrl);
}
}
}
});
}
});
$('#datatable').DataTable({
responsive: true,
order: [[ 0, 'asc' ]]
});
}); | $(function() {
$("form :button").each(function(){
var button = $(this);
if ($(button).attr('id') == 'cancel') {
$(button).click(function(e){
e.preventDefault();
history.back();
});
}
else {
$(button).click(function(e){
var buttonId = $(button).attr('id');
if (typeof buttonId !== 'undefined') {
e.preventDefault();
var form = $(this).closest('form');
var originalActionUrl = $(form).attr('action');
if ($(form).valid()) {
if (buttonId == "plan" || buttonId == "apply") {
$('#myModal').modal('toggle');
}
var submit = true;
if (buttonId.startsWith('delete')) {
submit = confirm('Do you really want to delete this item?');
if (submit) {
$('#myModal').modal('toggle');
}
}
if (submit) {
$(form).attr('action', originalActionUrl + "/" + buttonId);
$(form).submit();
$(form).attr('action', originalActionUrl);
}
}
}
});
}
});
$('#datatable').DataTable({
responsive: true,
order: [[ 0, 'desc' ]]
});
}); |
Adjust saving of test taxons | <?php
namespace Tests\SitemapPlugin\Controller;
use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;
/**
* @author Stefan Doorn <[email protected]>
*/
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
/**
* @before
*/
public function setUpDatabase()
{
parent::setUpDatabase();
$root = new Taxon();
$root->setCurrentLocale('en_US');
$root->setName('Root');
$root->setCode('root');
$root->setSlug('root');
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Test');
$taxon->setCode('test-code');
$taxon->setSlug('test');
$taxon->setParent($root);
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Mock');
$taxon->setCode('mock-code');
$taxon->setSlug('mock');
$taxon->setParent($root);
$this->getEntityManager()->persist($root);
$this->getEntityManager()->flush();
}
public function testShowActionResponse()
{
$this->client->request('GET', '/sitemap/taxons.xml');
$response = $this->client->getResponse();
$this->assertResponse($response, 'show_sitemap_taxons');
}
}
| <?php
namespace Tests\SitemapPlugin\Controller;
use Lakion\ApiTestCase\XmlApiTestCase;
use Sylius\Component\Core\Model\Product;
use Sylius\Component\Core\Model\Taxon;
/**
* @author Stefan Doorn <[email protected]>
*/
class SitemapTaxonControllerApiTest extends XmlApiTestCase
{
/**
* @before
*/
public function setUpDatabase()
{
parent::setUpDatabase();
$root = new Taxon();
$root->setCurrentLocale('en_US');
$root->setName('Root');
$root->setCode('root');
$root->setSlug('root');
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Test');
$taxon->setCode('test-code');
$taxon->setSlug('test');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$taxon = new Taxon();
$taxon->setCurrentLocale('en_US');
$taxon->setName('Mock');
$taxon->setCode('mock-code');
$taxon->setSlug('mock');
$taxon->setParent($root);
$this->getEntityManager()->persist($taxon);
$this->getEntityManager()->persist($root);
$this->getEntityManager()->flush();
}
public function testShowActionResponse()
{
$this->client->request('GET', '/sitemap/taxons.xml');
$response = $this->client->getResponse();
$this->assertResponse($response, 'show_sitemap_taxons');
}
}
|
Fix length problem in test. | package net.simplestorage.storage.impl.indexed;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import static org.junit.Assert.assertEquals;
public class IndexedStorageFileTest {
private IndexedStorageFile storageFile;
private File testFile;
@Before
public void setUp() throws URISyntaxException, IOException {
testFile = new File(ExistingIndexedStorageIntegrationTest.class.getResource("testIndexFile.txt").toURI());
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(testFile));
stream.write("test001test002".toString().getBytes("UTF-8"));
stream.close();
storageFile = new IndexedStorageFile(testFile.getAbsolutePath());
}
@After
public void tearDown() {
testFile.delete();
}
@Test
public void testRead() throws Exception {
String data = storageFile.read(0,7);
assertEquals("test001", data);
data = storageFile.read(7,7);
assertEquals("test002", data);
}
@Test
public void testWrite() throws Exception {
assertEquals(14,storageFile.length());
storageFile.write("test003", 14);
assertEquals(21,storageFile.length());
storageFile.clear(14,7);
}
@Test
public void testAppend() throws Exception {
assertEquals(14,storageFile.length());
storageFile.append("test003");
assertEquals(21,storageFile.length());
storageFile.clear(14,7);
}
} | package net.simplestorage.storage.impl.indexed;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import static org.junit.Assert.*;
public class IndexedStorageFileTest {
private IndexedStorageFile storageFile;
@Before
public void setUp() throws URISyntaxException, FileNotFoundException {
File testFile = new File(ExistingIndexedStorageIntegrationTest.class.getResource("testIndexFile.txt").toURI());
storageFile = new IndexedStorageFile(testFile.getAbsolutePath());
}
@Test
public void testRead() throws Exception {
String data = storageFile.read(0,7);
assertEquals("test001", data);
data = storageFile.read(7,7);
assertEquals("test002", data);
}
@Test
public void testWrite() throws Exception {
assertEquals(14,storageFile.length());
storageFile.write("test003", 14);
assertEquals(21,storageFile.length());
storageFile.clear(14,7);
}
@Test
public void testAppend() throws Exception {
assertEquals(14,storageFile.length());
storageFile.append("test003");
assertEquals(21,storageFile.length());
storageFile.clear(14,7);
}
@Test
public void testClear() throws Exception {
}
} |
Rename transpile label to transpile-app | var
gulp = require('gulp'),
babel = require('gulp-babel'),
watch = require('gulp-watch'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
rename = require('gulp-rename');
// Transpile ES6 app to ES5 using babel
gulp.task('transpile-app', function () {
return gulp.src('app/main.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Pipe the file into babel
.pipe(uglify()) // Pipe the file into babel
.pipe(rename('main.dist.js')) // rename to main.js
.pipe(gulp.dest('app')) // Save it in the same directory
});
// Transpile general ES6 javascripts
gulp.task('transpile-scripts', function () {
return gulp.src('browser/src/es6-js/**.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Babel ES5 -> ES6
.pipe(uglify()) // uglify
.pipe(rename(function (path) { // Rename files so .es6.js -> .js
path.basename = path.basename.replace('.es6', '');
}))
.pipe(gulp.dest('browser/build/js'))
});
gulp.task('default', ['transpile-app'])
| var
gulp = require('gulp'),
babel = require('gulp-babel'),
watch = require('gulp-watch'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
rename = require('gulp-rename');
// Transpile ES6 app to ES5 using babel
gulp.task('transpile', function () {
return gulp.src('app/main.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Pipe the file into babel
.pipe(uglify()) // Pipe the file into babel
.pipe(rename('main.dist.js')) // rename to main.js
.pipe(gulp.dest('app')) // Save it in the same directory
});
// Transpile general ES6 javascripts
gulp.task('transpile-scripts', function () {
return gulp.src('browser/src/es6-js/**.es6.js')
.pipe(strip()) // Strip comments
.pipe(babel()) // Babel ES5 -> ES6
.pipe(uglify()) // uglify
.pipe(rename(function (path) { // Rename files so .es6.js -> .js
path.basename = path.basename.replace('.es6', '');
}))
.pipe(gulp.dest('browser/build/js'))
});
gulp.task('default', ['transpile'])
|
Remove a blank line, because. | package org.wildfly.swarm.examples.messaging;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSDeployment;
import org.wildfly.swarm.messaging.MessagingFraction;
import org.wildfly.swarm.messaging.MessagingServer;
import org.wildfly.swarm.msc.ServiceActivatorDeployment;
/**
* @author Bob McWhirter
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
container.subsystem(new MessagingFraction()
.server(
new MessagingServer()
.enableInVMConnector()
.topic("my-topic")
.queue("my-queue")
)
);
// Start the container
container.start();
JAXRSDeployment appDeployment = new JAXRSDeployment(container);
appDeployment.addResource(MyResource.class);
// Deploy your app
container.deploy(appDeployment);
ServiceActivatorDeployment deployment = new ServiceActivatorDeployment(container);
deployment.addServiceActivator( MyServiceActivator.class );
deployment.addClass( MyService.class );
// Deploy the services
container.deploy( deployment );
}
}
| package org.wildfly.swarm.examples.messaging;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSDeployment;
import org.wildfly.swarm.messaging.MessagingFraction;
import org.wildfly.swarm.messaging.MessagingServer;
import org.wildfly.swarm.msc.ServiceActivatorDeployment;
/**
* @author Bob McWhirter
*/
public class Main {
public static void main(String[] args) throws Exception {
Container container = new Container();
container.subsystem(new MessagingFraction()
.server(
new MessagingServer()
.enableInVMConnector()
.topic("my-topic")
.queue("my-queue")
)
);
// Start the container
container.start();
JAXRSDeployment appDeployment = new JAXRSDeployment(container);
appDeployment.addResource(MyResource.class);
// Deploy your app
container.deploy(appDeployment);
ServiceActivatorDeployment deployment = new ServiceActivatorDeployment(container);
deployment.addServiceActivator( MyServiceActivator.class );
deployment.addClass( MyService.class );
// Deploy the services
container.deploy( deployment );
}
}
|
Initialize random sequence of words when starting training, so that words do not repeat | import logging
import random
DIRECT = 'direct'
REVERSE = 'reverse'
LOG = logging.getLogger(__name__)
class Trainer:
def __init__(self, store, kind=DIRECT):
self.store = store
if kind == DIRECT:
self._words = list(store.direct_index.items())
self._plugin = store.meaning_plugin
elif kind == REVERSE:
self._words = list(store.reverse_index.items())
self._plugin = store.original_plugin
else:
raise ValueError("Expected kind, got %r", kind)
self.challenge = self.answer = None
self._init()
def check(self, answer):
converted = self._plugin.convert_word(answer.strip())
if converted != self.answer:
LOG.info("'%(converted)s' (converted from '%(answer)s') "
"is incorrect",
locals())
return False
else:
LOG.debug("%s is accepted", converted)
return True
def next(self):
assert len(self._words) != 0
try:
self.challenge, self.answer = self._words[self._ptr]
except IndexError:
LOG.info("All words finished, starting from the beginning")
self._init()
return self.next()
else:
self._ptr += 1
LOG.debug("Next challenge is '%s'", self.challenge)
return self.challenge
def _init(self):
self._ptr = 0
random.shuffle(self._words)
| import logging
import random
DIRECT = 'direct'
REVERSE = 'reverse'
LOG = logging.getLogger(__name__)
class Trainer:
def __init__(self, store, kind=DIRECT):
self.store = store
if kind == DIRECT:
self._words = list(store.direct_index.items())
self._plugin = store.meaning_plugin
elif kind == REVERSE:
self._words = list(store.reverse_index.items())
self._plugin = store.original_plugin
else:
raise ValueError("Expected kind, got %r", kind)
self.challenge = self.answer = None
def check(self, answer):
converted = self._plugin.convert_word(answer.strip())
if converted != self.answer:
LOG.info("'%(converted)s' (converted from '%(answer)s') "
"is incorrect",
locals())
return False
else:
LOG.debug("%s is accepted", converted)
return True
def next(self):
self.challenge, self.answer = random.choice(self._words)
LOG.debug("Next challenge is '%s'", self.challenge)
return self.challenge
|
Add missing coma (jshint fix) | var fs = require('fs');
var css = fs.readFileSync(__dirname + '/cache/bootstrap.css').toString();
var CSSOM = require('cssom');
var postcss = require('../build');
var rework = require('rework');
var stylecow = require('stylecow');
var gonzales = require('gonzales');
var gonzalesPe = require('gonzales-pe');
module.exports = {
name: 'Bootstrap',
maxTime: 15,
tests: [
{
name: 'PostCSS',
fn: function() {
return postcss.parse(css).toResult().css;
}
},
{
name: 'CSSOM',
fn: function() {
return CSSOM.parse(css).toString();
}
},
{
name: 'Rework',
fn: function() {
return rework(css).toString();
}
},
{
name: 'Stylecow',
fn: function() {
return stylecow.create(css).toString();
}
},
{
name: 'Gonzales',
fn: function() {
return gonzales.csspToSrc( gonzales.srcToCSSP(css) );
}
},
{
name: 'Gonzales PE',
fn: function() {
return gonzalesPe.astToSrc({
ast: gonzalesPe.srcToAST({ src: css })
});
}
},
]
};
| var fs = require('fs');
var css = fs.readFileSync(__dirname + '/cache/bootstrap.css').toString();
var CSSOM = require('cssom');
var postcss = require('../build');
var rework = require('rework');
var stylecow = require('stylecow');
var gonzales = require('gonzales');
var gonzalesPe = require('gonzales-pe');
module.exports = {
name: 'Bootstrap',
maxTime: 15,
tests: [
{
name: 'PostCSS',
fn: function() {
return postcss.parse(css).toResult().css;
}
},
{
name: 'CSSOM',
fn: function() {
return CSSOM.parse(css).toString();
}
},
{
name: 'Rework',
fn: function() {
return rework(css).toString();
}
},
{
name: 'Stylecow',
fn: function() {
return stylecow.create(css).toString()
}
},
{
name: 'Gonzales',
fn: function() {
return gonzales.csspToSrc( gonzales.srcToCSSP(css) );
}
},
{
name: 'Gonzales PE',
fn: function() {
return gonzalesPe.astToSrc({
ast: gonzalesPe.srcToAST({ src: css })
});
}
},
]
};
|
Use to_playlist in the playlist provider | from __future__ import unicode_literals
import logging
from mopidy import backend
import spotify
from mopidy_spotify import translator
logger = logging.getLogger(__name__)
class SpotifyPlaylistsProvider(backend.PlaylistsProvider):
def __init__(self, backend):
self._backend = backend
def create(self, name):
pass # TODO
def delete(self, uri):
pass # TODO
def lookup(self, uri):
pass # TODO
@property
def playlists(self):
# XXX We should just return light-weight Ref objects here, but Mopidy's
# core and backend APIs must be changed first.
if self._backend._session.playlist_container is None:
return []
result = []
folders = []
for sp_playlist in self._backend._session.playlist_container:
if isinstance(sp_playlist, spotify.PlaylistFolder):
if sp_playlist.type is spotify.PlaylistType.START_FOLDER:
folders.append(sp_playlist.name)
elif sp_playlist.type is spotify.PlaylistType.END_FOLDER:
folders.pop()
continue
playlist = translator.to_playlist(sp_playlist, folders=folders)
if playlist is not None:
result.append(playlist)
# TODO Add starred playlist
return result
def refresh(self):
pass # TODO
def save(self, playlist):
pass # TODO
| from __future__ import unicode_literals
import logging
from mopidy import backend, models
import spotify
from mopidy_spotify import translator
logger = logging.getLogger(__name__)
class SpotifyPlaylistsProvider(backend.PlaylistsProvider):
def __init__(self, backend):
self._backend = backend
def create(self, name):
pass # TODO
def delete(self, uri):
pass # TODO
def lookup(self, uri):
pass # TODO
@property
def playlists(self):
# XXX We should just return light-weight Ref objects here, but Mopidy's
# core and backend APIs must be changed first.
if self._backend._session.playlist_container is None:
return []
result = []
folder = []
for sp_playlist in self._backend._session.playlist_container:
if isinstance(sp_playlist, spotify.PlaylistFolder):
if sp_playlist.type is spotify.PlaylistType.START_FOLDER:
folder.append(sp_playlist.name)
elif sp_playlist.type is spotify.PlaylistType.END_FOLDER:
folder.pop()
continue
if not sp_playlist.is_loaded:
continue
name = '/'.join(folder + [sp_playlist.name])
# TODO Add "by <playlist owner>" to name
tracks = [
translator.to_track(sp_track)
for sp_track in sp_playlist.tracks
]
tracks = filter(None, tracks)
playlist = models.Playlist(
uri=sp_playlist.link.uri,
name=name,
tracks=tracks)
result.append(playlist)
# TODO Add starred playlist
return result
def refresh(self):
pass # TODO
def save(self, playlist):
pass # TODO
|
Improve error logging in uglify worker | var uglify;
try {
uglify = require('uglify-js');
} catch (err) { /* NOP */ }
process.on('message', function(msg) {
var outputFile = msg.output,
data = msg.data,
sourceMap = msg.sourceMap,
warnings = [];
try {
var warnFunction;
try {
warnFunction = uglify.AST_Node.warn_function;
uglify.AST_Node.warn_function = function(msg) {
warnings.push(msg);
};
var ast = uglify.parse(data),
compressor = uglify.Compressor(),
outputOptions = {};
if (sourceMap) {
sourceMap = uglify.SourceMap({
file: outputFile,
orig: sourceMap
});
outputOptions.source_map = sourceMap;
}
ast.figure_out_scope();
ast = ast.transform(compressor);
ast.figure_out_scope();
ast.compute_char_frequency();
ast.mangle_names();
data = ast.print_to_string(outputOptions);
process.send({
data: {
data: data,
warnings: warnings,
sourceMap: sourceMap && sourceMap.toString()
}
});
} finally {
uglify.AST_Node.warn_function = warnFunction;
}
} catch (err) {
process.send({err: err.stack || err.msg || err.toString()});
}
});
| var uglify;
try {
uglify = require('uglify-js');
} catch (err) { /* NOP */ }
process.on('message', function(msg) {
var outputFile = msg.output,
data = msg.data,
sourceMap = msg.sourceMap,
warnings = [];
try {
var warnFunction;
try {
warnFunction = uglify.AST_Node.warn_function;
uglify.AST_Node.warn_function = function(msg) {
warnings.push(msg);
};
var ast = uglify.parse(data),
compressor = uglify.Compressor(),
outputOptions = {};
if (sourceMap) {
sourceMap = uglify.SourceMap({
file: outputFile,
orig: sourceMap
});
outputOptions.source_map = sourceMap;
}
ast.figure_out_scope();
ast = ast.transform(compressor);
ast.figure_out_scope();
ast.compute_char_frequency();
ast.mangle_names();
data = ast.print_to_string(outputOptions);
process.send({
data: {
data: data,
warnings: warnings,
sourceMap: sourceMap && sourceMap.toString()
}
});
} finally {
uglify.AST_Node.warn_function = warnFunction;
}
} catch (err) {
process.send({err: err.toString()});
}
});
|
Fix button misfires on mobile | import React, { Component } from 'react';
import _ from 'lodash';
import styles from './css/Button.module.css';
export default class Button extends Component {
static propTypes = {
onClick: React.PropTypes.func.isRequired,
disabled: React.PropTypes.bool
}
constructor (props) {
super(props);
this.onClick = _.debounce(this.props.onClick, 500, {
leading: true,
trailing: false
});
this.state = {
active: false
};
}
render () {
return (
<button
onTouchStart={() => { this.setState({ active: true }); }}
onTouchEnd={() => {
this.onClick();
this.setState({ active: false });
}}
onClick={this.onClick}
className={styles.wrapper}
disabled={this.props.disabled}
>
<span className={(this.state.active) ? styles.raisedActive : styles.raised}>
<span className={styles.button}>{this.props.children}</span>
</span>
</button>
);
}
};
| import React, { Component } from 'react';
import _ from 'lodash';
import styles from './css/Button.module.css';
export default class Button extends Component {
static propTypes = {
onClick: React.PropTypes.func.isRequired,
disabled: React.PropTypes.bool
}
constructor (props) {
super(props);
this.onClick = _.debounce(this.props.onClick, 500, {
leading: true,
trailing: false
});
this.state = {
active: false
};
}
render () {
return (
<button
onTouchStart={() => { this.setState({ active: true }); }}
onTouchEnd={() => { this.setState({ active: false }, this.onClick); }}
onClick={this.onClick}
className={styles.wrapper}
disabled={this.props.disabled}
>
<span className={(this.state.active) ? styles.raisedActive : styles.raised}>
<span className={styles.button}>{this.props.children}</span>
</span>
</button>
);
}
};
|
FEAT: Use bulk operation in migration script for performance | const mongoModel = require('./mongo-model');
const sqlModel = require('./sql-model');
function main() {
sqlModel.sequelize.sync()
.then(() => mongoModel.find({}))
.then(users => {
console.log('MongoDB query done. Length: ', users.length);
let promises = [];
for (let user of users) {
let userReq = sqlModel.User.create({
refreshToken: user.tokens.refresh_token,
accessToken: user.tokens.access_token,
googleID: user.googleId,
renewEnabled: user.renewEnabled,
libraryLogin: user.libraryLogin,
libraryPassword: user.libraryPassword,
renewDate: user.renewDate,
calendarEnabled: user.calendarEnabled,
calendarName: user.calendarName,
emailEnabled: user.emailEnabled,
emailAddress: user.emailAddress,
isAdmin: user.isAdmin
});
let logReq = sqlModel.Logs.bulkCreate(user.logs.map(log => {
return {
userID: user.googleId,
time: log.time,
message: log.message,
level: log.level
}
}));
promises.push(userReq);
promises.push(logReq);
}
return Promise.all(promises);
})
.then(() => {
console.log('Done');
process.exit(0);
});
}
main(); | const mongoModel = require('./mongo-model');
const sqlModel = require('./sql-model');
function main() {
sqlModel.sequelize.sync()
.then(() => mongoModel.find({}))
.then(users => {
console.log('MongoDB query done. Length: ', users.length);
let promises = [];
for (let user of users) {
promises.push(sqlModel.User.create({
refreshToken: user.tokens.refresh_token,
accessToken: user.tokens.access_token,
googleID: user.googleId,
renewEnabled: user.renewEnabled,
libraryLogin: user.libraryLogin,
libraryPassword: user.libraryPassword,
renewDate: user.renewDate,
calendarEnabled: user.calendarEnabled,
calendarName: user.calendarName,
emailEnabled: user.emailEnabled,
emailAddress: user.emailAddress,
isAdmin: user.isAdmin
}));
promises.push(user.logs.map(log => {
return sqlModel.Logs.create({
userID: user.googleId,
time: log.time,
message: log.message,
level: log.level
})
}));
}
return Promise.all(promises);
})
.then(() => {
console.log('Done');
process.exit(0);
});
}
main(); |
Convert list member addresses to non-unicode strings when possible. | from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',
'ccErrors',
'reports',
'vacation',
'ackPost',
'echoPost',
'hidden',
])
def member_flag_representer(dumper, data):
return dumper.represent_scalar(u'!flag', data.name)
yaml.add_representer(MemberFlag, member_flag_representer)
def member_flag_constructor(loader, node):
value = loader.construct_scalar(node)
return MemberFlag[value]
yaml.SafeLoader.add_constructor(u'!flag', member_flag_constructor)
class ListMember(yaml.YAMLObject):
yaml_tag = u'!Member'
yaml_loader = yaml.SafeLoader
def __init__(self, address, *args, **kwargs):
if isinstance(address, unicode):
# Attempt to down-convert unicode-string addresses to plain strings
try:
address = str(address)
except UnicodeEncodeError:
pass
self.address = address
self.flags = set(a for a in args if isinstance(a, MemberFlag))
def __repr__(self):
return u'{}({}, flags: {})'.format(
self.__class__.__name__,
self.address,
', '.join(
map(lambda f: f.name,
self.flags)
),
)
| from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',
'ccErrors',
'reports',
'vacation',
'ackPost',
'echoPost',
'hidden',
])
def member_flag_representer(dumper, data):
return dumper.represent_scalar(u'!flag', data.name)
yaml.add_representer(MemberFlag, member_flag_representer)
def member_flag_constructor(loader, node):
value = loader.construct_scalar(node)
return MemberFlag[value]
yaml.SafeLoader.add_constructor(u'!flag', member_flag_constructor)
class ListMember(yaml.YAMLObject):
yaml_tag = u'!Member'
yaml_loader = yaml.SafeLoader
def __init__(self, address, *args, **kwargs):
self.address = address
self.flags = set(a for a in args if isinstance(a, MemberFlag))
def __repr__(self):
return u'{}({}, flags: {})'.format(
self.__class__.__name__,
self.address,
', '.join(
map(lambda f: f.name,
self.flags)
),
)
|
Correct status output text for Make Map | const webModel = require('../webModel');
const webModelFunctions = require('../webModelFunctions');
const robotModel = require('../robotModel');
async function makeMap() {
if (webModel.debugging) {
console.log('Make Map');
webModelFunctions.scrollingStatusUpdate('Make Map');
}
if (robotModel.makeMap.started) {
if (robotModel.makeMap.startupComplete) {
if (robotModel.makeMap.hasExited) {
webModelFunctions.update('status', 'Make Map process is closed.');
webModelFunctions.update('makeMapRunning', false);
webModelFunctions.update('makeMap', false);
robotModel.makeMap.started = false;
webModelFunctions.behaviorStatusUpdate('Make Map: FAILURE');
return false;
} else {
webModelFunctions.update('status', 'Make Map process started.');
webModelFunctions.update('makeMapRunning', true);
if (webModel.pluggedIn) {
webModelFunctions.behaviorStatusUpdate('Make Map: Robot is still plugged in!');
} else {
webModelFunctions.behaviorStatusUpdate('Make Map: Robot is ready to make a map.');
}
return true;
}
} else {
webModelFunctions.update('status', 'Make Map is starting...');
return false;
}
} else {
robotModel.makeMap.start();
webModelFunctions.behaviorStatusUpdate('Make Map');
return false;
}
}
module.exports = makeMap;
| const webModel = require('../webModel');
const webModelFunctions = require('../webModelFunctions');
const robotModel = require('../robotModel');
async function makeMap() {
if (webModel.debugging) {
console.log('Make Map');
webModelFunctions.scrollingStatusUpdate('Make Map');
}
if (robotModel.makeMap.started) {
if (robotModel.makeMap.startupComplete) {
if (robotModel.makeMap.hasExited) {
webModelFunctions.update('status', 'Make Map process is closed.');
webModelFunctions.update('makeMapRunning', false);
webModelFunctions.update('makeMap', false);
robotModel.makeMap.started = false;
webModelFunctions.behaviorStatusUpdate('Make Map: FAILURE');
return false;
} else {
webModelFunctions.update('status', 'Make Map process started.');
webModelFunctions.update('makeMapRunning', true);
if (webModel.pluggedIn) {
webModelFunctions.behaviorStatusUpdate('Make Map: Robot is still plugged in!');
} else {
webModelFunctions.behaviorStatusUpdate('Make Map: Robot is ready to make a map.');
}
return true;
}
} else {
webModelFunctions.update('status', 'Explore process is starting...');
return false;
}
} else {
robotModel.makeMap.start();
webModelFunctions.behaviorStatusUpdate('Make Map');
return false;
}
}
module.exports = makeMap;
|
Add getter and setter for Patient attribute | package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
}
| package org.pdxfinder.dao;
import java.util.HashSet;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
/**
* Created by jmason on 16/03/2017.
*/
@NodeEntity
public class PatientSnapshot {
@GraphId
Long id;
Patient patient;
String age;
@Relationship(type = "SAMPLED_FROM", direction = Relationship.OUTGOING)
Set<Sample> samples;
public PatientSnapshot() {
}
public PatientSnapshot(Patient patient, String age) {
this.patient = patient;
this.age = age;
}
public PatientSnapshot(Patient patient, String age, Set<Sample> samples) {
this.patient = patient;
this.age = age;
this.samples = samples;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Set<Sample> getSamples() {
return samples;
}
public void setSamples(Set<Sample> samples) {
this.samples = samples;
}
public void addSample(Sample sample){
if(this.samples == null){
this.samples = new HashSet<Sample>();
}
this.samples.add(sample);
}
}
|
Revert "hide worker and coordinator"
This reverts commit f73ce955ef6a2562f75f3311de279d43566dba08. | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
name = 'Mikko Korpela'
# I might be just a little bit too much afraid of those bots..
address = name.lower().replace(' ', '.')+chr(64)+'gmail.com'
setup(name='robotframework-pabot',
version='1.2.1',
description='Parallel test runner for Robot Framework',
long_description='A parallel executor for Robot Framework tests.'
' With Pabot you can split one execution into multiple and save test execution time.',
author=name,
author_email=address,
url='https://pabot.org',
download_url='https://pypi.python.org/pypi/robotframework-pabot',
packages=find_packages(),
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Testing',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Framework :: Robot Framework'
],
entry_points = {'console_scripts': [
'pabot=pabot.pabot:main',
'pabotcoordinator=pabot.coordinatorwrapper:main',
'pabotworker=pabot.workerwrapper:main']},
license='Apache License, Version 2.0',
install_requires=[
'robotframework',
'websockets>=8.1;python_version>="3.6"',
'robotremoteserver>=1.1',
'typing;python_version<"3.5"'])
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
name = 'Mikko Korpela'
# I might be just a little bit too much afraid of those bots..
address = name.lower().replace(' ', '.')+chr(64)+'gmail.com'
setup(name='robotframework-pabot',
version='1.2.1',
description='Parallel test runner for Robot Framework',
long_description='A parallel executor for Robot Framework tests.'
' With Pabot you can split one execution into multiple and save test execution time.',
author=name,
author_email=address,
url='https://pabot.org',
download_url='https://pypi.python.org/pypi/robotframework-pabot',
packages=find_packages(),
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Testing',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Framework :: Robot Framework'
],
entry_points = {'console_scripts': [
'pabot=pabot.pabot:main']},
license='Apache License, Version 2.0',
install_requires=[
'robotframework',
'websockets>=8.1;python_version>="3.6"',
'robotremoteserver>=1.1',
'typing;python_version<"3.5"'])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.