text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Remove confusing and useless "\n" | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main server script for a pyqode.python backend. You can directly use this
script in your application if it fits your needs or use it as a starting point
for writing your own server.
::
usage: server.py [-h] [-s [SYSPATH [SYSPATH ...]]] port
positional arguments:
port the local tcp port to use to run the server
optional arguments:
-h, --help show this help message and exit
-s [SYSPATH [SYSPATH ...]], --syspath [SYSPATH [SYSPATH ...]]
"""
import argparse
import sys
if __name__ == '__main__':
"""
Server process' entry point
"""
# setup argument parser and parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("port", help="the local tcp port to use to run "
"the server")
parser.add_argument('-s', '--syspath', nargs='*')
args = parser.parse_args()
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
print('append path %s to sys.path' % path)
sys.path.append(path)
from pyqode.core import backend
from pyqode.python.backend.workers import JediCompletionProvider
# setup completion providers
backend.CodeCompletionWorker.providers.append(JediCompletionProvider())
backend.CodeCompletionWorker.providers.append(
backend.DocumentWordsProvider())
# starts the server
backend.serve_forever(args)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main server script for a pyqode.python backend. You can directly use this
script in your application if it fits your needs or use it as a starting point
for writing your own server.
::
usage: server.py [-h] [-s [SYSPATH [SYSPATH ...]]] port
positional arguments:
port the local tcp port to use to run the server
optional arguments:
-h, --help show this help message and exit
-s [SYSPATH [SYSPATH ...]], --syspath [SYSPATH [SYSPATH ...]]
"""
import argparse
import sys
if __name__ == '__main__':
"""
Server process' entry point
"""
# setup argument parser and parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("port", help="the local tcp port to use to run "
"the server")
parser.add_argument('-s', '--syspath', nargs='*')
args = parser.parse_args()
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
print('append path %s to sys.path\n' % path)
sys.path.append(path)
from pyqode.core import backend
from pyqode.python.backend.workers import JediCompletionProvider
# setup completion providers
backend.CodeCompletionWorker.providers.append(JediCompletionProvider())
backend.CodeCompletionWorker.providers.append(
backend.DocumentWordsProvider())
# starts the server
backend.serve_forever(args)
|
Trim resolutions so they are a factor of 2.
Currently ol3 appears to be assuming that resolutions are always a
factor of 2, need to look into it more. | // Extent of the map in units of the projection
var extent = [-3276800, -3276800, 3276800, 3276800];
// Fixed resolutions to display the map at
var resolutions = [1600, 800, 400, 200, 100, 50, 25];
// Basic ol3 Projection definition, include the extent here and specify the
// resolutions as a property of the View2D or TileWMS if you are using a tiled
// WMS to ensure tiles are requested at the correct boundaries
var projection = new ol.proj.Projection({
code: 'EPSG:27700',
units: 'm',
extent: extent
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://t0.ads.astuntechnology.com/astuntechnology/osopen/service?',
attributions: [
new ol.Attribution({html: 'OS OpenData, © Ordnance Survey'})
],
params: {
'LAYERS': 'osopen',
'FORMAT': 'image/png',
'TILED': true
}
})
})
],
view: new ol.View2D({
projection: projection,
resolutions: resolutions,
center: [315000, 468000],
zoom: 0
})
});
| // Extent of the map in units of the projection
var extent = [-3276800, -3276800, 3276800, 3276800];
// Fixed resolutions to display the map at
var resolutions = [1600, 800, 400, 200, 100, 50, 25, 10, 5, 2.5, 1, 0.5];
// Basic ol3 Projection definition, include the extent here and specify the
// resolutions as a property of the View2D or TileWMS if you are using a tiled
// WMS to ensure tiles are requested at the correct boundaries
var projection = new ol.proj.Projection({
code: 'EPSG:27700',
units: 'm',
extent: extent
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://t0.ads.astuntechnology.com/astuntechnology/osopen/service?',
attributions: [
new ol.Attribution({html: 'OS OpenData, © Ordnance Survey'})
],
params: {
'LAYERS': 'osopen',
'FORMAT': 'image/png',
'TILED': true
}
})
})
],
view: new ol.View2D({
projection: projection,
resolutions: resolutions,
center: [315000, 468000],
zoom: 0
})
});
|
ZON-3409: Update to version with celery. | from setuptools import setup, find_packages
setup(
name='zeit.wysiwyg',
version='2.0.8.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description="vivi legacy WYSIWYG editor",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'gocept.fckeditor[fanstatic]>=2.6.4.1-2',
'lxml',
'pytz',
'rwproperty',
'setuptools',
'zc.iso8601',
'zc.resourcelibrary',
'zeit.cms >= 3.0.dev0',
'zeit.content.image>=2.13.6.dev0',
'zope.app.pagetemplate',
'zope.app.testing',
'zope.cachedescriptors',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.security',
'zope.testing',
'zope.traversing',
],
extras_require=dict(test=[
'zeit.content.gallery',
'zeit.content.infobox',
'zeit.content.portraitbox',
]),
entry_points={
'fanstatic.libraries': [
'zeit_wysiwyg=zeit.wysiwyg.browser.resources:lib',
],
},
)
| from setuptools import setup, find_packages
setup(
name='zeit.wysiwyg',
version='2.0.8.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description="vivi legacy WYSIWYG editor",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'gocept.fckeditor[fanstatic]>=2.6.4.1-2',
'lxml',
'pytz',
'rwproperty',
'setuptools',
'zc.iso8601',
'zc.resourcelibrary',
'zeit.cms>=2.93.dev0',
'zeit.content.image>=2.13.6.dev0',
'zope.app.pagetemplate',
'zope.app.testing',
'zope.cachedescriptors',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.security',
'zope.testing',
'zope.traversing',
],
extras_require=dict(test=[
'zeit.content.gallery',
'zeit.content.infobox',
'zeit.content.portraitbox',
]),
entry_points={
'fanstatic.libraries': [
'zeit_wysiwyg=zeit.wysiwyg.browser.resources:lib',
],
},
)
|
Remove reference to dashboard services. | define(
[
"angular",
"./dataset-list-controllers",
"./dataset-list-services"
],
function (angular, controllers) {
"use strict";
var datasetListRoutes = angular.module("datasetList.routes", ["narthex.common"]);
datasetListRoutes.config(
[
"$routeProvider", "userResolve",
function ($routeProvider, userResolve) {
$routeProvider.when(
"/", {
templateUrl: "/narthex/assets/templates/dataset-list.html",
controller: controllers.DatasetListCtrl,
resolve: userResolve,
reloadOnSearch: false
}
);
}
]
);
var narthexDatasetList = angular.module("narthex.datasetList", [
"ngRoute",
"datasetList.routes",
"datasetList.services",
"narthex.common"
]);
narthexDatasetList.controller('DatasetEntryCtrl', controllers.DatasetEntryCtrl);
var config = function config($rootScopeProvider) {
$rootScopeProvider.digestTtl(15);
};
config.$inject = ['$rootScopeProvider'];
narthexDatasetList.config(config);
return narthexDatasetList;
});
| define(
[
"angular",
"./dataset-list-controllers",
"./dataset-list-services"
],
function (angular, controllers) {
"use strict";
var datasetListRoutes = angular.module("datasetList.routes", ["narthex.common", "dashboard.services"]);
datasetListRoutes.config(
[
"$routeProvider", "userResolve",
function ($routeProvider, userResolve) {
$routeProvider.when(
"/", {
templateUrl: "/narthex/assets/templates/dataset-list.html",
controller: controllers.DatasetListCtrl,
resolve: userResolve,
reloadOnSearch: false
}
);
}
]
);
var narthexDatasetList = angular.module("narthex.datasetList", [
"ngRoute",
"datasetList.routes",
"datasetList.services",
"narthex.common"
]);
narthexDatasetList.controller('DatasetEntryCtrl', controllers.DatasetEntryCtrl);
var config = function config($rootScopeProvider) {
$rootScopeProvider.digestTtl(15);
};
config.$inject = ['$rootScopeProvider'];
narthexDatasetList.config(config);
return narthexDatasetList;
});
|
Work around for watchdog problem on OS X. | import sys
# FSEvents observer in watchdog cannot have multiple watchers of the same path
# use kqueue instead
if sys.platform == 'darwin':
from watchdog.observers.kqueue import KqueueObserver as Observer
else:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import time
class MyEventHandler(FileSystemEventHandler):
def __init__(self, filePath, callback):
super(MyEventHandler, self).__init__()
self.filePath = filePath
self.callback = callback
self.paused = True
def on_modified(self, event):
if os.path.normpath(event.src_path) == self.filePath:
if not self.paused:
"""
Hold off for half a second
If the event is from the file being opened to be written this gives
time for it to be written.
"""
time.sleep(0.5)
self.callback()
class LibraryFileWatcher(object):
def __init__(self, filePath, callback):
super(LibraryFileWatcher, self).__init__()
self.filePath = os.path.normpath(filePath)
self.callback = callback
self.eventHandler = MyEventHandler(self.filePath, callback)
self.observer = Observer()
self.watch = self.observer.schedule(self.eventHandler, path=os.path.dirname(self.filePath))
self.observer.start()
self.resume()
def __del__(self):
self.observer.stop()
self.observer.join()
def pause(self):
self.eventHandler.paused = True
def resume(self):
self.eventHandler.paused = False | from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import time
class MyEventHandler(FileSystemEventHandler):
def __init__(self, filePath, callback):
super(MyEventHandler, self).__init__()
self.filePath = filePath
self.callback = callback
self.paused = True
def on_modified(self, event):
if os.path.normpath(event.src_path) == self.filePath:
if not self.paused:
"""
Hold off for half a second
If the event is from the file being opened to be written this gives
time for it to be written.
"""
time.sleep(0.5)
self.callback()
class LibraryFileWatcher(object):
def __init__(self, filePath, callback):
super(LibraryFileWatcher, self).__init__()
self.filePath = os.path.normpath(filePath)
self.callback = callback
self.eventHandler = MyEventHandler(self.filePath, callback)
self.observer = Observer()
self.watch = self.observer.schedule(self.eventHandler, path=os.path.dirname(self.filePath))
self.observer.start()
self.resume()
def __del__(self):
self.observer.stop()
self.observer.join()
def pause(self):
self.eventHandler.paused = True
def resume(self):
self.eventHandler.paused = False |
Implement web assets in the twig function | <?php
declare(strict_types=1);
/**
* Copyright (c) 2013-2017 OpenCFP
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/opencfp/opencfp
*/
namespace OpenCFP\Infrastructure\Templating;
use OpenCFP\PathInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig_Extension;
use Twig_SimpleFunction;
class TwigExtension extends Twig_Extension
{
/**
* @var RequestStack
*/
private $requestStack;
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* @var PathInterface
*/
private $path;
public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path)
{
$this->requestStack = $requestStack;
$this->urlGenerator = $urlGenerator;
$this->path = $path;
}
public function getFunctions()
{
return [
new Twig_SimpleFunction('uploads', function ($path) {
return $this->path->downloadFromPath() . $path;
}),
new Twig_SimpleFunction('assets', function ($path) {
return $this->path->webAssetsPath() . $path;
}),
new Twig_SimpleFunction('active', function ($route) {
return $this->urlGenerator->generate($route)
=== $this->requestStack->getCurrentRequest()->getRequestUri();
}),
];
}
}
| <?php
declare(strict_types=1);
/**
* Copyright (c) 2013-2017 OpenCFP
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/opencfp/opencfp
*/
namespace OpenCFP\Infrastructure\Templating;
use OpenCFP\PathInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig_Extension;
use Twig_SimpleFunction;
class TwigExtension extends Twig_Extension
{
/**
* @var RequestStack
*/
private $requestStack;
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* @var PathInterface
*/
private $path;
public function __construct(RequestStack $requestStack, UrlGeneratorInterface $urlGenerator, PathInterface $path)
{
$this->requestStack = $requestStack;
$this->urlGenerator = $urlGenerator;
$this->path = $path;
}
public function getFunctions()
{
return [
new Twig_SimpleFunction('uploads', function ($path) {
return $this->path->downloadFromPath() . $path;
}),
new Twig_SimpleFunction('assets', function ($path) {
return '/assets/' . $path;
}),
new Twig_SimpleFunction('active', function ($route) {
return $this->urlGenerator->generate($route)
=== $this->requestStack->getCurrentRequest()->getRequestUri();
}),
];
}
}
|
Fix invalid typehint for subject in is_granted Twig function | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* SecurityExtension exposes security context features.
*
* @author Fabien Potencier <[email protected]>
*/
final class SecurityExtension extends AbstractExtension
{
private $securityChecker;
public function __construct(AuthorizationCheckerInterface $securityChecker = null)
{
$this->securityChecker = $securityChecker;
}
/**
* @param mixed $object
*/
public function isGranted($role, $object = null, string $field = null): bool
{
if (null === $this->securityChecker) {
return false;
}
if (null !== $field) {
$object = new FieldVote($object, $field);
}
try {
return $this->securityChecker->isGranted($role, $object);
} catch (AuthenticationCredentialsNotFoundException $e) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* SecurityExtension exposes security context features.
*
* @author Fabien Potencier <[email protected]>
*/
final class SecurityExtension extends AbstractExtension
{
private $securityChecker;
public function __construct(AuthorizationCheckerInterface $securityChecker = null)
{
$this->securityChecker = $securityChecker;
}
public function isGranted($role, object $object = null, string $field = null): bool
{
if (null === $this->securityChecker) {
return false;
}
if (null !== $field) {
$object = new FieldVote($object, $field);
}
try {
return $this->securityChecker->isGranted($role, $object);
} catch (AuthenticationCredentialsNotFoundException $e) {
return false;
}
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array
{
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
}
|
Adjust Account.databases() to new return format |
from .base import BaseWrapper
from .database import Database
from ..constants import URL_BASE
class Account(BaseWrapper):
"""An object encapsulating a billing account on Luminoso's servers"""
def __init__(self, acct_name, session):
"""Construct a wrapper around a particular account name
NOTE: Construction does not validate the existence or accessibility
of the account"""
super(Account, self).__init__(path=acct_name, session=session)
self.acct_name = acct_name
def __unicode__(self):
return u'Account("%s")' % self.acct_name
@classmethod
def accessible(cls, session):
accounts = session.get(URL_BASE + '/.accounts/').json
return [Account(acct, session) for acct in accounts['accounts']]
def databases(self):
db_table = self._get('/.list_dbs/')['result']
dbs = {}
for db_name, db_meta in db_table.items():
path = self.api_path + '/' + db_meta['name']
dbs[db_name]=Database(path, db_name, meta=db_meta,
session=self._session)
return dbs
def create_project(self, db_name):
resp = self._post_raw('/%s/create_project/' % db_name)
if resp == 'Database %s created' % db_name:
return None
return resp
|
from .base import BaseWrapper
from .database import Database
from ..constants import URL_BASE
class Account(BaseWrapper):
"""An object encapsulating a billing account on Luminoso's servers"""
def __init__(self, acct_name, session):
"""Construct a wrapper around a particular account name
NOTE: Construction does not validate the existence or accessibility
of the account"""
super(Account, self).__init__(path=acct_name, session=session)
self.acct_name = acct_name
def __unicode__(self):
return u'Account("%s")' % self.acct_name
@classmethod
def accessible(cls, session):
accounts = session.get(URL_BASE + '/.accounts/').json
return [Account(acct, session) for acct in accounts['accounts']]
def databases(self):
db_table = self._get('/.list_dbs/')
dbs = {}
for db_name, db_meta in db_table.items():
path = self.api_path + '/' + db_meta['name']
dbs[db_name]=Database(path, db_name, meta=db_meta,
session=self._session)
return dbs
def create_project(self, db_name):
resp = self._post_raw('/%s/create_project/' % db_name)
if resp == 'Database %s created' % db_name:
return None
return resp
|
Use the proper entry point name. | import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='jirafs_list_table',
version=version_string,
url='https://github.com/coddingtonbear/jirafs-list-table',
description="Make simple tables in JIRA more easily by using a simple list-based syntax.",
author='Adam Coddington',
author_email='[email protected]',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'list_table = jirafs_list_table.plugin:Plugin',
]
},
)
| import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='jirafs_list_table',
version=version_string,
url='https://github.com/coddingtonbear/jirafs-list-table',
description="Make simple tables in JIRA more easily by using a simple list-based syntax.",
author='Adam Coddington',
author_email='[email protected]',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_list_table': [
'list_table = jirafs_list_table.plugin:Plugin',
]
},
)
|
Use the babel-runtime to fix the build | /* global process */
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: true,
frameworks: [ 'mocha' ],
files: [
'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js',
'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js',
'./__tests__/tests.webpack.js'
],
preprocessors: {
'./__tests__/tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: [ 'dots' ],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'jsx-loader?stripTypes',
'babel?stage=0&optional=runtime'
],
exclude: /node_modules/
}
]
},
externals : {
'react' : 'React',
'react-dom' : 'ReactDOM'
}
},
webpackServer: {
noInfo: true
}
});
};
| /* global process */
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: true,
frameworks: [ 'mocha' ],
files: [
'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js',
'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js',
'./__tests__/tests.webpack.js'
],
preprocessors: {
'./__tests__/tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: [ 'dots' ],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'jsx-loader?stripTypes',
'babel?stage=0'
],
exclude: /node_modules/
}
]
},
externals : {
'react' : 'React',
'react-dom' : 'ReactDOM'
}
},
webpackServer: {
noInfo: true
}
});
};
|
Prepare first 2.0 alpha release | import sys
from setuptools import find_packages, setup
VERSION = '2.0a1'
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Decrease mapLimit and pool maximums | #!/usr/bin/env node
'use strict';
var stdin = process.openStdin();
var async = require('async');
var cheerio = require('cheerio');
var ent = require('ent');
var request = require('request');
main();
function main() {
stdin.setEncoding('utf8');
stdin.on('data', function(data) {
fetchTitles(JSON.parse(data));
});
}
function fetchTitles(urls) {
async.mapLimit(urls, 10, fetchTitle, function(err, d) {
if(err) {
return console.error(err);
}
console.log(JSON.stringify(d.filter(id), null, 4));
});
}
function fetchTitle(d, cb) {
if(!d) {
return cb();
}
request.get(d.url, {
rejectUnauthorized: false,
pool: {
maxSockets: 10
}
}, function(err, res, body) {
if(err) {
console.error(d.url, err);
return cb();
}
var $ = cheerio.load(body);
d.title = ent.decode($('title').text().split('·')[0].
split(' - ')[0].
split(' — ')[0].
split('|')[0].
split('//')[0].
split(' « ')[0].
split(' » ')[0].
split(' : ')[0].
trim());
cb(null, d);
});
}
function id(a) {return a;}
| #!/usr/bin/env node
'use strict';
var stdin = process.openStdin();
var async = require('async');
var cheerio = require('cheerio');
var ent = require('ent');
var request = require('request');
main();
function main() {
stdin.setEncoding('utf8');
stdin.on('data', function(data) {
fetchTitles(JSON.parse(data));
});
}
function fetchTitles(urls) {
async.mapLimit(urls, 20, fetchTitle, function(err, d) {
if(err) {
return console.error(err);
}
console.log(JSON.stringify(d.filter(id), null, 4));
});
}
function fetchTitle(d, cb) {
if(!d) {
return cb();
}
request.get(d.url, {
rejectUnauthorized: false,
pool: {
maxSockets: 1000
}
}, function(err, res, body) {
if(err) {
console.error(d.url, err);
return cb();
}
var $ = cheerio.load(body);
d.title = ent.decode($('title').text().split('·')[0].
split(' - ')[0].
split(' — ')[0].
split('|')[0].
split('//')[0].
split(' « ')[0].
split(' » ')[0].
split(' : ')[0].
trim());
cb(null, d);
});
}
function id(a) {return a;}
|
Add test cases for optional enums
Added test cases where required is set as true and false,
with the attribute omitted. | <?php
/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JsonSchema\Tests\Constraints;
class EnumTest extends BaseTestCase
{
public function getInvalidTests()
{
return array(
array(
'{
"value":"Morango"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
},
"additionalProperties":false
}'
),
array(
'{}',
'{
"type":"object",
"properties":{
"value":{
"type":"string",
"enum":["Abacate","Manga","Pitanga"],
"required":true
}
},
"additionalProperties":false
}'
)
);
}
public function getValidTests()
{
return array(
array(
'{
"value":"Abacate"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
},
"additionalProperties":false
}'
),
array(
'{}',
'{
"type":"object",
"properties":{
"value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
},
"additionalProperties":false
}'
),
array(
'{}',
'{
"type":"object",
"properties":{
"value":{
"type":"string",
"enum":["Abacate","Manga","Pitanga"],
"required":false
}
},
"additionalProperties":false
}'
)
);
}
}
| <?php
/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JsonSchema\Tests\Constraints;
class EnumTest extends BaseTestCase
{
public function getInvalidTests()
{
return array(
array(
'{
"value":"Morango"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
},
"additionalProperties":false
}'
)
);
}
public function getValidTests()
{
return array(
array(
'{
"value":"Abacate"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","enum":["Abacate","Manga","Pitanga"]}
},
"additionalProperties":false
}'
)
);
}
}
|
Order radar view more sensibly
1. Sort with by date_seen DESC so new stuff is at the top
and old stuff is at the bottom
2. Sort by id as secondary criteria so order is consistent
otherwise the order changes a bit every time we make an edit | from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from election_snooper.models import SnoopedElection
from election_snooper.forms import ReviewElectionForm
class SnoopedElectionView(TemplateView):
template_name = "election_snooper/snooped_election_list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
queryset = SnoopedElection.objects.all().order_by('-date_seen', 'id')
if 'status' in self.request.GET:
queryset = queryset.filter(status=self.request.GET['status'])
if 'pk' in self.request.GET:
queryset = queryset.filter(pk=self.request.GET['pk'])
object_list = []
for item in queryset:
object_list.append(
ReviewElectionForm(instance=item, prefix=item.pk)
)
context['object_list'] = object_list
return context
def post(self, request, *args, **kwargs):
instance = SnoopedElection.objects.get(pk=request.POST.get('pk'))
form = ReviewElectionForm(
request.POST, instance=instance, prefix=instance.pk)
if form.is_valid():
form.save()
# TODO: if there's an error it's not processed yet
return HttpResponseRedirect(reverse('snooped_election_view'))
| from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from election_snooper.models import SnoopedElection
from election_snooper.forms import ReviewElectionForm
class SnoopedElectionView(TemplateView):
template_name = "election_snooper/snooped_election_list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
queryset = SnoopedElection.objects.all().order_by('date_seen')
if 'status' in self.request.GET:
queryset = queryset.filter(status=self.request.GET['status'])
if 'pk' in self.request.GET:
queryset = queryset.filter(pk=self.request.GET['pk'])
object_list = []
for item in queryset:
object_list.append(
ReviewElectionForm(instance=item, prefix=item.pk)
)
context['object_list'] = object_list
return context
def post(self, request, *args, **kwargs):
instance = SnoopedElection.objects.get(pk=request.POST.get('pk'))
form = ReviewElectionForm(
request.POST, instance=instance, prefix=instance.pk)
if form.is_valid():
form.save()
# TODO: if there's an error it's not processed yet
return HttpResponseRedirect(reverse('snooped_election_view'))
|
Set the api token from a successful authorization | import Ember from 'ember';
export default Ember.Route.extend({
beforeModel: function(transition) {
var win = window.open('/github_login', 'Authorization',
'width=1000,height=450,' +
'toolbar=0,scrollbars=1,status=1,resizable=1,' +
'location=1,menuBar=0');
if (!win) { return; }
// For the life of me I cannot figure out how to do this other than
// polling
var self = this;
var oauthInterval = window.setInterval(function(){
if (!win.closed) { return; }
window.clearInterval(oauthInterval);
var response = JSON.parse(localStorage.github_response);
if (!response.ok) {
self.controllerFor('application').set('flashError',
'Failed to log in');
return;
}
var data = response.data;
if (data.errors) {
var error = "Failed to log in: " + data.errors[0];
self.controllerFor('application').set('flashError', error);
return;
}
var user = self.store.push('user', data.user);
user.set('api_token', data.api_token);
var transition = self.session.get('savedTransition');
self.session.loginUser(user);
if (transition) {
transition.retry();
}
}, 200);
transition.abort();
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
beforeModel: function(transition) {
var win = window.open('/github_login', 'Authorization',
'width=1000,height=450,' +
'toolbar=0,scrollbars=1,status=1,resizable=1,' +
'location=1,menuBar=0');
if (!win) { return; }
// For the life of me I cannot figure out how to do this other than
// polling
var self = this;
var oauthInterval = window.setInterval(function(){
if (!win.closed) { return; }
window.clearInterval(oauthInterval);
var response = JSON.parse(localStorage.github_response);
if (!response.ok) {
self.controllerFor('application').set('flashError',
'Failed to log in');
return;
}
var data = response.data;
if (data.errors) {
var error = "Failed to log in: " + data.errors[0];
self.controllerFor('application').set('flashError', error);
return;
}
var user = self.store.push('user', data.user);
var transition = self.session.get('savedTransition');
self.session.loginUser(user);
if (transition) {
transition.retry();
}
}, 200);
transition.abort();
}
});
|
Add more shards to test speed | <?php
return [
'index' => 'sites',
'body' => [
'settings' => [
'number_of_shards' => 20,
'number_of_replicas' => 0,
],
'mapping' => [
'default' => [
'properties' => [
'title' => [
'type' => 'string',
'index' => 'analyzed',
'analyzer' => 'english'
],
'content' => [
'type' => 'string',
'index' => 'analyzed',
'analyzer' => 'english'
],
'hash_id' => ['type' => 'string', 'index' => 'not_analyzed'],
'date' => ['type' => 'date', 'format' => 'date_time_no_millis'],
'original' => [
'type' => 'object',
'properties' => [
'title' => ['type' => 'string', 'index' => 'no'],
'content' => ['type' => 'string', 'index' => 'no'],
'url' => ['type' => 'string', 'index' => 'no']
]
]
]
]
]
]
]; | <?php
return [
'index' => 'sites',
'body' => [
'settings' => [
'number_of_shards' => 10,
'number_of_replicas' => 0,
],
'mapping' => [
'default' => [
'properties' => [
'title' => [
'type' => 'string',
'index' => 'analyzed',
'analyzer' => 'english'
],
'content' => [
'type' => 'string',
'index' => 'analyzed',
'analyzer' => 'english'
],
'hash_id' => ['type' => 'string', 'index' => 'not_analyzed'],
'date' => ['type' => 'date', 'format' => 'date_time_no_millis'],
'original' => [
'type' => 'object',
'properties' => [
'title' => ['type' => 'string', 'index' => 'no'],
'content' => ['type' => 'string', 'index' => 'no'],
'url' => ['type' => 'string', 'index' => 'no']
]
]
]
]
]
]
]; |
Revert "small fix in perplexity runner"
This reverts commit b195416761f12df496baa389df4686b2cf60c675. | from typing import Dict, List
from typeguard import check_argument_types
import tensorflow as tf
import numpy as np
from neuralmonkey.decoders.autoregressive import AutoregressiveDecoder
from neuralmonkey.decorators import tensor
from neuralmonkey.runners.base_runner import BaseRunner
class PerplexityRunner(BaseRunner[AutoregressiveDecoder]):
# pylint: disable=too-few-public-methods
# Pylint issue here: https://github.com/PyCQA/pylint/issues/2607
class Executable(BaseRunner.Executable["PerplexityRunner"]):
def collect_results(self, results: List[Dict]) -> None:
perplexities = np.mean(
[2 ** res["xents"] for res in results], axis=0)
xent = float(np.mean([res["xents"] for res in results]))
self.set_runner_result(outputs=perplexities.tolist(),
losses=[xent])
# pylint: enable=too-few-public-methods
def __init__(self,
output_series: str,
decoder: AutoregressiveDecoder) -> None:
check_argument_types()
BaseRunner[AutoregressiveDecoder].__init__(
self, output_series, decoder)
@tensor
def fetches(self) -> Dict[str, tf.Tensor]:
return {"xents": self.decoder.train_xents}
@property
def loss_names(self) -> List[str]:
return ["xent"]
| from typing import Dict, List
from typeguard import check_argument_types
import tensorflow as tf
import numpy as np
from neuralmonkey.decoders.autoregressive import AutoregressiveDecoder
from neuralmonkey.decorators import tensor
from neuralmonkey.runners.base_runner import BaseRunner
class PerplexityRunner(BaseRunner[AutoregressiveDecoder]):
# pylint: disable=too-few-public-methods
# Pylint issue here: https://github.com/PyCQA/pylint/issues/2607
class Executable(BaseRunner.Executable["PerplexityRunner"]):
def collect_results(self, results: List[Dict]) -> None:
perplexities = np.mean(
[2 ** res["xents"] for res in results], axis=0)
xent = float(np.mean([res["xents"] for res in results]))
self.set_runner_result(outputs=perplexities.tolist(),
losses=[xent])
# pylint: enable=too-few-public-methods
def __init__(self,
output_series: str,
decoder: AutoregressiveDecoder) -> None:
check_argument_types()
BaseRunner[AutoregressiveDecoder].__init__(
self, output_series, decoder)
@tensor
def fetches(self) -> Dict[str, tf.Tensor]:
return {"xents": self.decoder.train_xents}
@property
def loss_names(self) -> List[str]:
return ["xents"]
|
CC-5781: Upgrade script for new storage quota implementation | <?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
require_once 'BaseCcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
| <?php
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
realpath(APPLICATION_PATH . '/../library')
)));
//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());
require_once 'CcMusicDirsQuery.php';
require_once 'BaseCcMusicDirsQuery.php';
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByDbType('stor')
->filterByDbExists(true)
->findOne();
$storPath = $musicDir->getDbDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
Use page.content if modified or fallback to page.sections in plugins hooks | var _ = require('lodash');
var error = require('../utils/error');
/*
Return the context for a plugin.
It tries to keep compatibilities with GitBook v2
*/
function pluginCtx(plugin) {
var book = plugin.book;
var ctx = book;
return ctx;
}
/*
Call a function "fn" with a context of page similar to the one in GitBook v2
@params {Page}
@returns {String|undefined} new content of the page
*/
function pageHook(page, fn) {
// Get page context
var ctx = page.getContext().page;
// Add other informations
ctx.type = page.type;
ctx.rawPath = page.rawPath;
ctx.path = page.path;
// Deprecate sections
error.deprecateField(ctx, 'sections', [
{ content: ctx.content, type: 'normal' }
], '"sections" property is deprecated, use page.content instead');
// Keep reference of original content for compatibility
var originalContent = ctx.content;
return fn(ctx)
.then(function(result) {
// No returned value
// Existing content will be used
if (!result) return undefined;
// GitBook 3
// Use returned page.content if different from original content
if (result.content != originalContent) {
return result.content;
}
// GitBook 2 compatibility
// Finally, use page.sections
if (result.sections) {
return _.pluck(result.sections, 'content').join('\n');
}
});
}
module.exports = {
pluginCtx: pluginCtx,
pageHook: pageHook
};
| var _ = require('lodash');
var error = require('../utils/error');
/*
Return the context for a plugin.
It tries to keep compatibilities with GitBook v2
*/
function pluginCtx(plugin) {
var book = plugin.book;
var ctx = book;
return ctx;
}
/*
Call a function "fn" with a context of page similar to the one in GitBook v2
@params {Page}
@returns {String|undefined} new content of the page
*/
function pageHook(page, fn) {
// Get page context
var ctx = page.getContext().page;
// Add other informations
ctx.type = page.type;
ctx.rawPath = page.rawPath;
ctx.path = page.path;
// Deprecate sections
error.deprecateField(ctx, 'sections', [
{ content: ctx.content, type: 'normal' }
], '"sections" property is deprecated, use page.content instead');
return fn(ctx)
.then(function(result) {
// No returned value
// Existing content will be used
if (!result) return undefined;
// GitBook 2 compatibility first
// Use sections if provided
if (result.sections) {
return _.pluck(result.sections, 'content').join('\n');
}
// GitBook 3
// Use returned page.content
if (result.content) {
return result.content;
}
});
}
module.exports = {
pluginCtx: pluginCtx,
pageHook: pageHook
};
|
Allow TextWire to write binary headers as well as plain text. | package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
interface MockMethods {
void method1(MockDto dto);
void method2(MockDto dto);
}
/**
* Created by peter on 17/05/2017.
*/
public class MethodReaderTest {
@Test
public void readMethods() throws IOException {
Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")).useTextDocuments();
Wire wire2 = new TextWire(Bytes.allocateElasticDirect());
// expected
Bytes expected = BytesUtil.readFile("methods-in.yaml");
MockMethods writer = wire2.methodWriter(MockMethods.class);
MethodReader reader = wire.methodReader(writer);
for (int i = 0; i < 2; i++) {
assertTrue(reader.readOne());
while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ')
wire2.bytes().writeSkip(-1);
wire2.bytes().append("---\n");
}
assertFalse(reader.readOne());
assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim());
}
}
class MockDto extends AbstractMarshallable {
String field1;
double field2;
}
| package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
interface MockMethods {
void method1(MockDto dto);
void method2(MockDto dto);
}
/**
* Created by peter on 17/05/2017.
*/
public class MethodReaderTest {
@Test
public void readMethods() throws IOException {
Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml"));
Wire wire2 = new TextWire(Bytes.allocateElasticDirect());
// expected
Bytes expected = BytesUtil.readFile("methods-in.yaml");
MockMethods writer = wire2.methodWriter(MockMethods.class);
MethodReader reader = wire.methodReader(writer);
for (int i = 0; i < 2; i++) {
assertTrue(reader.readOne());
while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ')
wire2.bytes().writeSkip(-1);
wire2.bytes().append("---\n");
}
assertFalse(reader.readOne());
assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim());
}
}
class MockDto extends AbstractMarshallable {
String field1;
double field2;
}
|
Remove extraneous colon from url(...) regex | <?php
namespace Kibo\Phast\Filters\HTML;
use Kibo\Phast\ValueObjects\URL;
class CSSImagesOptimizationServiceHTMLFilter extends ImagesOptimizationServiceHTMLFilter {
public function transformHTMLDOM(\DOMDocument $document) {
$styleTags = $document->getElementsByTagName('style');
/** @var \DOMElement $styleTag */
foreach ($styleTags as $styleTag) {
$styleTag->textContent = $this->rewriteStyle($styleTag->textContent);
}
$styleAttrs = (new \DOMXPath($document))->query('//@style');
/** @var \DOMAttr $styleAttr */
foreach ($styleAttrs as $styleAttr) {
$styleAttr->value = htmlspecialchars($this->rewriteStyle($styleAttr->value));
}
}
private function rewriteStyle($styleContent) {
return preg_replace_callback(
'~
(
\b (?: image | background ):
[^;}]*
\b url \( [\'"]?
)
(
[^\'")] +
)
~xi',
function ($matches) {
$params = ['src' => (string) URL::fromString($matches[2])->withBase($this->baseUrl)];
return $matches[1] . $this->makeSignedUrl($this->serviceUrl, $params, $this->signature);
},
$styleContent
);
}
}
| <?php
namespace Kibo\Phast\Filters\HTML;
use Kibo\Phast\ValueObjects\URL;
class CSSImagesOptimizationServiceHTMLFilter extends ImagesOptimizationServiceHTMLFilter {
public function transformHTMLDOM(\DOMDocument $document) {
$styleTags = $document->getElementsByTagName('style');
/** @var \DOMElement $styleTag */
foreach ($styleTags as $styleTag) {
$styleTag->textContent = $this->rewriteStyle($styleTag->textContent);
}
$styleAttrs = (new \DOMXPath($document))->query('//@style');
/** @var \DOMAttr $styleAttr */
foreach ($styleAttrs as $styleAttr) {
$styleAttr->value = htmlspecialchars($this->rewriteStyle($styleAttr->value));
}
}
private function rewriteStyle($styleContent) {
return preg_replace_callback(
'~
(
\b (?: image | background ):
[^;}]*
\b url \( [:\'"]?
)
(
[^\'")] +
)
~xi',
function ($matches) {
$params = ['src' => (string) URL::fromString($matches[2])->withBase($this->baseUrl)];
return $matches[1] . $this->makeSignedUrl($this->serviceUrl, $params, $this->signature);
},
$styleContent
);
}
}
|
Add ES6 string interpolation in template | import React from 'react';
const Item = ({
onDeleteClick,
name,
year,
rated,
runtime,
genre,
director,
actors,
description,
country,
awards,
poster,
scoreMetacritic,
scoreImdb,
scoreTomato,
scoreTomatoUser,
tomatoConsensus }) =>
<li className="item">
<img className="item__poster" src={poster} alt={`${name} movie poster`} />
<div className="item__info">
<div>
<h2 className="item__info__name">{name}</h2>
<p className="item__info__genre">{genre}</p>
<p className="item__info__tech">{`${year} ${rated} ${runtime}`}</p>
</div>
<ul className="item__info__scores">
<li>{scoreTomato}%</li>
<li>{scoreTomatoUser}%</li>
<li>{scoreImdb}</li>
<li>{scoreMetacritic}</li>
</ul>
<p>{description}</p>
<p>
Starring: {actors}
<br/>
Director: {director}
</p>
<button className="item__btn-delete" onClick={onDeleteClick}>X</button>
</div>
</li>
export default Item; | import React from 'react';
const Item = ({
onDeleteClick,
name,
year,
rated,
runtime,
genre,
director,
actors,
description,
country,
awards,
poster,
scoreMetacritic,
scoreImdb,
scoreTomato,
scoreTomatoUser,
tomatoConsensus }) =>
<li className="item">
<img className="item__poster" src={poster} alt={name + " movie poster"} />
<div className="item__info">
<div>
<h2 className="item__info__name">{name}</h2>
<p className="item__info__genre">{genre}</p>
<p className="item__info__tech">{year + ' ' + rated + ' ' + runtime}</p>
</div>
<ul className="item__info__scores">
<li>{scoreTomato}%</li>
<li>{scoreTomatoUser}%</li>
<li>{scoreImdb}</li>
<li>{scoreMetacritic}</li>
</ul>
<p>{description}</p>
<p>
Starring: {actors}
<br/>
Director: {director}
</p>
<button className="item__btn-delete" onClick={onDeleteClick}>X</button>
</div>
</li>
export default Item; |
Add newly created packages to config. | <?php
namespace Studio\Console;
use Studio\Config\Config;
use Studio\Creator;
use Studio\Package;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CreateCommand extends Command
{
protected $config;
protected $creator;
public function __construct(Config $config, Creator $creator)
{
parent::__construct();
$this->config = $config;
$this->creator = $creator;
}
protected function configure()
{
$this
->setName('create')
->setDescription('Create a new package skeleton')
->addArgument(
'package',
InputArgument::REQUIRED,
'The name of the package to create'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$package = $this->makePackage($input);
$directory = $this->creator->create($package);
$this->config->addPackage($package);
$output->writeln("<info>Package directory $directory created.</info>");
}
protected function makePackage(InputInterface $input)
{
$name = $input->getArgument('package');
if (! str_contains($name, '/')) {
throw new \InvalidArgumentException('Invalid package name');
}
list($vendor, $package) = explode('/', $name, 2);
return new Package($vendor, $package);
}
}
| <?php
namespace Studio\Console;
use Studio\Creator;
use Studio\Package;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CreateCommand extends Command
{
protected $creator;
public function __construct(Creator $creator)
{
parent::__construct();
$this->creator = $creator;
}
protected function configure()
{
$this
->setName('create')
->setDescription('Create a new package skeleton')
->addArgument(
'package',
InputArgument::REQUIRED,
'The name of the package to create'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$directory = $this->creator->create($this->makePackage($input));
$output->writeln("<info>Package directory $directory created.</info>");
}
protected function makePackage(InputInterface $input)
{
$name = $input->getArgument('package');
if (! str_contains($name, '/')) {
throw new \InvalidArgumentException('Invalid package name');
}
list($vendor, $package) = explode('/', $name, 2);
return new Package($vendor, $package);
}
}
|
Change credential text to use the same identifiers as the commandline tools
This allows a single simple cut/paste into a config file. | <h4>Details for your app: <em><?php $this->utility->safe($name); ?></em></h4>
<div class="row">
<div class="span12">
<table class="table left-header">
<tr>
<td class="span2">Name</td>
<td><?php $this->utility->safe($name); ?></td>
</tr>
<tr>
<td>consumerKey =</td>
<td><?php $this->utility->safe($id); ?></td>
</tr>
<tr>
<td>consumerSecret =</td>
<td><?php $this->utility->safe($clientSecret); ?></td>
</tr>
<tr>
<td>token =</td>
<td><?php $this->utility->safe($userToken); ?></td>
</tr>
<tr>
<td>tokenSecret =</td>
<td><?php $this->utility->safe($userSecret); ?></td>
</tr>
<tr>
<td>Type</td>
<td>
<?php $this->utility->safe($type); ?>
<?php if($type !== Credential::typeAccess) { ?>
<small>(Only access tokens can be used)</small>
<?php } ?>
</td>
</tr>
</table>
</div>
</div>
<a href="#" class="batchHide close" title="Close this dialog"><i class="icon-remove batchHide"></i></a>
| <h4>Details for your app: <em><?php $this->utility->safe($name); ?></em></h4>
<div class="row">
<div class="span12">
<table class="table left-header">
<tr>
<td class="span2">Name</td>
<td><?php $this->utility->safe($name); ?></td>
</tr>
<tr>
<td>Consumer Key</td>
<td><?php $this->utility->safe($id); ?></td>
</tr>
<tr>
<td>Consumer Secret</td>
<td><?php $this->utility->safe($clientSecret); ?></td>
</tr>
<tr>
<td>OAuth Token</td>
<td><?php $this->utility->safe($userToken); ?></td>
</tr>
<tr>
<td>OAuth Secret</td>
<td><?php $this->utility->safe($userSecret); ?></td>
</tr>
<tr>
<td>Type</td>
<td>
<?php $this->utility->safe($type); ?>
<?php if($type !== Credential::typeAccess) { ?>
<small>(Only access tokens can be used)</small>
<?php } ?>
</td>
</tr>
</table>
</div>
</div>
<a href="#" class="batchHide close" title="Close this dialog"><i class="icon-remove batchHide"></i></a>
|
Check the end of notification fade-out animation | var NotificationComponent = Ember.Component.extend({
classNames: ['js-bb-notification'],
typeClass: function () {
var classes = '',
message = this.get('message'),
type,
dismissible;
// Check to see if we're working with a DS.Model or a plain JS object
if (typeof message.toJSON === 'function') {
type = message.get('type');
dismissible = message.get('dismissible');
}
else {
type = message.type;
dismissible = message.dismissible;
}
classes += 'notification-' + type;
if (type === 'success' && dismissible !== false) {
classes += ' notification-passive';
}
return classes;
}.property(),
didInsertElement: function () {
var self = this;
self.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
/* jshint unused: false */
if (event.originalEvent.animationName === 'fade-out') {
self.notifications.removeObject(self.get('message'));
}
});
},
actions: {
closeNotification: function () {
var self = this;
self.notifications.closeNotification(self.get('message'));
}
}
});
export default NotificationComponent;
| var NotificationComponent = Ember.Component.extend({
classNames: ['js-bb-notification'],
typeClass: function () {
var classes = '',
message = this.get('message'),
type,
dismissible;
// Check to see if we're working with a DS.Model or a plain JS object
if (typeof message.toJSON === 'function') {
type = message.get('type');
dismissible = message.get('dismissible');
}
else {
type = message.type;
dismissible = message.dismissible;
}
classes += 'notification-' + type;
if (type === 'success' && dismissible !== false) {
classes += ' notification-passive';
}
return classes;
}.property(),
didInsertElement: function () {
var self = this;
self.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
/* jshint unused: false */
self.notifications.removeObject(self.get('message'));
});
},
actions: {
closeNotification: function () {
var self = this;
self.notifications.closeNotification(self.get('message'));
}
}
});
export default NotificationComponent;
|
Add a space into the material filter search string
Without this space the end of the session title is forced onto the start
of the instructor names. This leads to a search for 'dean' returning
results of suicideAngela which is incorrect. | import Ember from 'ember';
import SortableTable from 'ilios/mixins/sortable-table';
import escapeRegExp from '../utils/escape-reg-exp';
const { Component, computed, isPresent } = Ember;
export default Component.extend(SortableTable, {
classNames: ['my-materials'],
filter: null,
courseIdFilter: null,
filteredMaterials: computed('materials.[]', 'filter', 'courseIdFilter', function(){
let materials = this.get('materials');
const filter = this.get('filter');
const courseIdFilter = this.get('courseIdFilter');
if (isPresent(courseIdFilter)) {
materials = materials.filterBy('course', courseIdFilter);
}
if (isPresent(filter)) {
let val = escapeRegExp(filter);
const exp = new RegExp(val, 'gi');
materials = materials.filter(material => {
let searchString = material.title + ' ' + material.courseTitle + ' ' + material.sessionTitle + ' ';
if (isPresent(material.instructors)) {
searchString += material.instructors.join(' ');
}
return searchString.match(exp);
});
}
return materials;
}),
courses: computed('materials.[]', function(){
const materials = this.get('materials');
return materials.map(material => {
return {
id: material.course,
title: material.courseTitle
};
}).uniqBy('id').sortBy('title');
}),
actions: {
sortString(a, b){
return a.localeCompare(b);
}
}
});
| import Ember from 'ember';
import SortableTable from 'ilios/mixins/sortable-table';
import escapeRegExp from '../utils/escape-reg-exp';
const { Component, computed, isPresent } = Ember;
export default Component.extend(SortableTable, {
classNames: ['my-materials'],
filter: null,
courseIdFilter: null,
filteredMaterials: computed('materials.[]', 'filter', 'courseIdFilter', function(){
let materials = this.get('materials');
const filter = this.get('filter');
const courseIdFilter = this.get('courseIdFilter');
if (isPresent(courseIdFilter)) {
materials = materials.filterBy('course', courseIdFilter);
}
if (isPresent(filter)) {
let val = escapeRegExp(filter);
const exp = new RegExp(val, 'gi');
materials = materials.filter(material => {
let searchString = material.title + material.courseTitle + material.sessionTitle;
if (isPresent(material.instructors)) {
searchString += material.instructors.join('');
}
return searchString.match(exp);
});
}
return materials;
}),
courses: computed('materials.[]', function(){
const materials = this.get('materials');
return materials.map(material => {
return {
id: material.course,
title: material.courseTitle
};
}).uniqBy('id').sortBy('title');
}),
actions: {
sortString(a, b){
return a.localeCompare(b);
}
}
});
|
Include JSX in browserified bundle for Karma | 'use strict';
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['browserify', 'mocha', 'sinon'],
files: [
// Source
// 'src/js/**/*.js',
// // Application
// 'build/css/main.css',
// 'build/js/modernizr.js',
// 'index.html',
// Test suites
'test/**/*.js',
'test/**/*.jsx'
],
exclude: [],
preprocessors: {
// 'src/js/**/*.js': ['browserify'],
'test/**/*.{js,jsx}': ['browserify']
},
browserify: {
debug: true,
extensions: ['.jsx'],
transform: [
['babelify', { presets: ['es2015', 'react'] }],
'brfs'
],
// Configuration required for enzyme to work; see
// http://airbnb.io/enzyme/docs/guides/browserify.html
configure: function (bundle) {
bundle.on('prebundle', function () {
bundle.external('react/addons');
bundle.external('react/lib/ReactContext');
bundle.external('react/lib/ExecutionEnvironment');
});
}
},
plugins: [
'karma-mocha',
'karma-sinon',
'karma-phantomjs-launcher',
'karma-mocha-reporter',
'karma-browserify'
],
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
| 'use strict';
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['browserify', 'mocha', 'sinon'],
files: [
// Source
// 'src/js/**/*.js',
// // Application
// 'build/css/main.css',
// 'build/js/modernizr.js',
// 'index.html',
// Test suites
'test/**/*.js',
'test/**/*.jsx'
],
exclude: [],
preprocessors: {
// 'src/js/**/*.js': ['browserify'],
'test/**/*.js': ['browserify']
},
browserify: {
debug: true,
extensions: ['.jsx'],
transform: [
['babelify', { presets: ['es2015', 'react'] }],
'brfs'
],
// Configuration required for enzyme to work; see
// http://airbnb.io/enzyme/docs/guides/browserify.html
configure: function (bundle) {
bundle.on('prebundle', function () {
bundle.external('react/addons');
bundle.external('react/lib/ReactContext');
bundle.external('react/lib/ExecutionEnvironment');
});
}
},
plugins: [
'karma-mocha',
'karma-sinon',
'karma-phantomjs-launcher',
'karma-mocha-reporter',
'karma-browserify'
],
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
});
};
|
Remove unneeded return + add comment about require.resolve() | var sass = require('node-sass'),
path = require('path'),
fs = require('fs');
var handledBaseFolderNames = {
'bower_components': 'bower_components',
'node_modules': 'node_modules'
};
function customImporter (url, prev, done) {
var baseFolderName = url.split(path.sep)[0];
if (handledBaseFolderNames[baseFolderName]) {
if (!endsWith(url, '.scss')) {
url += '.scss';
}
findInParentDir(url, prev, done);
}
return sass.NULL;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function findInParentDir(relativePath, startingDirPath, done) {
// For node modules we may want to try using require.resolve() here instead.
var dirToTry = path.join(startingDirPath, '..');
var pathToTry = path.join(dirToTry, relativePath);
fs.access(pathToTry, fs.R_OK, function(err) {
if (err) {
if (pathToTry === ('/' + relativePath)) {
done(new Error('File not found: ' + relativePath));
} else {
return findInParentDir(relativePath, dirToTry, done);
}
} else {
done({ file: pathToTry });
}
});
}
module.exports = customImporter;
| var sass = require('node-sass'),
path = require('path'),
fs = require('fs');
var handledBaseFolderNames = {
'bower_components': 'bower_components',
'node_modules': 'node_modules'
};
function customImporter (url, prev, done) {
var baseFolderName = url.split(path.sep)[0];
if (handledBaseFolderNames[baseFolderName]) {
if (!endsWith(url, '.scss')) {
url += '.scss';
}
return findInParentDir(url, prev, done);
}
return sass.NULL;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function findInParentDir(relativePath, startingDirPath, done) {
var dirToTry = path.join(startingDirPath, '..');
var pathToTry = path.join(dirToTry, relativePath);
fs.access(pathToTry, fs.R_OK, function(err) {
if (err) {
if (pathToTry === ('/' + relativePath)) {
done(new Error('File not found: ' + relativePath));
} else {
return findInParentDir(relativePath, dirToTry, done);
}
} else {
done({ file: pathToTry });
}
});
}
module.exports = customImporter;
|
Remove HTML table (our mail cannot send HTML) | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def mail_time_summary():
users = []
for item in InvoiceUser.objects.all():
if item.mail_time_summary and item.user.email:
users.append(item.user)
for user in users:
logger.info('mail_time_summary: {}'.format(user.username))
report = time_summary(user, days=1)
message = ''
for d, summary in report.items():
message = message + '\n\n{}, total time {}'.format(
d.strftime('%d/%m/%Y %A'),
summary['format_total'],
)
for ticket in summary['tickets']:
message = message + '\n{}: {}, {} ({})'.format(
ticket['pk'],
ticket['contact'],
ticket['description'],
ticket['format_minutes'],
)
queue_mail_message(
user,
[user.email],
'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
message,
)
if users:
process_mail.delay()
| # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def mail_time_summary():
users = []
for item in InvoiceUser.objects.all():
if item.mail_time_summary and item.user.email:
users.append(item.user)
for user in users:
logger.info('mail_time_summary: {}'.format(user.username))
report = time_summary(user, days=1)
message = '<table border="0">'
for d, summary in report.items():
message = message + '<tr colspan="3">'
message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A'))
message = message + '</tr>'
for ticket in summary['tickets']:
message = message + '<tr>'
message = message + '<td>{}</td>'.format(ticket['pk'])
message = message + '<td>{}, {}</td>'.format(
ticket['contact'],
ticket['description'],
)
message = message + '<td>{}</td>'.format(
ticket['format_minutes'],
)
message = message + '</tr>'
message = message + '<tr>'
message = message + '<td></td><td></td>'
message = message + '<td><b>{}</b></td>'.format(
summary['format_total']
)
message = message + '</tr>'
message = message + '</table>'
queue_mail_message(
user,
[user.email],
'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
message,
)
if users:
process_mail.delay()
|
Allow Edit and Set of Slug Field | <div class="form-group">
<input type="text" id="name"
class="form-control input-lg"
name="name"
placeholder="Enter Page Title"
value="{{ old('name', $page->name) }}">
</div>
<div class="form-group no-margin">
<div class="input-group">
<span class="input-group-addon">
<strong>
Link:
</strong>
{{ url() }}/
</span>
<input type="text" class="form-control" name="slug" value="{{ old('slug', $page->slug) }}" id="slug-modify-field" readonly>
<span class="input-group-btn">
<a href="#" class="btn btn-default btn-flat" id="slug-modify-button">
Edit
</a>
</span>
@if ($page->link && !$page->trashed())
<span class="input-group-btn">
<a href="{{ url($page->link) }}" class="btn btn-default btn-flat">
View Page
</a>
</span>
@endif
</div>
</div>
@section('enqueued-js')
<script>
$(document).ready(function(){
$('#slug-modify-button').click(function(e){
e.preventDefault();
$field = $('#slug-modify-field');
if ($field.prop('readonly')) {
$field.prop('readonly', false);
$(this).text('Set');
return;
}
$field.prop('readonly', true);
$(this).text('Edit');
});
});
</script>
@append | <div class="form-group">
<input type="text" id="name"
class="form-control input-lg"
name="name"
placeholder="Enter Page Title"
value="{{ old('name', $page->name) }}">
</div>
<div class="form-group no-margin">
<div class="input-group">
<span class="input-group-addon">
<strong>
Link:
</strong>
{{ url() }}/
</span>
<input type="text" class="form-control" name="slug" value="{{ old('slug', $page->slug) }}" readonly>
<span class="input-group-btn">
<a href="#" class="btn btn-default btn-flat">
Edit
</a>
</span>
@if ($page->link && !$page->trashed())
<span class="input-group-btn">
<a href="{{ url($page->link) }}" class="btn btn-default btn-flat">
View Page
</a>
</span>
@endif
</div>
</div> |
Use SplFileInfo::isFile() method for checking if path is a file | <?php
namespace App\Controllers;
use PHLAK\Config\Config;
use Slim\Psr7\Response;
use SplFileInfo;
class FileInfoController
{
/** @var Config App configuration component */
protected $config;
/**
* Create a new FileInfoController object.
*
* @param \PHLAK\Config\Config $config
*/
public function __construct(Config $config)
{
$this->config = $config;
}
/**
* Invoke the FileInfoController.
*
* @param \Slim\Psr7\Response $response
* @param string $path
*/
public function __invoke(Response $response, string $path = '.')
{
$file = new SplFileInfo($path);
if (! $file->isFile()) {
return $response->withStatus(404, 'File not found');
}
if ($file->getSize() >= $this->config->get('app.max_hash_size', 1000000000)) {
return $response->withStatus(500, 'File size too large');
}
$response->getBody()->write(json_encode([
'hashes' => [
'md5' => hash('md5', file_get_contents($file->getPathname())),
'sha1' => hash('sha1', file_get_contents($file->getPathname())),
'sha256' => hash('sha256', file_get_contents($file->getPathname())),
]
]));
return $response->withHeader('Content-Type', 'application/json');
}
}
| <?php
namespace App\Controllers;
use PHLAK\Config\Config;
use Slim\Psr7\Response;
use SplFileInfo;
class FileInfoController
{
/** @var Config App configuration component */
protected $config;
/**
* Create a new FileInfoController object.
*
* @param \PHLAK\Config\Config $config
*/
public function __construct(Config $config)
{
$this->config = $config;
}
/**
* Invoke the FileInfoController.
*
* @param \Slim\Psr7\Response $response
* @param string $path
*/
public function __invoke(Response $response, string $path = '.')
{
if (! is_file($path)) {
return $response->withStatus(404, 'File not found');
}
$file = new SplFileInfo($path);
if ($file->getSize() >= $this->config->get('app.max_hash_size', 1000000000)) {
return $response->withStatus(500, 'File size too large');
}
$response->getBody()->write(json_encode([
'hashes' => [
'md5' => hash('md5', file_get_contents($file->getPathname())),
'sha1' => hash('sha1', file_get_contents($file->getPathname())),
'sha256' => hash('sha256', file_get_contents($file->getPathname())),
]
]));
return $response->withHeader('Content-Type', 'application/json');
}
}
|
Set dashboard as next state after logging in | (function () {
"use strict";
angular.module("mfl.auth.controllers", [
"mfl.auth.services",
"ui.router"
])
.controller("mfl.auth.controllers.login",
["$scope", "$sce", "$state", "mfl.auth.services.login",
function ($scope, $sce, $state, loginService) {
$scope.test = "Login";
$scope.login_err = "";
$scope.login_err_html = "";
$scope.submitUser = function(obj) {
var error_fxn = function (data) {
$scope.login_err = data.data.error_description || data.data.detail;
$scope.login_err_html = $sce.trustAsHtml($scope.login_err);
};
var success_fxn = function () {
$state.go("dashboard");
};
loginService.login(obj)
.then(
function () {
loginService.currentUser().then(success_fxn, error_fxn);
},
error_fxn
);
};
}
]);
})(angular);
| (function () {
"use strict";
angular.module("mfl.auth.controllers", [
"mfl.auth.services",
"ui.router"
])
.controller("mfl.auth.controllers.login",
["$scope", "$sce", "$state", "mfl.auth.services.login",
function ($scope, $sce, $state, loginService) {
$scope.test = "Login";
$scope.login_err = "";
$scope.login_err_html = "";
$scope.submitUser = function(obj) {
var error_fxn = function (data) {
$scope.login_err = data.data.error_description || data.data.detail;
$scope.login_err_html = $sce.trustAsHtml($scope.login_err);
};
var success_fxn = function () {
$state.go("home");
};
loginService.login(obj)
.then(
function () {
loginService.currentUser().then(success_fxn, error_fxn);
},
error_fxn
);
};
}
]);
})(angular);
|
Generalize method names to be compatible with Python 2.7 and 3.4 | import unittest
from utils import TextLoader
import numpy as np
from collections import Counter
class TestUtilsMethods(unittest.TestCase):
def setUp(self):
self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5)
def test_init(self):
print (self.data_loader.vocab)
print (self.data_loader.tensor)
print (self.data_loader.vocab_size)
def test_build_vocab(self):
sentences = ["I", "love", "cat", "cat"]
vocab, vocab_inv = self.data_loader.build_vocab(sentences)
print (vocab, vocab_inv)
# Must include I, love, and cat
self.assertEqual(Counter(list(vocab)), Counter(list(["I", "love", "cat"])))
self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1})
self.assertEqual(Counter(list(vocab_inv)), Counter(list(["I", "love", "cat"])))
def test_batch_vocab(self):
print (np.array(self.data_loader.x_batches).shape)
self.assertEqual(Counter(list(self.data_loader.x_batches[0][0][1:])),
Counter(list(self.data_loader.y_batches[0][0][:-1])))
self.assertEqual(Counter(list(self.data_loader.x_batches[0][1][1:])),
Counter(list(self.data_loader.y_batches[0][1][:-1])))
if __name__ == '__main__':
unittest.main()
| import unittest
from utils import TextLoader
import numpy as np
class TestUtilsMethods(unittest.TestCase):
def setUp(self):
self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5)
def test_init(self):
print (self.data_loader.vocab)
print (self.data_loader.tensor)
print (self.data_loader.vocab_size)
def test_build_vocab(self):
sentences = ["I", "love", "cat", "cat"]
vocab, vocab_inv = self.data_loader.build_vocab(sentences)
print (vocab, vocab_inv)
# Must include I, love, and cat
self.assertItemsEqual(vocab, ["I", "love", "cat"])
self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1})
self.assertItemsEqual(vocab_inv, ["I", "love", "cat"])
def test_batch_vocab(self):
print (np.array(self.data_loader.x_batches).shape)
self.assertItemsEqual(self.data_loader.x_batches[0][0][1:],
self.data_loader.y_batches[0][0][:-1])
self.assertItemsEqual(self.data_loader.x_batches[0][1][1:],
self.data_loader.y_batches[0][1][:-1])
if __name__ == '__main__':
unittest.main() |
Use find_packages to find migrations and management commands | #!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = ['Django>=1.5']
try:
from collections import OrderedDict
except ImportError:
install_requires.append('ordereddict>=1.1')
setup(
name='django-auth-policy',
version='0.9.5',
zip_safe=False,
description='Enforces a couple of common authentication policies for the '
'Django web framework.',
author='Fox-IT B.V.',
author_email='[email protected]',
maintainer='Rudolph Froger',
maintainer_email='[email protected]',
url='https://github.com/rudolphfroger/django-auth-policy',
license='BSD',
packages=find_packages(exclude=["testsite", "testsite.*", "*.tests", "*.tests.*", "tests.*", "tests"]),
package_data={'django_auth_policy': ['locale/*/LC_MESSAGES/*.mo',
'locale/*/LC_MESSAGES/*.po']},
install_requires=install_requires,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Topic :: Security',
'Topic :: Internet :: WWW/HTTP :: Session',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| #!/usr/bin/env python
from setuptools import setup
install_requires = ['Django>=1.5']
try:
from collections import OrderedDict
except ImportError:
install_requires.append('ordereddict>=1.1')
setup(
name='django-auth-policy',
version='0.9.4',
zip_safe=False,
description='Enforces a couple of common authentication policies for the '
'Django web framework.',
author='Fox-IT B.V.',
author_email='[email protected]',
maintainer='Rudolph Froger',
maintainer_email='[email protected]',
url='https://github.com/rudolphfroger/django-auth-policy',
license='BSD',
packages=['django_auth_policy'],
package_data={'django_auth_policy': ['locale/*/LC_MESSAGES/*.mo',
'locale/*/LC_MESSAGES/*.po']},
install_requires=install_requires,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'Topic :: Security',
'Topic :: Internet :: WWW/HTTP :: Session',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
|
Update sorl-thumbnail to latest version | #!/usr/bin/env python
from fancypages import __version__
from setuptools import setup, find_packages
setup(
name='django-fancypages',
version=__version__,
url='https://github.com/tangentlabs/django-fancypages',
author="Sebastian Vetter",
author_email="[email protected]",
description="Make content editing in Django fancier",
long_description='\n\n'.join([
open('README.rst').read(),
open('CHANGELOG.rst').read(),
]),
keywords="django, cms, pages, flatpages",
license='BSD',
platforms=['linux'],
packages=find_packages(exclude=["sandbox*", "tests*"]),
include_package_data=True,
install_requires=[
'Django>=1.5',
'South',
'unidecode',
'django-appconf',
'django-treebeard',
'django-model-utils',
'django-shortuuidfield',
# we are using DRF routers that are only available in
# DRF 2.3+ so we are restricting the version here
'djangorestframework>=2.3.10',
'pillow',
'sorl-thumbnail>=11.12.1b',
],
# See http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python',
]
)
| #!/usr/bin/env python
from fancypages import __version__
from setuptools import setup, find_packages
setup(
name='django-fancypages',
version=__version__,
url='https://github.com/tangentlabs/django-fancypages',
author="Sebastian Vetter",
author_email="[email protected]",
description="Make content editing in Django fancier",
long_description='\n\n'.join([
open('README.rst').read(),
open('CHANGELOG.rst').read(),
]),
keywords="django, cms, pages, flatpages",
license='BSD',
platforms=['linux'],
packages=find_packages(exclude=["sandbox*", "tests*"]),
include_package_data=True,
install_requires=[
'Django>=1.5',
'South',
'unidecode',
'django-appconf',
'django-treebeard',
'django-model-utils',
'django-shortuuidfield',
# we are using DRF routers that are only available in
# DRF 2.3+ so we are restricting the version here
'djangorestframework>=2.3.10',
'pillow',
'sorl-thumbnail>=11.12',
],
# See http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python',
]
)
|
[Address] Clean all inputs before filling in the address | /*
* 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.
*/
(function ( $ ) {
$.fn.extend({
addressBook: function () {
var element = $(this);
var addresses = [];
var select = element.find('.address-book-select');
select.dropdown({
apiSettings: {
action: 'address book',
cache: false,
onResponse: function (syliusResponse) {
var response = {
success: true,
results: []
};
$.each(syliusResponse, function (index, address) {
addresses.push(address);
response.results.push({
name: address.city + ' ' + address.street,
value: address.id
});
});
return response;
}
},
onChange: function (name, text, choice) {
var selectedAddress = addresses.filter(function (address) {
return address.id === choice.data().value;
})[0];
var inputs = element.find('input');
$.each(inputs, function (key, input) {
$(input).val('');
});
$.each(selectedAddress, function (key, property) {
element.find('input[name*='+ parseKey(key) +']').val(property);
});
}
});
var parseKey = function (key) {
return key.replace(/(_\w)/g, function (m) {return m[1].toUpperCase()});
}
}
});
})( jQuery );
| /*
* 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.
*/
(function ( $ ) {
$.fn.extend({
addressBook: function () {
var element = $(this);
var addresses = [];
var select = element.find('.address-book-select');
select.dropdown({
apiSettings: {
action: 'address book',
cache: false,
onResponse: function (syliusResponse) {
var response = {
success: true,
results: []
};
$.each(syliusResponse, function (index, address) {
addresses.push(address);
console.log(address);
response.results.push({
name: address.city + ' ' + address.street,
value: address.id
});
});
return response;
}
},
onChange: function (name, text, choice) {
var selectedAddress = addresses.filter(function (address) {
return address.id === choice.data().value;
})[0];
$.each(selectedAddress, function (key, property) {
element.find('input[name*='+ parseKey(key) +']').val(property);
});
}
});
var parseKey = function (key) {
return key.replace(/(_\w)/g, function (m) {return m[1].toUpperCase()});
}
}
});
})( jQuery );
|
Use Bukkit.getPlayerExact(String) rather than Bukkit.getPlayer(String) | package fr.aumgn.bukkitutils.playerid;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public final class PlayerId {
private static final Map<String, PlayerId> accounts =
new HashMap<String, PlayerId>();
public static PlayerId get(OfflinePlayer player) {
return get(player.getName());
}
public static PlayerId get(String name) {
String lname = name.toLowerCase(Locale.ENGLISH);
if (!accounts.containsKey(lname)) {
accounts.put(lname, new PlayerId(lname));
}
return accounts.get(lname);
}
private final String name;
private PlayerId(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isOnline() {
return (getPlayer() != null);
}
public boolean isOffline() {
return (getPlayer() == null);
}
public Player getPlayer() {
return Bukkit.getPlayerExact(name);
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(name);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof PlayerId)) {
return false;
}
return name.equals(((PlayerId) other).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}
| package fr.aumgn.bukkitutils.playerid;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public final class PlayerId {
private static final Map<String, PlayerId> accounts =
new HashMap<String, PlayerId>();
public static PlayerId get(OfflinePlayer player) {
return get(player.getName());
}
public static PlayerId get(String name) {
String lname = name.toLowerCase(Locale.ENGLISH);
if (!accounts.containsKey(lname)) {
accounts.put(lname, new PlayerId(lname));
}
return accounts.get(lname);
}
private final String name;
private PlayerId(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isOnline() {
return (getPlayer() != null);
}
public boolean isOffline() {
return (getPlayer() == null);
}
public Player getPlayer() {
return Bukkit.getPlayer(name);
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(name);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof PlayerId)) {
return false;
}
return name.equals(((PlayerId) other).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}
|
Fix amdDefine patch to check for backboneCandidate | // @private
// Calls the callback passing to it the Backbone object every time it's detected.
// The function uses multiple methods of detection.
var patchDefine = function(callback) {
// AMD
patchFunctionLater(window, "define", function(originalFunction) { return function() {
// function arguments: (id? : String, dependencies? : Array, factory : Function)
// make arguments editable
var argumentsArray = Array.prototype.slice.call(arguments);
// find the factory function to patch it
for (var i=0,l=argumentsArray.length; i<l; i++) {
if (typeof argumentsArray[i] == "function") {
// factory function found, patch it.
// NOTE: in the patcher function, specify the parameters for the
// default modules, or in case of a module with no dependencies but
// that uses the default modules internally, the original define would see a 0-arity
// function and would call it without them (see define() in the AMD API)
patchFunction(argumentsArray, i, function(originalFunction) {
return function(require, exports, modules) {
var module = originalFunction.apply(this, arguments);
// check if Backbone has been defined by the factory fuction
// (some factories set "this" to Backbone)
var BackboneCandidate = module || this;//
var isBackbone = isObject(BackboneCandidate) &&
typeof BackboneCandidate.View == "function" &&
typeof BackboneCandidate.Model == "function" &&
typeof BackboneCandidate.Collection == "function" &&
typeof BackboneCandidate.Router == "function";
if (isBackbone) {
callback(BackboneCandidate);
}
return module;
}});
break;
}
}
return originalFunction.apply(this, argumentsArray);
}});
};
| // @private
// Calls the callback passing to it the Backbone object every time it's detected.
// The function uses multiple methods of detection.
var patchDefine = function(callback) {
// AMD
patchFunctionLater(window, "define", function(originalFunction) { return function() {
// function arguments: (id? : String, dependencies? : Array, factory : Function)
// make arguments editable
var argumentsArray = Array.prototype.slice.call(arguments);
// find the factory function to patch it
for (var i=0,l=argumentsArray.length; i<l; i++) {
if (typeof argumentsArray[i] == "function") {
// factory function found, patch it.
// NOTE: in the patcher function, specify the parameters for the
// default modules, or in case of a module with no dependencies but
// that uses the default modules internally, the original define would see a 0-arity
// function and would call it without them (see define() in the AMD API)
patchFunction(argumentsArray, i, function(originalFunction) {
return function(require, exports, modules) {
var module = originalFunction.apply(this, arguments);
// check if Backbone has been defined by the factory fuction
// (some factories set "this" to Backbone)
var BackboneCandidate = module || this;
callback(BackboneCandidate);
return module;
}});
break;
}
}
return originalFunction.apply(this, argumentsArray);
}});
}; |
Add Access Rules in AudioConference controller | <?php
/**
* oskr-portal
* Created: 11.05.17 12:44
* @copyright Copyright (c) 2017 OSKR NIAEP
*/
namespace frontend\controllers;
use frontend\models\audioconference\AudioConferenceService;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
/**
* Class AudioConferenceController
*
* @author Shubnikov Alexey <[email protected]>
*
*/
class AudioConferenceController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'actions' => ['index', 'create', 'delete'],
'roles' => ['@'],
],
]
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'create' => ['post'],
'delete' => ['post', 'delete']
]
]
];
}
public function actionIndex()
{
return $this->render('index', ['conference' => (new AudioConferenceService())->getConferenceByUserId(\Yii::$app->user->getId())]);
}
public function actionCreate()
{
return $this->render('index', ['conference' => (new AudioConferenceService())->createConferenceForUser(\Yii::$app->user->getId())]);
}
public function actionDelete()
{
(new AudioConferenceService())->deleteConferenceForUser(\Yii::$app->user->getId());
return $this->render('index', ['conference' => null]);
}
} | <?php
/**
* oskr-portal
* Created: 11.05.17 12:44
* @copyright Copyright (c) 2017 OSKR NIAEP
*/
namespace frontend\controllers;
use frontend\models\audioconference\AudioConferenceService;
use yii\web\Controller;
use yii\filters\VerbFilter;
/**
* Class AudioConferenceController
*
* @author Shubnikov Alexey <[email protected]>
*
*/
class AudioConferenceController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'create' => ['post'],
'delete' => ['post', 'delete']
]
]
];
}
public function actionIndex()
{
return $this->render('index', ['conference' => (new AudioConferenceService())->getConferenceByUserId(\Yii::$app->user->getId())]);
}
public function actionCreate()
{
return $this->render('index', ['conference' => (new AudioConferenceService())->createConferenceForUser(\Yii::$app->user->getId())]);
}
public function actionDelete()
{
(new AudioConferenceService())->deleteConferenceForUser(\Yii::$app->user->getId());
return $this->render('index', ['conference' => null]);
}
} |
Return `parent::newQuery();` is not using `withTrashed` or `onlyTrashed` | <?php
/**
* Laravel 4 Repository classes
*
* @author Andreas Lutro <[email protected]>
* @license http://opensource.org/licenses/MIT
* @package l4-repository
*/
namespace anlutro\LaravelRepository;
use Illuminate\Database\Eloquent\Model;
class SoftDeletingEloquentRepository extends EloquentRepository
{
/**
* @var boolean
*/
protected $onlyTrashed = false;
/**
* @var boolean
*/
protected $withTrashed = false;
/**
* @param \Illuminate\Database\Eloquent\Model $model
*/
public function restore($model)
{
$model->restore();
}
/**
* Limit to trashed entities.
*/
public function onlyTrashed()
{
$this->onlyTrashed = true;
$this->withTrashed = false;
}
/**
* Return trashed entites aswell.
*/
public function withTrashed()
{
$this->onlyTrashed = false;
$this->withTrashed = true;
}
/**
* {@inheritdoc}
*
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function newQuery()
{
if ($this->onlyTrashed === true) {
return call_user_func([$this->model, 'onlyTrashed']);
}
if ($this->withTrashed === true) {
return call_user_func([$this->model, 'withTrashed']);
}
return parent::newQuery();
}
}
| <?php
/**
* Laravel 4 Repository classes
*
* @author Andreas Lutro <[email protected]>
* @license http://opensource.org/licenses/MIT
* @package l4-repository
*/
namespace anlutro\LaravelRepository;
use Illuminate\Database\Eloquent\Model;
class SoftDeletingEloquentRepository extends EloquentRepository
{
/**
* @var boolean
*/
protected $onlyTrashed = false;
/**
* @var boolean
*/
protected $withTrashed = false;
/**
* @param \Illuminate\Database\Eloquent\Model $model
*/
public function restore($model)
{
$model->restore();
}
/**
* Limit to trashed entities.
*/
public function onlyTrashed()
{
$this->onlyTrashed = true;
$this->withTrashed = false;
}
/**
* Return trashed entites aswell.
*/
public function withTrashed()
{
$this->onlyTrashed = false;
$this->withTrashed = true;
}
/**
* {@inheritdoc}
*
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function newQuery()
{
if ($this->onlyTrashed === true) {
return call_user_func([$this->model, 'onlyTrashed']);
}
if ($this->withTrashed === true) {
return call_user_func([$this->model, 'withTrashed']);
}
return $this->model->newQuery();
}
}
|
Use compat for unicode import | """Coordination chatroom game."""
import dallinger as dlgr
from dallinger.compat import unicode
from dallinger.config import get_config
config = get_config()
def extra_settings():
config.register('network', unicode)
config.register('n', int)
class CoordinationChatroom(dlgr.experiments.Experiment):
"""Define the structure of the experiment."""
def __init__(self, session):
"""Initialize the experiment."""
super(CoordinationChatroom, self).__init__(session)
self.experiment_repeats = 1
self.num_participants = config.get('n')
self.initial_recruitment_size = self.num_participants
self.quorum = self.num_participants
self.config = config
if not self.config.ready:
self.config.load_config()
self.setup()
def create_network(self):
"""Create a new network by reading the configuration file."""
class_ = getattr(
dlgr.networks,
self.config.get('network')
)
return class_(max_size=self.num_participants)
def info_post_request(self, node, info):
"""Run when a request to create an info is complete."""
for agent in node.neighbors():
node.transmit(what=info, to_whom=agent)
def create_node(self, participant, network):
"""Create a node for a participant."""
return dlgr.nodes.Agent(network=network, participant=participant)
| """Coordination chatroom game."""
import dallinger as dlgr
from dallinger.config import get_config
try:
unicode = unicode
except NameError: # Python 3
unicode = str
config = get_config()
def extra_settings():
config.register('network', unicode)
config.register('n', int)
class CoordinationChatroom(dlgr.experiments.Experiment):
"""Define the structure of the experiment."""
def __init__(self, session):
"""Initialize the experiment."""
super(CoordinationChatroom, self).__init__(session)
self.experiment_repeats = 1
self.num_participants = config.get('n')
self.initial_recruitment_size = self.num_participants
self.quorum = self.num_participants
self.config = config
if not self.config.ready:
self.config.load_config()
self.setup()
def create_network(self):
"""Create a new network by reading the configuration file."""
class_ = getattr(
dlgr.networks,
self.config.get('network')
)
return class_(max_size=self.num_participants)
def info_post_request(self, node, info):
"""Run when a request to create an info is complete."""
for agent in node.neighbors():
node.transmit(what=info, to_whom=agent)
def create_node(self, participant, network):
"""Create a node for a participant."""
return dlgr.nodes.Agent(network=network, participant=participant)
|
Fix filename creation in csv export action |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
if label:
self.short_description = label
def __call__(self, admin, request, queryset):
if self.serialiser is None:
ser_class = modelserialiser_factory(
'%sSerialiser' % admin.__class__.__name__,
admin.model,
**self.opts
)
else:
ser_class = self.serialiser
def inner(ser):
csv = CSV(fields=ser._fields.keys())
yield csv.write_headers()
for obj in queryset:
data = {
key: force_text(val)
for key, val in ser.object_deflate(obj).items()
}
yield csv.write_dict(data)
response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv')
filename = self.opts.get('filename', 'export_{classname}.csv')
if callable(filename):
filename = filename(admin)
else:
filename = filename.format(
classname=admin.__class__.__name__,
model=admin.model._meta.module_name,
app_label=admin.model._meta.app_label,
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
|
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
if label:
self.short_description = label
def __call__(self, admin, request, queryset):
if self.serialiser is None:
ser_class = modelserialiser_factory(
'%sSerialiser' % admin.__class__.__name__,
admin.model,
**self.opts
)
else:
ser_class = self.serialiser
def inner(ser):
csv = CSV(fields=ser._fields.keys())
yield csv.write_headers()
for obj in queryset:
data = {
key: force_text(val)
for key, val in ser.object_deflate(obj).items()
}
yield csv.write_dict(data)
response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv')
filename = admin.csv_
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
|
Revert "Return utf-8, not ascii."
This reverts commit 86cbefc74471e4c991c96e0385b931a2a20f5d50.
Former-commit-id: 3246e0bfefb806bd2b4d3dda0cb77e91f3481971 | from falcon.util.uri import parse_query_string
import json
from api.actions import pos_tagging
class ApiResource(object):
def parse_request_data(self, raw_post_data):
encoded_raw_post_data = ""
try:
encoded_raw_post_data = str(raw_post_data, 'utf-8')
except UnicodeDecodeError:
try:
encoded_raw_post_data = str(raw_post_data, 'latin-1')
except UnicodeDecodeError:
pass
return encoded_raw_post_data
def on_post(self, request, response):
body = request.stream.read()
encoded_raw_post_data = self.parse_request_data(body)
pretty = request.get_param("pretty")
if not pretty:
pretty = parse_query_string(encoded_raw_post_data).get("pretty", False)
data = request.get_param("data")
if not data:
data = parse_query_string(encoded_raw_post_data).get("data", False)
if not data:
data = encoded_raw_post_data
if not data:
return {"error": "No data posted or data incorrectly encoded"}
tagged_json = pos_tagging(data)
json_kwargs = {"separators": (',', ':')}
if pretty:
json_kwargs = {"indent": 4, "separators": (', ', ': ')}
response.body = json.dumps(tagged_json, **json_kwargs)
| from falcon.util.uri import parse_query_string
import json
from api.actions import pos_tagging
class ApiResource(object):
def parse_request_data(self, raw_post_data):
encoded_raw_post_data = ""
try:
encoded_raw_post_data = str(raw_post_data, 'utf-8')
except UnicodeDecodeError:
try:
encoded_raw_post_data = str(raw_post_data, 'latin-1')
except UnicodeDecodeError:
pass
return encoded_raw_post_data
def on_post(self, request, response):
body = request.stream.read()
encoded_raw_post_data = self.parse_request_data(body)
pretty = request.get_param("pretty")
if not pretty:
pretty = parse_query_string(encoded_raw_post_data).get("pretty", False)
data = request.get_param("data")
if not data:
data = parse_query_string(encoded_raw_post_data).get("data", False)
if not data:
data = encoded_raw_post_data
if not data:
return {"error": "No data posted or data incorrectly encoded"}
tagged_json = pos_tagging(data)
json_kwargs = {
"separators": (',', ':'),
"ensure_ascii": False,
}
if pretty:
json_kwargs["indent"] = 4
json_kwargs["separators"] = (', ', ': ')
response.body = json.dumps(tagged_json, **json_kwargs)
|
Add source maps to get better debugging in the browser | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
},
devtool: "source-map"
}
| const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
}
}
|
Add divider to the list | import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Divider } from "@blueprintjs/core";
import { EntriesShape } from "../prop-types/entry.js";
import Entry from "./Entry.js";
import { List, AutoSizer } from "react-virtualized";
class Entries extends PureComponent {
rowRenderer = ({ key, index, style }) => {
const { entries, onSelectEntry, autoLoginEnabled = true } = this.props;
return (
<div style={style} key={key}>
<Entry entry={entries[index]} onSelectEntry={onSelectEntry} autoLoginEnabled={autoLoginEnabled} />
<Divider />
</div>
);
};
render() {
const { entries } = this.props;
return (
<AutoSizer>
{({ height, width }) => (
<List
width={width}
height={height}
rowCount={entries.length}
rowHeight={66}
rowRenderer={this.rowRenderer}
overscanRowCount={10}
/>
)}
</AutoSizer>
);
}
}
Entries.propTypes = {
entries: EntriesShape,
sourcesUnlocked: PropTypes.number,
autoLoginEnabled: PropTypes.bool,
onSelectEntry: PropTypes.func.isRequired
};
export default Entries;
| import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { EntriesShape } from "../prop-types/entry.js";
import Entry from "./Entry.js";
import { List, AutoSizer } from "react-virtualized";
class Entries extends PureComponent {
rowRenderer = ({ key, index, style }) => {
const { entries, onSelectEntry, autoLoginEnabled = true } = this.props;
return (
<div style={style} key={key}>
<Entry entry={entries[index]} onSelectEntry={onSelectEntry} autoLoginEnabled={autoLoginEnabled} />
</div>
);
};
render() {
const { entries } = this.props;
return (
<AutoSizer>
{({ height, width }) => (
<List
width={width}
height={height}
rowCount={entries.length}
rowHeight={66}
rowRenderer={this.rowRenderer}
overscanRowCount={10}
/>
)}
</AutoSizer>
);
}
}
Entries.propTypes = {
entries: EntriesShape,
sourcesUnlocked: PropTypes.number,
autoLoginEnabled: PropTypes.bool,
onSelectEntry: PropTypes.func.isRequired
};
export default Entries;
|
Allow empty input to terminate testing | package ch.poole.openinghoursparser;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Scanner;
/**
* Individual testing for the OpeningHoursParser, receiving inputs from System.in
*
*
* @author Vuong Ho
*
*/
public class IndividualTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean isStrict = args[0].equals("true");
System.out.println("Parse strings in opening-hours format, empty input will terminate");
while (true) {
System.out.print("Please enter your input: ");
String input = sc.nextLine();
if ("".equals(input)) {
break;
}
try {
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(input.getBytes()));
List<ch.poole.openinghoursparser.Rule> rules = parser.rules(isStrict);
System.out.println("Legal input string");
System.out.println("Detected rules in input string listed below");
System.out.println("\n------------------------------\n");
for (ch.poole.openinghoursparser.Rule rule : rules) {
System.out.println(rule.toDebugString());
}
System.out.println("\n------------------------------\n");
} catch (OpeningHoursParseException e) {
System.out.println("Illegal input string");
e.printStackTrace();
System.out.println("\n------------------------------\n");
}
}
}
} | package ch.poole.openinghoursparser;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Scanner;
/**
* Individual testing for the OpeningHoursParser, receiving
* inputs from System.in
*
*
* @author Vuong Ho
*
*/
public class IndividualTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean isStrict = args[0].equals("true");
while(true) {
System.out.print("Please enter your input: ");
String input = sc.nextLine();
try {
OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(input.getBytes()));
List<ch.poole.openinghoursparser.Rule> rules = parser.rules(isStrict);
System.out.println("Legal input string");
System.out.println("Detected rules in input string listed below");
for(ch.poole.openinghoursparser.Rule rule : rules) {
System.out.println(rule.toDebugString());
}
System.out.println("\n------------------------------\n");
} catch (OpeningHoursParseException e) {
System.out.println("Illegal input string");
e.printStackTrace();
System.out.println("\n------------------------------\n");
}
}
}
} |
Change locale support for Laravel 5.4 | <?php namespace Someline\Support\Controllers;
/**
* Created for someline-starter.
* User: Libern
*/
use Carbon\Carbon;
use Illuminate\Http\Request;
use Someline\Base\Http\Controllers\Controller;
class LocaleController extends Controller
{
/**
* @param Request $request
* @param $locale
* @return \Illuminate\Http\Response
*/
public function getLocaleJs(Request $request, $locale)
{
$content = 'window.Someline.locales = ' . json_encode(trans('app', [], $locale));
$response = response()->make($content);
$response->header('Content-Type', 'application/javascript');
$response->setPublic()
->setMaxAge(604800)
->setExpires(Carbon::now()->addDay(7));
return $response;
}
/**
* @param Request $request
* @param $locale
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function getSwitchLocale(Request $request, $locale)
{
// check if supported
$supportedLanguagesKeys = \LaravelLocalization::getSupportedLanguagesKeys();
if (!in_array($locale, $supportedLanguagesKeys)) {
abort(404);
}
// store in session
session(['someline-locale' => $locale]);
// check if has redirect url
$redirect_url = '/';
if ($request->has('redirect_url')) {
$redirect_url = $request->get('redirect_url');
}
return redirect($redirect_url);
}
} | <?php namespace Someline\Support\Controllers;
/**
* Created for someline-starter.
* User: Libern
*/
use Carbon\Carbon;
use Illuminate\Http\Request;
use Someline\Base\Http\Controllers\Controller;
class LocaleController extends Controller
{
/**
* @param Request $request
* @param $locale
* @return \Illuminate\Http\Response
*/
public function getLocaleJs(Request $request, $locale)
{
$content = 'window.Someline.locales = ' . json_encode(trans('app', [], 'messages', $locale));
$response = response()->make($content);
$response->header('Content-Type', 'application/javascript');
$response->setPublic()
->setMaxAge(604800)
->setExpires(Carbon::now()->addDay(7));
return $response;
}
/**
* @param Request $request
* @param $locale
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function getSwitchLocale(Request $request, $locale)
{
// check if supported
$supportedLanguagesKeys = \LaravelLocalization::getSupportedLanguagesKeys();
if (!in_array($locale, $supportedLanguagesKeys)) {
abort(404);
}
// store in session
session(['someline-locale' => $locale]);
// check if has redirect url
$redirect_url = '/';
if ($request->has('redirect_url')) {
$redirect_url = $request->get('redirect_url');
}
return redirect($redirect_url);
}
} |
Fix course id separator at export all courses command | """
Script for exporting all courseware from Mongo to a directory
"""
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
class Command(BaseCommand):
"""Export all courses from mongo to the specified data directory"""
help = 'Export all courses from mongo to the specified data directory'
def handle(self, *args, **options):
"Execute the command"
if len(args) != 1:
raise CommandError("export requires one argument: <output path>")
output_path = args[0]
cs = contentstore()
ms = modulestore('direct')
root_dir = output_path
courses = ms.get_courses()
print("%d courses to export:" % len(courses))
cids = [x.id for x in courses]
print(cids)
for course_id in cids:
print("-"*77)
print("Exporting course id = {0} to {1}".format(course_id, output_path))
if 1:
try:
course_dir = course_id.to_deprecated_string().replace('/', '...')
export_to_xml(ms, cs, course_id, root_dir, course_dir, modulestore())
except Exception as err:
print("="*30 + "> Oops, failed to export %s" % course_id)
print("Error:")
print(err)
| """
Script for exporting all courseware from Mongo to a directory
"""
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
class Command(BaseCommand):
"""Export all courses from mongo to the specified data directory"""
help = 'Export all courses from mongo to the specified data directory'
def handle(self, *args, **options):
"Execute the command"
if len(args) != 1:
raise CommandError("export requires one argument: <output path>")
output_path = args[0]
cs = contentstore()
ms = modulestore('direct')
root_dir = output_path
courses = ms.get_courses()
print("%d courses to export:" % len(courses))
cids = [x.id for x in courses]
print(cids)
for course_id in cids:
print("-"*77)
print("Exporting course id = {0} to {1}".format(course_id, output_path))
if 1:
try:
course_dir = course_id.replace('/', '...')
export_to_xml(ms, cs, course_id, root_dir, course_dir, modulestore())
except Exception as err:
print("="*30 + "> Oops, failed to export %s" % course_id)
print("Error:")
print(err)
|
Fix bug which caused shots to be fired at the wrong board
Postgres (SQL) makes no promises regarding what order rows are stored /
returned, so we need to sort them if we are to make the assumption that
the 'first board' belongs to player 1. | function coordinatesToString(x, y) {
return x + ',' + y;
}
module.exports = function(sequelize, DataTypes) {
var Game = sequelize.define('Game', {
player1: {type: DataTypes.STRING},
player2: {type: DataTypes.STRING},
next: {type: DataTypes.STRING},
lastMove: {type: DataTypes.STRING, allowNull: false, defaultValue: '-1,-1'},
finished: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false}
}, {
classMethods: {
associate: function (models) {
Game.hasMany(models.Board);
}
},
instanceMethods: {
fire: function (player, x, y) {
function byId(game1, game2) {
return game1.id > game2.id;
}
if (player === this.player1) {
this.next = this.player2;
this.lastMove = coordinatesToString(x, y);
this.save();
return this.Boards.sort(byId)[1].fire(x, y);
} else if (player === this.player2) {
this.next = this.player1;
this.lastMove = coordinatesToString(x, y);
this.save();
return this.Boards.sort(byId)[0].fire(x, y);
}
},
},
getterMethods: {
gameOver: function() {
return this.Boards[0].gameOver || this.Boards[1].gameOver;
}
}
});
return Game;
};
| function coordinatesToString(x, y) {
return x + ',' + y;
}
module.exports = function(sequelize, DataTypes) {
var Game = sequelize.define('Game', {
player1: {type: DataTypes.STRING},
player2: {type: DataTypes.STRING},
next: {type: DataTypes.STRING},
lastMove: {type: DataTypes.STRING, allowNull: false, defaultValue: '-1,-1'},
finished: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false}
}, {
classMethods: {
associate: function (models) {
Game.hasMany(models.Board);
}
},
instanceMethods: {
fire: function (player, x, y) {
if (player === this.player1) {
this.next = this.player2;
this.lastMove = coordinatesToString(x, y);
this.save();
return this.Boards[1].fire(x, y);
} else if (player === this.player2) {
this.next = this.player1;
this.lastMove = coordinatesToString(x, y);
this.save();
return this.Boards[0].fire(x, y);
}
},
},
getterMethods: {
gameOver: function() {
return this.Boards[0].gameOver || this.Boards[1].gameOver;
}
}
});
return Game;
};
|
Move _hal_regex to class scope. | #!/usr/bin/env python
# encoding: utf-8
import json
import re
from .resource import Resource
class Response(Resource):
"""Represents an HTTP response that is hopefully a HAL document."""
_hal_regex = re.compile(r"application/hal\+json")
def __init__(self, response):
"""Pass it a Requests response object.
:response: A response object from the Requests library.
"""
self._response = response
self._parsed_hal = None
def is_hal(self):
"""Test if a response was a HAL document or not.
:returns: True or False
"""
return bool(self._hal_regex.match(self._response.headers['content-type']))
@property
def _hal(self):
"""Returns the parsed HAL body of the response
:returns: A parsed HAL body (dicts and lists) or an empty dictionary.
"""
if self._parsed_hal != None: return self._parsed_hal
self._parsed_hal = self._parse_hal()
return self._parsed_hal
def _parse_hal(self):
"""Parses the JSON body of the response.
:returns: A parsed JSON body (dicts and lists) or an empty dictionary.
"""
if not self.is_hal(): return {}
try:
return json.loads(self._response.content)
except ValueError, e:
return {}
| #!/usr/bin/env python
# encoding: utf-8
import json
import re
from .resource import Resource
class Response(Resource):
"""Represents an HTTP response that is hopefully a HAL document."""
def __init__(self, response):
"""Pass it a Requests response object.
:response: A response object from the Requests library.
"""
self._response = response
self._hal_regex = re.compile(r"application/hal\+json")
self._parsed_hal = None
def is_hal(self):
"""Test if a response was a HAL document or not.
:returns: True or False
"""
return bool(self._hal_regex.match(self._response.headers['content-type']))
@property
def _hal(self):
"""Returns the parsed HAL body of the response
:returns: A parsed HAL body (dicts and lists) or an empty dictionary.
"""
if self._parsed_hal != None: return self._parsed_hal
self._parsed_hal = self._parse_hal()
return self._parsed_hal
def _parse_hal(self):
"""Parses the JSON body of the response.
:returns: A parsed JSON body (dicts and lists) or an empty dictionary.
"""
if not self.is_hal(): return {}
try:
return json.loads(self._response.content)
except ValueError, e:
return {}
|
Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency | #!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
"EurysCore", # replaced by SlimevoidLib?
))
DEP_ADDITIONS = {
"gregtech": ["IC2"],
"MineFactoryReloaded": ["PowerCrystalsCore"],
"NetherOres": ["PowerCrystalsCore"],
"PowerConverters": ["PowerCrystalsCore"],
"FlatBedrock": ["PowerCrystalsCore"],
"immibis-microblocks": ["ImmibisCore"],
"SlopesAndCorners": ["SlimevoidLib"],
}
def getExtraDeps(mod):
for k, v in DEP_ADDITIONS.iteritems():
if mod.startswith(k):
return set(v)
return set()
def fixDeps(mod, deps):
deps = set(deps)
deps -= DEP_BLACKLIST
deps |= getExtraDeps(mod)
return deps
MOD_IDS = {
"PowerCrystalsCore": ["PowerCrystalsCore"],
}
def fixModIDs(mod, ids):
for k, v in MOD_IDS.iteritems():
if mod.startswith(k):
return v
return ids
COREMODS = ["PowerCrystalsCore", "immibis-microblocks"]
def isCoremod(fn):
for k in COREMODS:
if fn.startswith(k):
return True
return False
| #!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
))
DEP_ADDITIONS = {
"gregtech": ["IC2"],
"MineFactoryReloaded": ["PowerCrystalsCore"],
"NetherOres": ["PowerCrystalsCore"],
"PowerConverters": ["PowerCrystalsCore"],
"FlatBedrock": ["PowerCrystalsCore"],
"immibis-microblocks": ["ImmibisCore"],
}
def getExtraDeps(mod):
for k, v in DEP_ADDITIONS.iteritems():
if mod.startswith(k):
return set(v)
return set()
def fixDeps(mod, deps):
deps = set(deps)
deps -= DEP_BLACKLIST
deps |= getExtraDeps(mod)
return deps
MOD_IDS = {
"PowerCrystalsCore": ["PowerCrystalsCore"],
}
def fixModIDs(mod, ids):
for k, v in MOD_IDS.iteritems():
if mod.startswith(k):
return v
return ids
COREMODS = ["PowerCrystalsCore", "immibis-microblocks"]
def isCoremod(fn):
for k in COREMODS:
if fn.startswith(k):
return True
return False
|
Remove argument defaulting from Version()
It was moved to the ABC and subsequently the check was left behind. | from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
| from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
def __init__(self, ns, config):
super(GitVersion, self).__init__(ns, config)
if 'arguments' not in config:
self.config.arguments = None
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
|
Add statsd data for (in)secure requests | from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, view_args, view_kwargs):
super(GraphiteViewHitCountMiddleware, self).process_view(
request, view_func, view_args, view_kwargs)
if hasattr(request, '_view_name'):
secure = 'secure' if request.is_secure() else 'insecure'
data = dict(module=request._view_module, name=request._view_name,
method=request.method, secure=secure)
statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{name}.{method}'.format(**data))
statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{method}'.format(**data))
statsd.incr('view.count.{method}.{secure}'.format(**data))
statsd.incr('view.count.{method}'.format(**data))
class HostnameMiddleware(object):
def __init__(self):
values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',
'DEIS_RELEASE', 'DEIS_DOMAIN']]
self.backend_server = '.'.join(x for x in values if x)
def process_response(self, request, response):
response['X-Backend-Server'] = self.backend_server
return response
| from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, view_args, view_kwargs):
super(GraphiteViewHitCountMiddleware, self).process_view(
request, view_func, view_args, view_kwargs)
if hasattr(request, '_view_name'):
data = dict(module=request._view_module, name=request._view_name,
method=request.method)
statsd.incr('view.count.{module}.{name}.{method}'.format(**data))
statsd.incr('view.count.{module}.{method}'.format(**data))
statsd.incr('view.count.{method}'.format(**data))
class HostnameMiddleware(object):
def __init__(self):
values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',
'DEIS_RELEASE', 'DEIS_DOMAIN']]
self.backend_server = '.'.join(x for x in values if x)
def process_response(self, request, response):
response['X-Backend-Server'] = self.backend_server
return response
|
BB-4189: Create listener for all entities in website search
- used correct mapping provider
- removed website restriction
- fixed functional test | <?php
namespace Oro\Bundle\SearchBundle\EventListener;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\UnitOfWork;
use Oro\Bundle\SearchBundle\Provider\AbstractSearchMappingProvider;
/**
* This trait contains common code that repeats in
* the listeners used for creating indexes.
*/
trait IndexationListenerTrait
{
/**
* @var AbstractSearchMappingProvider
*/
protected $mappingProvider;
/**
* @param UnitOfWork $uow
*
* @return object[]
*/
protected function getEntitiesWithUpdatedIndexedFields(UnitOfWork $uow)
{
$entitiesToReindex = [];
foreach ($uow->getScheduledEntityUpdates() as $hash => $entity) {
$className = ClassUtils::getClass($entity);
if (!$this->mappingProvider->hasFieldsMapping($className)) {
continue;
}
$entityConfig = $this->mappingProvider->getEntityConfig($className);
$indexedFields = [];
foreach ($entityConfig['fields'] as $fieldConfig) {
$indexedFields[] = $fieldConfig['name'];
}
$changeSet = $uow->getEntityChangeSet($entity);
$fieldsToReindex = array_intersect($indexedFields, array_keys($changeSet));
if ($fieldsToReindex) {
$entitiesToReindex[$hash] = $entity;
}
}
return $entitiesToReindex;
}
}
| <?php
namespace Oro\Bundle\SearchBundle\EventListener;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\UnitOfWork;
use Oro\Bundle\SearchBundle\Provider\SearchMappingProvider;
/**
* This trait contains common code that repeats in
* the listeners used for creating indexes.
*/
trait IndexationListenerTrait
{
/**
* @var SearchMappingProvider
*/
protected $mappingProvider;
/**
* @param UnitOfWork $uow
*
* @return object[]
*/
protected function getEntitiesWithUpdatedIndexedFields(UnitOfWork $uow)
{
$entitiesToReindex = [];
foreach ($uow->getScheduledEntityUpdates() as $hash => $entity) {
$className = ClassUtils::getClass($entity);
if (!$this->mappingProvider->hasFieldsMapping($className)) {
continue;
}
$entityConfig = $this->mappingProvider->getEntityConfig($className);
$indexedFields = [];
foreach ($entityConfig['fields'] as $fieldConfig) {
$indexedFields[] = $fieldConfig['name'];
}
$changeSet = $uow->getEntityChangeSet($entity);
$fieldsToReindex = array_intersect($indexedFields, array_keys($changeSet));
if ($fieldsToReindex) {
$entitiesToReindex[$hash] = $entity;
}
}
return $entitiesToReindex;
}
}
|
Add camera selection based on desired feed and camera number | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,PIN_MAP_FEED1,PIN_MAP_FEED2]
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('camera_feed_selection',CameraFeedSelection, self.callback)
#Set pin as output
for pin_list in PIN_MAP_LIST:
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
def callback(self, msg):
# Get pin map for relevant feed
feed_pin_map = PIN_MAP_LIST[msg.feed]
# Convert selected camera to binary array
cam_select = [int(bit) for bit in bin(msg.camera)[2:]]
for indx, output_pin in enumerate(cam_select):
if output_pin:
GPIO.output(feed_pin_map[indx], GPIO.HIGH)
else
GPIO.output(feed_pin_map[indx], GPIO.LOW)
if __name__ == '__main__':
try:
camera_selection = CameraSelection()
rospy.spin()
except rospy.ROSInterruptException:
pass
| #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,PIN_MAP_FEED1,PIN_MAP_FEED2]
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('camera_feed_selection',CameraFeedSelection, self.callback)
#Set pin as output
for pin_list in PIN_MAP_LIST:
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
def callback(self, msg):
feed_pin_map = PIN_MAP_LIST[msg.feed]
for i, level in enumerate(msg.pin_values):
if level:
GPIO.output(feed_pin_map[i], GPIO.HIGH)
else
GPIO.output(feed_pin_map[i], GPIO.LOW)
if __name__ == '__main__':
try:
camera_selection = CameraSelection()
rospy.spin()
except rospy.ROSInterruptException:
pass
|
Make start_message_params optional in start_workflow() | from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@transaction.commit_on_success
def create(workflow_type, sender, raw_parameters):
workflow = get_workflow(workflow_type)
if workflow is None:
raise WorkflowNotLoadedError(workflow_type)
form = workflow.create_form_cls(raw_parameters)
if form.is_valid():
instance = workflow.instance_fabric(sender, form.cleaned_data)
# Ensure that we will create, not update
instance.id = None
# Set workflow type
setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type)
instance.save()
workflow.post_create_hook(sender, form.cleaned_data, instance)
return instance
else:
raise CreateValidationError(form.errors)
def start_workflow(obj, sender, start_message_params=None):
if start_message_params is None:
start_message_params = {}
workflow = get_workflow_by_instance(obj)
if isinstance(workflow.start_workflow, basestring):
return dispatch.dispatch(obj, sender, workflow.start_workflow)
elif callable(workflow.start_workflow):
start_message_id = workflow.start_workflow(obj, sender)
return dispatch.dispatch(obj, sender, start_message_id,
start_message_params)
else:
return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
| from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@transaction.commit_on_success
def create(workflow_type, sender, raw_parameters):
workflow = get_workflow(workflow_type)
if workflow is None:
raise WorkflowNotLoadedError(workflow_type)
form = workflow.create_form_cls(raw_parameters)
if form.is_valid():
instance = workflow.instance_fabric(sender, form.cleaned_data)
# Ensure that we will create, not update
instance.id = None
# Set workflow type
setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type)
instance.save()
workflow.post_create_hook(sender, form.cleaned_data, instance)
return instance
else:
raise CreateValidationError(form.errors)
def start_workflow(obj, sender, start_message_params):
workflow = get_workflow_by_instance(obj)
if isinstance(workflow.start_workflow, basestring):
return dispatch.dispatch(obj, sender, workflow.start_workflow)
elif callable(workflow.start_workflow):
start_message_id = workflow.start_workflow(obj, sender)
return dispatch.dispatch(obj, sender, start_message_id,
start_message_params)
else:
return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
|
Prepend simplejson import with 'module' name | import sublime
import sublime_plugin
import PrettyJSON.simplejson as json
from PrettyJSON.simplejson import OrderedDict
import decimal
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the selection
if region.empty() and s.get("use_entire_file_if_no_selection"):
selection = sublime.Region(0, self.view.size())
else:
selection = region
try:
obj = json.loads(self.view.substr(selection),
object_pairs_hook=OrderedDict,
parse_float=decimal.Decimal)
self.view.replace(edit, selection, json.dumps(obj,
indent=s.get("indent", 2),
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ': '),
use_decimal=True))
except Exception:
import sys
exc = sys.exc_info()[1]
sublime.status_message(str(exc))
| import sublime
import sublime_plugin
import simplejson as json
from simplejson import OrderedDict
import decimal
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the selection
if region.empty() and s.get("use_entire_file_if_no_selection"):
selection = sublime.Region(0, self.view.size())
else:
selection = region
try:
obj = json.loads(self.view.substr(selection),
object_pairs_hook=OrderedDict,
parse_float=decimal.Decimal)
self.view.replace(edit, selection, json.dumps(obj,
indent=s.get("indent", 2),
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ': '),
use_decimal=True))
except Exception:
import sys
exc = sys.exc_info()[1]
sublime.status_message(str(exc))
|
Add unit to the test directories | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS:
if filename.find(key) > -1:
return True
return False
def this_platform(filename):
if filename.find(platform) > -1:
return True
return False
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if platform_test(file):
if this_platform(file):
run_test(file_path)
else:
run_test(file_path)
| """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS:
if filename.find(key) > -1:
return True
return False
def this_platform(filename):
if filename.find(platform) > -1:
return True
return False
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if platform_test(file):
if this_platform(file):
run_test(file_path)
else:
run_test(file_path)
|
Add support for incuna_mail 3.0.0 | from setuptools import find_packages, setup
version = '6.0.0'
install_requires = (
'djangorestframework>=2.4.4,<3',
'incuna_mail>=2.0.0,<=3.0.0',
)
extras_require = {
'avatar': [
'django-imagekit>=3.2',
],
'utils': [
'raven>=5.1.1',
],
}
setup(
name='django-user-management',
packages=find_packages(),
include_package_data=True,
version=version,
description='User management model mixins and api views.',
long_description='',
keywords='django rest framework user management api',
author='Incuna',
author_email='[email protected]',
url='https://github.com/incuna/django-user-management/',
install_requires=install_requires,
extras_require=extras_require,
zip_safe=False,
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
'Topic :: Utilities',
],
)
| from setuptools import find_packages, setup
version = '6.0.0'
install_requires = (
'djangorestframework>=2.4.4,<3',
'incuna_mail>=2.0.0,<3',
)
extras_require = {
'avatar': [
'django-imagekit>=3.2',
],
'utils': [
'raven>=5.1.1',
],
}
setup(
name='django-user-management',
packages=find_packages(),
include_package_data=True,
version=version,
description='User management model mixins and api views.',
long_description='',
keywords='django rest framework user management api',
author='Incuna',
author_email='[email protected]',
url='https://github.com/incuna/django-user-management/',
install_requires=install_requires,
extras_require=extras_require,
zip_safe=False,
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
'Topic :: Utilities',
],
)
|
Revert "parando de lançar exceção"
This reverts commit 6153703a5c2a3d4dda559c2b8bc285760b4f9bf1. | package br.com.caelum.brutal.infra;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
/**
* Encodes a string
*
* @param str
* String to encode
* @return Encoded String
*/
public static String crypt(String str) {
if (str == null || str.length() == 0) {
throw new IllegalArgumentException("String to encript cannot be null or zero length");
}
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return hexString.toString();
}
} | package br.com.caelum.brutal.infra;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
/**
* Encodes a string
*
* @param str
* String to encode
* @return Encoded String
*/
public static String crypt(String str) {
if (str == null || str.length() == 0) return str;
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return hexString.toString();
}
} |
Fix $var name in hydrator | <?php
/*
* This file is part of vaibhavpandeyvpz/pimple-config package.
*
* (c) Vaibhav Pandey <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.md.
*/
namespace Pimple\Config;
use InvalidArgumentException;
use RuntimeException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class ConfigServiceProvider
* @package Pimple\Config
*/
class ConfigServiceProvider implements ServiceProviderInterface
{
/**
* @inheritdoc
*/
public function register(Container $pimple)
{
$pimple['config.files'] = function ($pimple) {
return [$pimple['config.file']];
};
$pimple['config.hydrate'] = $pimple->protect(function ($pimple) {
foreach ($pimple['config.files'] as $file) {
if (is_file($file) && is_readable($file)) {
/** @noinspection PhpIncludeInspection */
$values = require $file;
if (is_array($values)) {
foreach ($values as $key => $value) {
$pimple[$key] = $value;
}
} else {
throw new InvalidArgumentException("Configuration file must return an array");
}
} else {
throw new RuntimeException("Could not find or read from {$file}");
}
}
});
}
}
| <?php
/*
* This file is part of vaibhavpandeyvpz/pimple-config package.
*
* (c) Vaibhav Pandey <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.md.
*/
namespace Pimple\Config;
use InvalidArgumentException;
use RuntimeException;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class ConfigServiceProvider
* @package Pimple\Config
*/
class ConfigServiceProvider implements ServiceProviderInterface
{
/**
* @inheritdoc
*/
public function register(Container $pimple)
{
$pimple['config.files'] = function ($pimple) {
return [$pimple['config.file']];
};
$pimple['config.hydrate'] = $pimple->protect(function ($pimple) {
foreach ($pimple['config.files'] as $file) {
if (is_file($file) && is_readable($file)) {
/** @noinspection PhpIncludeInspection */
$values = require $file;
if (is_array($contents)) {
foreach ($values as $key => $value) {
$pimple[$key] = $value;
}
} else {
throw new InvalidArgumentException("Configuration file must return an array");
}
} else {
throw new RuntimeException("Could not find or read from {$file}");
}
}
});
}
}
|
Remove .json suffix from run names | import BenchmarkRun from 'models/BenchmarkRun.js';
import DoingWorkSpinner from 'components/DoingWorkSpinner.jsx';
//A non-ui class which cares about upload file, converting them to json and passing them on to the AppState
export default class FileUploader {
constructor(uploadBenchmarksFunction) {
this.uploadBenchmarksFunction = uploadBenchmarksFunction;
}
upload(files) {
if (files.length > 2) {
alert(`Maximum 2 files allowed to upload, but not ${files.length}!`)
return
}
DoingWorkSpinner.show();
const benchmarkRuns = [];
const uploadFunction = this.uploadBenchmarksFunction;
files.forEach((file, i) => {
const reader = new FileReader();
const runName = file.name.replace('.json', '');
reader.onload = function(evt) {
try {
var parsedBenchmarks = JSON.parse(evt.target.result);
const benchmarkRun = new BenchmarkRun({
name: runName,
benchmarks: parsedBenchmarks
});
benchmarkRuns.push(benchmarkRun);
if (i == files.length - 1) {
benchmarkRuns.sort((a, b) => a.name.localeCompare(b.name));
uploadFunction(benchmarkRuns);
}
} catch ( e ) {
alert(e); //error in the above string(in this case,yes)!
DoingWorkSpinner.hide();
}
};
reader.readAsText(file);
});
}
} | import BenchmarkRun from 'models/BenchmarkRun.js';
import DoingWorkSpinner from 'components/DoingWorkSpinner.jsx';
//A non-ui class which cares about upload file, converting them to json and passing them on to the AppState
export default class FileUploader {
constructor(uploadBenchmarksFunction) {
this.uploadBenchmarksFunction = uploadBenchmarksFunction;
}
upload(files) {
if (files.length > 2) {
alert(`Maximum 2 files allowed to upload, but not ${files.length}!`)
return
}
DoingWorkSpinner.show();
const benchmarkRuns = [];
const uploadFunction = this.uploadBenchmarksFunction;
files.forEach((file, i) => {
const reader = new FileReader();
reader.onload = function(evt) {
try {
var parsedBenchmarks = JSON.parse(evt.target.result);
const benchmarkRun = new BenchmarkRun({
name: file.name,
benchmarks: parsedBenchmarks
});
benchmarkRuns.push(benchmarkRun);
if (i == files.length - 1) {
benchmarkRuns.sort((a, b) => a.name.localeCompare(b.name));
uploadFunction(benchmarkRuns);
}
} catch ( e ) {
alert(e); //error in the above string(in this case,yes)!
DoingWorkSpinner.hide();
}
};
reader.readAsText(file);
});
}
} |
FIX toolbar not activating on topbar menu click | import React, { Component } from 'react';
import filtersIcon from '../icons/filtersIcon.svg';
import effectsIcon from '../icons/effectsIcon.svg';
import MenuItemIconAbove from './MenuItemIconAbove';
import Toolbar from './Toolbar';
class MainNavbar extends Component {
constructor(props) {
super(props);
this.state = {currentItem: "Effects"};
}
render() {
const menuItems = [
{
icon: effectsIcon,
alt: "effects",
label: "Effects",
disabled: false
},
{
icon: filtersIcon,
alt: "filters",
label: "Filters",
disabled: false
}
];
const menu = menuItems.map((item) => {
return <MenuItemIconAbove
className={item.disabled?"menu-item-disabled": "menu-item-active"}
icon={item.icon} alt={item.alt}
label={item.label} currentItem={this.state.currentItem}
key={item.label}
onClick={(e) => this.activateMenu(e, item)}/>
});
return (
<div>
<div className="middle navbar-container">
{menu}
</div>
<Toolbar canvas={this.props.canvas} active={this.state.currentItem}/>
</div>
);
}
activateMenu(e, item) {
if (!item.disabled) {
this.setState({currentItem: item.label});
}
}
}
export default MainNavbar;
| import React, { Component } from 'react';
import filtersIcon from '../icons/filtersIcon.svg';
import effectsIcon from '../icons/effectsIcon.svg';
import MenuItemIconAbove from './MenuItemIconAbove';
import Toolbar from './Toolbar';
class MainNavbar extends Component {
constructor(props) {
super(props);
this.state = {currentItem: "Effects"};
}
render() {
const menuItems = [
{
icon: effectsIcon,
alt: "effects",
label: "Effects",
disabled: false
},
{
icon: filtersIcon,
alt: "filters",
label: "Filters",
disabled: true
}
];
const menu = menuItems.map((item) => {
return <MenuItemIconAbove
className={item.disabled?"menu-item-disabled": "menu-item-active"}
icon={item.icon} alt={item.alt}
label={item.label} currentItem={this.state.currentItem}
key={item.label}
onClick={(e) => this.activateMenu.bind(this, e, item)}/>
});
return (
<div>
<div className="middle navbar-container">
{menu}
</div>
<Toolbar canvas={this.props.canvas} active={this.state.currentItem}/>
</div>
);
}
activateMenu(e, item) {
if (!item.disabled) {
this.setState({currentItem: item.label});
}
}
}
export default MainNavbar;
|
Fix chatroom url pattern to include '-' | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
| from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
Refactor TodosController to use Space.messaging.Controller | Space.messaging.Controller.extend('Todos.TodosController', {
dependencies: {
configuration: 'configuration'
},
eventSubscriptions() {
return [{
'Todos.TodoCreated': this._onTodoCreated,
'Todos.TodoReopened': this._onTodoReopened,
'Todos.TodoCompleted': this._onTodoCompleted,
'Todos.TodoRemoved': this._onTodoRemoved,
'Todos.TodoTitleChanged': this._onTodoTitleChanged
}];
},
_onTodoCreated(event) {
this.send(new Todos.CreateTodo({
targetId: this.configuration.todoListId,
title: event.title
}));
},
_onTodoReopened(event) {
this.send(new Todos.ReopenTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoCompleted(event) {
this.send(new Todos.CompleteTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoRemoved(event) {
this.send(new Todos.RemoveTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoTitleChanged(event) {
this.send(new Todos.ChangeTodoTitle({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId),
newTitle: event.newTitle
}));
}
});
| Space.Object.extend('Todos.TodosController', {
mixin: [
Space.messaging.EventSubscribing,
Space.messaging.CommandSending
],
dependencies: {
configuration: 'configuration'
},
eventSubscriptions() {
return [{
'Todos.TodoCreated': this._onTodoCreated,
'Todos.TodoReopened': this._onTodoReopened,
'Todos.TodoCompleted': this._onTodoCompleted,
'Todos.TodoRemoved': this._onTodoRemoved,
'Todos.TodoTitleChanged': this._onTodoTitleChanged
}];
},
_onTodoCreated(event) {
this.send(new Todos.CreateTodo({
targetId: this.configuration.todoListId,
title: event.title
}));
},
_onTodoReopened(event) {
this.send(new Todos.ReopenTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoCompleted(event) {
this.send(new Todos.CompleteTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoRemoved(event) {
this.send(new Todos.RemoveTodo({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId)
}));
},
_onTodoTitleChanged(event) {
this.send(new Todos.ChangeTodoTitle({
targetId: this.configuration.todoListId,
todoId: new Guid(event.todoId),
newTitle: event.newTitle
}));
}
});
|
Add test with usleep() function | <?php
namespace Isswp101\Timer\Test;
use Isswp101\Timer\Timer;
class TimerTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultTimerFormat()
{
$timer = new Timer;
$this->assertRegExp('/\d{2}:\d{2}:\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithoutHours()
{
$timer = new Timer('i:s.ms');
$this->assertRegExp('/\d{2}:\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithoutHoursAndMinutes()
{
$timer = new Timer('s.ms');
$this->assertRegExp('/\d{2}\.\d{3}/', $timer->end());
}
public function testEmptyTimerFormat()
{
$timer = new Timer('');
$this->assertEmpty($timer->end());
}
public function testCustomTimerFormat()
{
$timer = new Timer('H-i-s.ms');
$this->assertRegExp('/\d{2}-\d{2}-\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithMicroseconds()
{
$timer = new Timer('H:i:s.u');
$this->assertRegExp('/\d{2}:\d{2}:\d{2}\.\d{6}/', $timer->end());
}
public function testTimer()
{
$timer = new Timer('H:i:s');
usleep(1000000);
$this->assertEquals('00:00:01', $timer->end());
}
} | <?php
namespace Isswp101\Timer\Test;
use Isswp101\Timer\Timer;
class TimerTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultTimerFormat()
{
$timer = new Timer;
$this->assertRegExp('/\d{2}:\d{2}:\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithoutHours()
{
$timer = new Timer('i:s.ms');
$this->assertRegExp('/\d{2}:\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithoutHoursAndMinutes()
{
$timer = new Timer('s.ms');
$this->assertRegExp('/\d{2}\.\d{3}/', $timer->end());
}
public function testEmptyTimerFormat()
{
$timer = new Timer('');
$this->assertEmpty($timer->end());
}
public function testCustomTimerFormat()
{
$timer = new Timer('H-i-s.ms');
$this->assertRegExp('/\d{2}-\d{2}-\d{2}\.\d{3}/', $timer->end());
}
public function testTimerFormatWithMicroseconds()
{
$timer = new Timer('H:i:s.u');
$this->assertRegExp('/\d{2}:\d{2}:\d{2}\.\d{6}/', $timer->end());
}
} |
Clean up some code mess | import { expect, getRenderedComponent, sinon } from '../../spec_helper'
import { routeActions } from 'react-router-redux'
import { Discover as Component } from '../../../src/containers/discover/Discover'
function createPropsForComponent(props = {}) {
const defaultProps = {
dispatch: sinon.spy(),
isLoggedIn: false,
params: {},
pathname: '/',
}
return { ...defaultProps, ...props }
}
describe('DiscoverComponent', () => {
describe('#componentWillMount', () => {
it("doesn't redirect logged out users", () => {
const props = createPropsForComponent()
getRenderedComponent(Component, props)
expect(props.dispatch.callCount).to.equal(0)
})
expect(props.dispatch.callCount).to.equal(0)
})
it('redirects logged in users to /following by default', () => {
const props = createPropsForComponent({
isLoggedIn: true,
})
getRenderedComponent(Component, props)
const routeAction = routeActions.replace('/following')
const routeDispatch = props.dispatch.firstCall
expect(routeDispatch.args[0]).to.eql(routeAction)
})
it('otherwise redirects users to their last active stream', () => {
const props = createPropsForComponent({
isLoggedIn: true,
currentStream: '/discover/trending',
})
getRenderedComponent(Component, props)
const routeAction = routeActions.replace('/discover/trending')
const routeDispatch = props.dispatch.firstCall
expect(routeDispatch.args[0]).to.eql(routeAction)
})
})
})
| import { expect, getRenderedComponent, sinon } from '../../spec_helper'
import { routeActions } from 'react-router-redux'
// import * as MAPPING_TYPES from '../../../src/constants/mapping_types'
import Container, { Discover as Component } from '../../../src/containers/discover/Discover'
function createPropsForComponent(props = {}) {
const defaultProps = {
dispatch: sinon.spy(),
isLoggedIn: false,
params: {},
pathname: '/',
}
return { ...defaultProps, ...props }
}
describe('DiscoverComponent', () => {
describe('#componentWillMount', () => {
it("doesn't redirect logged out users", () => {
const props = createPropsForComponent()
const comp = getRenderedComponent(Component, props)
expect(props.dispatch.callCount).to.equal(0)
})
it('redirects logged in users to /following by default', () => {
const props = createPropsForComponent({
isLoggedIn: true,
})
getRenderedComponent(Component, props)
const routeAction = routeActions.replace('/following')
const routeDispatch = props.dispatch.firstCall
expect(routeDispatch.args[0]).to.eql(routeAction)
})
it('otherwise redirects users to their last active stream', () => {
const props = createPropsForComponent({
isLoggedIn: true,
currentStream: '/discover/trending',
})
getRenderedComponent(Component, props)
const routeAction = routeActions.replace('/discover/trending')
const routeDispatch = props.dispatch.firstCall
expect(routeDispatch.args[0]).to.eql(routeAction)
})
})
})
|
Fix service provider class reference | <?php namespace GeneaLabs\LaravelCasts\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use GeneaLabs\LaravelCasts\Providers\Service;
use File;
class Publish extends Command
{
protected $signature = 'casts:publish {--assets} {--config}';
protected $description = 'Publish various assets of the Laravel Casts package.';
public function handle()
{
if ($this->option('assets')) {
$this->delTree(public_path('genealabs-laravel-casts'));
$this->call('vendor:publish', [
'--provider' => Service::class,
'--tag' => ['assets'],
'--force' => true,
]);
}
if ($this->option('config')) {
$this->call('vendor:publish', [
'--provider' => Service::class,
'--tag' => ['config'],
'--force' => true,
]);
}
}
private function delTree($folder)
{
if (! is_dir($folder)) {
return false;
}
$files = array_diff(scandir($folder), ['.','..']);
foreach ($files as $file) {
is_dir("$folder/$file") ? $this->delTree("$folder/$file") : unlink("$folder/$file");
}
return rmdir($folder);
}
}
| <?php namespace GeneaLabs\LaravelCasts\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel;
use GeneaLabs\LaravelCasts\Providers\LaravelCastsService;
use File;
class Publish extends Command
{
protected $signature = 'casts:publish {--assets} {--config}';
protected $description = 'Publish various assets of the Laravel Casts package.';
public function handle()
{
if ($this->option('assets')) {
$this->delTree(public_path('genealabs-laravel-casts'));
$this->call('vendor:publish', [
'--provider' => LaravelCastsService::class,
'--tag' => ['assets'],
'--force' => true,
]);
}
if ($this->option('config')) {
$this->call('vendor:publish', [
'--provider' => LaravelCastsService::class,
'--tag' => ['config'],
'--force' => true,
]);
}
}
private function delTree($folder)
{
if (! is_dir($folder)) {
return false;
}
$files = array_diff(scandir($folder), ['.','..']);
foreach ($files as $file) {
is_dir("$folder/$file") ? $this->delTree("$folder/$file") : unlink("$folder/$file");
}
return rmdir($folder);
}
}
|
Remove route resolves from login/logout routes
Was previously using wrong route names. | export default function($stateProvider) {
this.$get = function() {
return {
getResolves: function(state){
var resolve = state.resolve || {},
routes = ["signIn", "signOut"];
if(_.indexOf(routes, state.name)>-1){
return;
}
else{
resolve.features = ['FeaturesService', function(FeaturesService) {
return FeaturesService.get();
}];
return resolve;
}
},
addState: function(state) {
var route = state.route || state.url,
resolve = this.getResolves(state);
$stateProvider.state(state.name, {
url: route,
controller: state.controller,
templateUrl: state.templateUrl,
resolve: resolve,
params: state.params,
data: state.data,
ncyBreadcrumb: state.ncyBreadcrumb,
onEnter: state.onEnter,
onExit: state.onExit,
template: state.template,
controllerAs: state.controllerAs,
views: state.views
});
}
};
};
}
| export default function($stateProvider) {
this.$get = function() {
return {
getResolves: function(state){
var resolve = state.resolve || {},
routes = ["login", "logout", "socket"];
if(_.indexOf(routes, state.name)>-1){
return;
}
else{
resolve.features = ['FeaturesService', function(FeaturesService) {
return FeaturesService.get();
}];
return resolve;
}
},
addState: function(state) {
var route = state.route || state.url,
resolve = this.getResolves(state);
$stateProvider.state(state.name, {
url: route,
controller: state.controller,
templateUrl: state.templateUrl,
resolve: resolve,
params: state.params,
data: state.data,
ncyBreadcrumb: state.ncyBreadcrumb,
onEnter: state.onEnter,
onExit: state.onExit,
template: state.template,
controllerAs: state.controllerAs,
views: state.views
});
}
};
};
}
|
Set BG to transparent instead of matching page background color | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
}(this, function (exports, echarts) {
var log = function (msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = ['#00ca5a','#919e8b', '#d7ab82', '#6e7074','#61a0a8','#efa18d', '#787464', '#cc7e63', '#724e58', '#4b565b'];
echarts.registerTheme('vintage', {
color: colorPalette,
backgroundColor: 'transparent',
graph: {
color: colorPalette,
},
textStyle: {color:"#777"},
title: {
textStyle:{color:"#777"}
},
});
})); | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
}(this, function (exports, echarts) {
var log = function (msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = ['#00ca5a','#919e8b', '#d7ab82', '#6e7074','#61a0a8','#efa18d', '#787464', '#cc7e63', '#724e58', '#4b565b'];
echarts.registerTheme('vintage', {
color: colorPalette,
backgroundColor: '#111717',
graph: {
color: colorPalette,
},
textStyle: {color:"#777"},
title: {
textStyle:{color:"#777"}
},
});
})); |
Use 'pass', not 'return', for empty Python methods | """
Test that Gabble times out the connection process after a while if the server
stops responding at various points. Real Gabbles time out after a minute; the
test suite's Gabble times out after a couple of seconds.
"""
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
pass
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
pass
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
pass
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
| """
Test that Gabble times out the connection process after a while if the server
stops responding at various points. Real Gabbles time out after a minute; the
test suite's Gabble times out after a couple of seconds.
"""
from servicetest import assertEquals
from gabbletest import exec_test, XmppAuthenticator
import constants as cs
import ns
class NoStreamHeader(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def streamStarted(self, root=None):
return
class NoAuthInfoResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def auth(self, auth):
return
class NoAuthResult(XmppAuthenticator):
def __init__(self):
XmppAuthenticator.__init__(self, 'test', 'pass')
def bindIq(self, iq):
return
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
e = q.expect('dbus-signal', signal='StatusChanged')
status, reason = e.args
assertEquals(cs.CONN_STATUS_DISCONNECTED, status)
assertEquals(cs.CSR_NETWORK_ERROR, reason)
if __name__ == '__main__':
exec_test(test, authenticator=NoStreamHeader())
exec_test(test, authenticator=NoAuthInfoResult())
exec_test(test, authenticator=NoAuthResult())
|
Fix an issue that on IE the QRCode cannot be displayed due to this.baseURI is undefined in IE | $(function() {
var links = $("#gamelist h1 a").map(function() {
var gameName = this.text;
var baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
this.href = baseUrl + "/" + gameName + ".html";
var qrCodeDiv = document.createElement("div");
qrCodeDiv.id = "qrcodediv_" + gameName;
this.parentNode.appendChild(qrCodeDiv);
new QRCode(qrCodeDiv,
{
text: this.href,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
return;
});
});
$(function() {
var links = $("#goodsufflist h1 a").map(function() {
var qrCodeDiv = document.createElement("div");
this.parentNode.appendChild(qrCodeDiv);
new QRCode(qrCodeDiv,
{
text: this.href,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
return;
});
}); | $(function() {
var links = $("#gamelist h1 a").map(function() {
var gameName = this.text;
var baseUrl = this.baseURI.substring(0, this.baseURI.lastIndexOf("/"));
this.href = baseUrl + "/" + gameName + ".html";
var qrCodeDiv = document.createElement("div");
qrCodeDiv.id = "qrcode_" + gameName;
this.appendChild(qrCodeDiv);
new QRCode(qrCodeDiv,
{
text: this.href,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
return;
});
});
$(function() {
var links = $("#goodsufflist h1 a").map(function() {
var qrCodeDiv = document.createElement("div");
this.appendChild(qrCodeDiv);
new QRCode(qrCodeDiv,
{
text: this.href,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
return;
});
}); |
Test modified according to refactorings | package org.jlib.core.collection;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ForwardingMap;
import org.junit.Test;
public class CachingMapTest {
@Test
public void performance() {
final Map<String, String> hashMap = new HashMap<>();
hashMap.put("ja", "nein");
hashMap.put("gut", "schlecht");
hashMap.put("München", "Berlin");
final Map<String, String> forwardingMap = new ForwardingMap<String, String>() {
@Override
protected Map<String, String> delegate() {
return hashMap;
}
};
final Map<String, String> cacheMap = new CachingMap<>(hashMap);
for (int i = 0; i < 20; i++) {
System.out.println("HashMap: " + measure(hashMap));
System.out.println("DelegatingMap: " + measure(forwardingMap));
System.out.println("CacheMap: " + measure(cacheMap));
}
}
private long measure(final Map<String, String> map) {
final int MAX = 100;
final String MUC = "ja";
long start = System.nanoTime();
for (int i = 0; i < MAX; i++)
if (map.containsKey(MUC))
map.get(MUC);
long end = System.nanoTime();
return end - start;
}
}
| package org.jlib.core.collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class CachingMapTest {
@Test
public void performance() {
final Map<String, String> hashMap = new HashMap<>();
hashMap.put("ja", "nein");
hashMap.put("gut", "schlecht");
hashMap.put("München", "Berlin");
final Map<String, String> delegatingMap = new DelegatingMap<String, String>(hashMap) {
// intentilonally empty
};
final Map<String, String> cacheMap = new CachingMap<>(hashMap);
for (int i = 0; i < 20; i++) {
System.out.println("HashMap: " + measure(hashMap));
System.out.println("DelegatingMap: " + measure(delegatingMap));
System.out.println("CacheMap: " + measure(cacheMap));
}
}
private long measure(final Map<String, String> map) {
final int MAX = 100;
final String MUC = "ja";
long start = System.nanoTime();
for (int i = 0; i < MAX; i++)
if (map.containsKey(MUC))
map.get(MUC);
long end = System.nanoTime();
return end - start;
}
}
|
Refactor create action into function | from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.")
parser.add_argument('--action', dest='action', required=True)
parser.add_argument('--user', dest='username', required=True)
parser.add_argument('--name', dest='collectionName', required=True)
parser.add_argument('--type', dest='collectionType', required=False)
return parser.parse_args()
def generateFileName(username, collectionName):
return CONST_COLLECTIONS_NAME + "/" + username + "_" + CONST_COLLECTIONS_NAME + "/" + username + "_" + collectionName + "_collection.dat"
def generateNewCollection(username, collectionType, collectionName):
return Collection(username, collectionType, collectionName, [])
def writeCollectionToFile(collectionFileName, arguments):
collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
collectionFile = open(collectionFileName, 'w')
collectionFile.write(collection.toJSON())
collectionFile.close()
def main():
arguments = generateArgumentsFromParser()
collectionFileName = generateFileName(arguments.username, arguments.collectionName)
if arguments.action.lower() == "create":
createCollectionFile(arguments.username, arguments.collectionName)
writeCollectionToFile(collectionFileName, arguments)
elif arguments.action.lower() == "update":
return None
if __name__ == '__main__':
main()
| from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.")
parser.add_argument('--action', dest='action', required=True)
parser.add_argument('--user', dest='username', required=True)
parser.add_argument('--name', dest='collectionName', required=True)
parser.add_argument('--type', dest='collectionType', required=False)
return parser.parse_args()
def generateFileName(username, collectionName):
return CONST_COLLECTIONS_NAME + "/" + username + "_" + CONST_COLLECTIONS_NAME + "/" + username + "_" + collectionName + "_collection.dat"
def generateNewCollection(username, collectionType, collectionName):
return Collection(username, collectionType, collectionName, [])
def main():
arguments = generateArgumentsFromParser()
collectionFileName = generateFileName(arguments.username, arguments.collectionName)
if arguments.action.lower() == "create":
createCollectionFile(arguments.username, arguments.collectionName)
collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
collectionFile = open(collectionFileName, 'w')
collectionFile.write(collection.toJSON())
collectionFile.close()
elif arguments.action.lower() == "update":
return None
if __name__ == '__main__':
main()
|
BAP-10985: Update the rules displaying autocomplete result for business unit owner field | <?php
namespace Oro\Bundle\OrganizationBundle\Form\Transformer;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;
class BusinessUnitTreeTransformer implements DataTransformerInterface
{
/** @var BusinessUnitManager */
protected $manager;
/** @var BusinessUnit */
protected $entity;
public function __construct($manager)
{
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (null == $value) {
return 0;
} elseif (is_array($value)) {
foreach($value as &$val) {
if ($val === "") {
$val = 0;
}
}
return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
}
return $this->manager->getBusinessUnitRepo()->find($value);
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if (null == $value) {
return 0;
}
if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
$result = [];
foreach ($value as $object) {
$result[] = $object->getId();
}
} elseif (is_object($value)) {
$result = $value->getId();
} else {
$result = $value;
}
return $result;
}
}
| <?php
namespace Oro\Bundle\OrganizationBundle\Form\Transformer;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;
class BusinessUnitTreeTransformer implements DataTransformerInterface
{
/** @var BusinessUnitManager */
protected $manager;
/** @var BusinessUnit */
protected $entity;
public function __construct($manager)
{
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (null == $value) {
return 0;
} elseif (is_array($value)) {
foreach($value as &$val) {
if ($val === "") {
$val =0;
}
}
return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
}
return $this->manager->getBusinessUnitRepo()->find($value);
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if (null == $value) {
return 0;
}
if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
$result = [];
foreach ($value as $object) {
$result[] = $object->getId();
}
} elseif (is_object($value)) {
$result = $value->getId();
} else {
$result = $value;
}
return $result;
}
}
|
Implement dialog injection of buttons | /**
* Created by bjanish on 3/6/15.
*/
RcmAdminService.rcmAdminPageNotFound = {
onEditChange: function(page){
var pageData = page.model.getData();
if(page.editMode) {
if (pageData.name != pageData.requestedPageData.rcmPageName) {
var actions = {
close: {
type: 'button',
label: 'Cancel',
css: 'btn btn-default',
method: function () {
window.location = "/";
}
},
save: {
label: 'Create new page',
css: 'btn btn-primary'
}
};
var dialog = RcmDialog.buildDialog(
'rcm-page-not-found-123',
"Page does not exist. Create a new one?", '/rcm-admin/page/new?url=' + pageData.requestedPageData.rcmPageName + '',
'RcmFormDialog',
actions
);
setTimeout(
function () {
dialog.open();
},
500
);
}
}
},
init: function(){
var page = RcmAdminService.getPage(
function (page) {
page.events.on(
'editingStateChange', RcmAdminService.rcmAdminPageNotFound.onEditChange
);
}
);
}
};
RcmAdminService.rcmAdminPageNotFound.init(); | /**
* Created by bjanish on 3/6/15.
*/
RcmAdminService.rcmAdminPageNotFound = {
onEditChange: function(page){
var pageData = page.model.getData();
if(page.editMode) {
if (pageData.name != pageData.requestedPageData.rcmPageName) {
var actions = {
close: function () {
window.location = "/";
}
};
var dialog = RcmDialog.buildDialog('rcm-page-not-found-123', "Page does not exist. Create a new one?", '/rcm-admin/page/new?url=' + pageData.requestedPageData.rcmPageName + '', 'RcmFormDialog', actions);
dialog.params.saveLabel = "Create new page";
dialog.params.closeLabel = "Cancel";
setTimeout(
function () {
dialog.open();
},
500
);
}
}
},
init: function(){
var page = RcmAdminService.getPage(
function (page) {
page.events.on(
'editingStateChange', RcmAdminService.rcmAdminPageNotFound.onEditChange
);
}
);
}
};
RcmAdminService.rcmAdminPageNotFound.init(); |
Fix bug where some files could get lost when uploading multiple files | import BenchmarkRun from 'models/BenchmarkRun.js';
import DoingWorkSpinner from 'components/DoingWorkSpinner.jsx';
//A non-ui class which cares about upload file, converting them to json and passing them on to the AppState
export default class FileUploader {
constructor(uploadBenchmarksFunction) {
this.uploadBenchmarksFunction = uploadBenchmarksFunction;
}
upload(files) {
DoingWorkSpinner.show();
const benchmarkRuns = [];
const uploadFunction = this.uploadBenchmarksFunction;
files.forEach((file) => {
const reader = new FileReader();
const runName = file.name.replace('.json', '');
reader.onload = function(evt) {
try {
var parsedBenchmarks = JSON.parse(evt.target.result);
const benchmarkRun = new BenchmarkRun({
name: runName,
benchmarks: parsedBenchmarks
});
benchmarkRuns.push(benchmarkRun);
if (benchmarkRuns.length == files.length) {
benchmarkRuns.sort((a, b) => a.name.localeCompare(b.name));
uploadFunction(benchmarkRuns);
}
} catch ( e ) {
alert(e); //error in the above string(in this case,yes)!
DoingWorkSpinner.hide();
}
};
reader.readAsText(file);
});
}
} | import BenchmarkRun from 'models/BenchmarkRun.js';
import DoingWorkSpinner from 'components/DoingWorkSpinner.jsx';
//A non-ui class which cares about upload file, converting them to json and passing them on to the AppState
export default class FileUploader {
constructor(uploadBenchmarksFunction) {
this.uploadBenchmarksFunction = uploadBenchmarksFunction;
}
upload(files) {
DoingWorkSpinner.show();
const benchmarkRuns = [];
const uploadFunction = this.uploadBenchmarksFunction;
files.forEach((file, i) => {
const reader = new FileReader();
const runName = file.name.replace('.json', '');
reader.onload = function(evt) {
try {
var parsedBenchmarks = JSON.parse(evt.target.result);
const benchmarkRun = new BenchmarkRun({
name: runName,
benchmarks: parsedBenchmarks
});
benchmarkRuns.push(benchmarkRun);
if (i == files.length - 1) {
benchmarkRuns.sort((a, b) => a.name.localeCompare(b.name));
uploadFunction(benchmarkRuns);
}
} catch ( e ) {
alert(e); //error in the above string(in this case,yes)!
DoingWorkSpinner.hide();
}
};
reader.readAsText(file);
});
}
} |
Introduce new "toAxisMessage()" to create a Axis message from a DOM
document. Use this new function instead of "toSOAPMessage()". This
resolves a problem in Java 6 which has a built-in xml.SOAPMessage
implementation. This implementation is in conflict with the previous
used Axis implementation. Previously the MessageFactory returned an
Axis message that implements a SOAPMessage interface. The test cases
(TestWS*) used this internal know-how and cast the SOAPMessage into an
Axis message directly. This fails in Java 6 and was bad programming style
anyhow. The TestWS* test cases will be modified to use the new function.
git-svn-id: 10bc45916fe30ae642aa5037c9a4b05727bba413@533031 13f79535-47bb-0310-9956-ffa450edef68 | package wssec;
import org.apache.xml.security.c14n.Canonicalizer;
import org.w3c.dom.Document;
import org.apache.axis.Message;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;
public class SOAPUtil {
/**
* Convert a DOM Document into a soap message.
* <p/>
*
* @param doc
* @return
* @throws Exception
*/
public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
Canonicalizer c14n =
Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
MessageFactory factory = MessageFactory.newInstance();
return factory.createMessage(null, in);
}
/**
* Convert a DOM Document into an Axis message.
* <p/>
*
* @param doc
* @return
* @throws Exception
*/
public static Message toAxisMessage(Document doc) throws Exception {
Canonicalizer c14n =
Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
return new Message(in);
}
/**
* Update soap message.
* <p/>
*
* @param doc
* @param message
* @return
* @throws Exception
*/
public static SOAPMessage updateSOAPMessage(Document doc,
SOAPMessage message)
throws Exception {
DOMSource domSource = new DOMSource(doc);
message.getSOAPPart().setContent(domSource);
return message;
}
}
| package wssec;
import org.apache.xml.security.c14n.Canonicalizer;
import org.w3c.dom.Document;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;
public class SOAPUtil {
/**
* Convert a DOM Document into a soap message.
* <p/>
*
* @param doc
* @return
* @throws Exception
*/
public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
Canonicalizer c14n =
Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
MessageFactory factory = MessageFactory.newInstance();
return factory.createMessage(null, in);
}
/**
* Update soap message.
* <p/>
*
* @param doc
* @param message
* @return
* @throws Exception
*/
public static SOAPMessage updateSOAPMessage(Document doc,
SOAPMessage message)
throws Exception {
DOMSource domSource = new DOMSource(doc);
message.getSOAPPart().setContent(domSource);
return message;
}
}
|
Make cluster extend Rectangle so that we get all of its lovely methods.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2337 542714f4-19e9-0310-aa3c-eee0fc999fb1 | //
// $Id: Cluster.java,v 1.6 2003/03/27 15:57:47 mdb Exp $
package com.threerings.whirled.spot.data;
import java.awt.Rectangle;
import com.samskivert.util.StringUtil;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.io.Streamable;
import com.threerings.presents.dobj.DSet;
/**
* Contains information on clusters.
*/
public class Cluster extends Rectangle
implements DSet.Entry, Streamable
{
/** A unique identifier for this cluster (also the distributed object
* id of the cluster chat object). */
public int clusterOid;
// documentation inherited
public Comparable getKey ()
{
if (_key == null) {
_key = new Integer(clusterOid);
}
return _key;
}
// documentation inherited
public boolean equals (Object other)
{
if (other instanceof Cluster) {
return ((Cluster)other).clusterOid == clusterOid;
} else {
return false;
}
}
// documentation inherited
public int hashCode ()
{
return clusterOid;
}
/**
* Generates a string representation of this instance.
*/
public String toString ()
{
return StringUtil.fieldsToString(this);
}
/** Used for {@link #geyKey}. */
protected transient Integer _key;
}
| //
// $Id: Cluster.java,v 1.5 2003/03/26 23:42:41 mdb Exp $
package com.threerings.whirled.spot.data;
import java.awt.Rectangle;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet;
/**
* Contains information on clusters.
*/
public class Cluster extends SimpleStreamableObject
implements DSet.Entry
{
/** A unique identifier for this cluster (also the distributed object
* id of the cluster chat object). */
public int clusterOid;
/** The bounds of the cluster in the scene. */
public int x, y, width, height;
/**
* Returns the "footprint" of this cluster in tile coordinates.
*/
public Rectangle getFootprint ()
{
return new Rectangle(x, y, width, height);
}
// documentation inherited
public Comparable getKey ()
{
if (_key == null) {
_key = new Integer(clusterOid);
}
return _key;
}
// documentation inherited
public boolean equals (Object other)
{
if (other instanceof Cluster) {
return ((Cluster)other).clusterOid == clusterOid;
} else {
return false;
}
}
// documentation inherited
public int hashCode ()
{
return clusterOid;
}
/** Used for {@link #geyKey}. */
protected transient Integer _key;
}
|
Add comments on use of 'initializer' key. | <?php
/**
* ZnZend
*
* @author Zion Ng <[email protected]>
* @link [Source] http://github.com/zionsg/ZnZend
*/
namespace ZnZend;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig($env = null)
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
// Any object pulled from a service manager is ran through the registered initializers
'initializers' => array(
function ($instance, $sm) {
// Sets default db adapter
// Instance needs to implement the interface and be pulled from a service manager for this to work
// Example in controller action:
// $userTable = $this->getServiceLocator()->get('Application\Model\UserTable');
if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
$instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
}
}
),
);
}
}
| <?php
/**
* ZnZend
*
* @author Zion Ng <[email protected]>
* @link [Source] http://github.com/zionsg/ZnZend
*/
namespace ZnZend;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig($env = null)
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'initializers' => array(
function ($instance, $sm) {
// Sets default db adapter
if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
$instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
}
}
),
);
}
}
|
Rewrite httputil test module via pytest | """Tests for ``cherrypy.lib.httputil``."""
import pytest
from cherrypy.lib import httputil
class TestUtility(object):
@pytest.mark.parametrize(
'script_name,path_info,expected_url',
[
('/sn/', '/pi/', '/sn/pi/'),
('/sn/', '/pi', '/sn/pi'),
('/sn/', '/', '/sn/'),
('/sn/', '', '/sn/'),
('/sn', '/pi/', '/sn/pi/'),
('/sn', '/pi', '/sn/pi'),
('/sn', '/', '/sn/'),
('/sn', '', '/sn'),
('/', '/pi/', '/pi/'),
('/', '/pi', '/pi'),
('/', '/', '/'),
('/', '', '/'),
('', '/pi/', '/pi/'),
('', '/pi', '/pi'),
('', '/', '/'),
('', '', '/'),
]
)
def test_urljoin(self, script_name, path_info, expected_url):
"""Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
actual_url = httputil.urljoin(script_name, path_info)
assert actual_url == expected_url
| """Tests for cherrypy/lib/httputil.py."""
import unittest
from cherrypy.lib import httputil
class UtilityTests(unittest.TestCase):
def test_urljoin(self):
# Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')
self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn', ''), '/sn')
self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('/', '/'), '/')
self.assertEqual(httputil.urljoin('/', ''), '/')
self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('', '/'), '/')
self.assertEqual(httputil.urljoin('', ''), '/')
if __name__ == '__main__':
unittest.main()
|
Fix depreciation notices with Symfony >= 4.2 | <?php
/*
* This file is part of the SensioLabsConnectBundle package.
*
* (c) SensioLabs <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SensioLabs\Bundle\ConnectBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration.
*
* @author Marc Weistroff <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
if (method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('sensiolabs_connect');
$rootNode = $treeBuilder->getRootNode();
} else {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sensiolabs_connect');
}
$rootNode
->children()
->scalarNode('app_id')->isRequired()->end()
->scalarNode('app_secret')->isRequired()->end()
->scalarNode('scope')->isRequired()->end()
->scalarNode('oauth_callback_path')->defaultValue('/session/callback')->end()
->scalarNode('oauth_endpoint')->defaultValue('https://connect.sensiolabs.com')->end()
->scalarNode('api_endpoint')->defaultValue('https://connect.sensiolabs.com/api')->end()
->scalarNode('timeout')->defaultValue(5)->end()
->booleanNode('strict_checks')->defaultValue(true)->end()
->end()
;
return $treeBuilder;
}
}
| <?php
/*
* This file is part of the SensioLabsConnectBundle package.
*
* (c) SensioLabs <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SensioLabs\Bundle\ConnectBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration.
*
* @author Marc Weistroff <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sensiolabs_connect');
$rootNode
->children()
->scalarNode('app_id')->isRequired()->end()
->scalarNode('app_secret')->isRequired()->end()
->scalarNode('scope')->isRequired()->end()
->scalarNode('oauth_callback_path')->defaultValue('/session/callback')->end()
->scalarNode('oauth_endpoint')->defaultValue('https://connect.sensiolabs.com')->end()
->scalarNode('api_endpoint')->defaultValue('https://connect.sensiolabs.com/api')->end()
->scalarNode('timeout')->defaultValue(5)->end()
->booleanNode('strict_checks')->defaultValue(true)->end()
->end()
;
return $treeBuilder;
}
}
|
Update text index to include url | var client = require('mongodb').MongoClient
var instance = false
module.exports = {
connect: function(config, callback) {
client.connect(config.database.host+config.database.name, function(err, db){
//Make db instance available to the rest of the module
instance = db
//Set up db index on pages collection
instance.collection('pages').ensureIndex({
"url": "text",
"title": "text",
"post.city": "text",
"post.content": "text",
"post.food": "text",
"post.product_type": "text"
}, {
"weights": {
"title": 20,
"url": 18,
"post.city": 15,
"post.food": 10,
"post.product_type": 5,
"post.content": 3
},
"default_language": "swedish"
})
callback(db)
})
},
instance: function() {
return instance
},
disconnect: function() {
instance.close()
}
} | var client = require('mongodb').MongoClient
var instance = false
module.exports = {
connect: function(config, callback) {
client.connect(config.database.host+config.database.name, function(err, db){
//Make db instance available to the rest of the module
instance = db
//Set up db index on pages collection
instance.collection('pages').ensureIndex({
"title": "text",
"post.city": "text",
"post.content": "text",
"post.food": "text",
"post.product_type": "text"
}, {
"weights": {
"title": 20,
"post.city": 15,
"post.food": 10,
"post.product_type": 5,
"post.content": 3
},
"default_language": "swedish"
})
callback(db)
})
},
instance: function() {
return instance
},
disconnect: function() {
instance.close()
}
} |
Add extra tests to query string query model | from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
| from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
|
Increase package version to 0.4 and update meta | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
version = "0.4"
setup(
name="dj-cmd",
version=version,
description="`dj cmd` is a Django shortcut command.",
license="BSD",
author="Filip Wasilewski",
author_email="[email protected]",
url="https://github.com/nigma/dj-cmd",
download_url="https://github.com/nigma/dj-cmd/zipball/master",
long_description=open("README.rst").read(),
packages=["dj_cmd"],
package_dir={"dj_cmd": "src"},
include_package_data=True,
classifiers=(
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules"
),
tests_require=["django>=1.3"],
entry_points={
"console_scripts": [
"dj = dj_cmd.dj:main",
]
},
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
version = "0.3"
setup(
name="dj-cmd",
version=version,
description="`dj cmd` is a Django shortcut command.",
license="BSD",
author="Filip Wasilewski",
author_email="[email protected]",
url="https://github.com/nigma/dj-cmd",
download_url="https://github.com/nigma/dj-cmd/zipball/master",
long_description=open("README.rst").read(),
packages=["dj_cmd"],
package_dir={"dj_cmd": "src"},
include_package_data=True,
classifiers=(
"Development Status :: 4 - Beta",
"Environment :: Console",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules"
),
tests_require=["django>=1.3"],
entry_points={
"console_scripts": [
"dj = dj_cmd.dj:main",
]
},
)
|
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`) | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
| # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
Clean up job stats when jobs are removed in build restart | from sqlalchemy.orm import joinedload
from datetime import datetime
from changes.api.base import APIView
from changes.api.build_index import execute_build
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, ItemStat
class BuildRestartAPIView(APIView):
def post(self, build_id):
build = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
joinedload('source'),
).get(build_id)
if build is None:
return '', 404
if build.status != Status.finished:
return '', 400
# ItemStat doesnt cascade
ItemStat.query.filter(
ItemStat.item_id == build.id
).delete()
ItemStat.query.filter(
ItemStat.item_id.in_(Job.query.filter(
Job.build_id == build.id,
)),
).delete()
# remove any existing job data
# TODO(dcramer): this is potentially fairly slow with cascades
Job.query.filter(
Job.build_id == build.id
).delete()
build.date_started = datetime.utcnow()
build.date_modified = build.date_started
build.date_finished = None
build.duration = None
build.status = Status.queued
build.result = Result.unknown
db.session.add(build)
execute_build(build=build)
return self.respond(build)
| from sqlalchemy.orm import joinedload
from datetime import datetime
from changes.api.base import APIView
from changes.api.build_index import execute_build
from changes.config import db
from changes.constants import Result, Status
from changes.models import Build, Job, ItemStat
class BuildRestartAPIView(APIView):
def post(self, build_id):
build = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
joinedload('source'),
).get(build_id)
if build is None:
return '', 404
if build.status != Status.finished:
return '', 400
# remove any existing job data
# TODO(dcramer): this is potentially fairly slow with cascades
Job.query.filter(
Job.build == build
).delete()
ItemStat.query.filter(
ItemStat.item_id == build.id
).delete()
build.date_started = datetime.utcnow()
build.date_modified = build.date_started
build.date_finished = None
build.duration = None
build.status = Status.queued
build.result = Result.unknown
db.session.add(build)
execute_build(build=build)
return self.respond(build)
|
Update charset of email config | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Emailing
{
private $ci;
private $config;
public function __construct()
{
$this->ci =& get_instance();
// initialize email configuration
$this->config = array(
'protocol' => 'smtp',
'smtp_host' => $_SERVER['SMTP_HOST'],
'smtp_user' => $_SERVER['SMTP_USER'],
'smtp_pass' => $_SERVER['SMTP_PASS'],
'mailtype' => 'html',
'smtp_port' => $_SERVER['SMTP_PORT'],
'charset' => 'iso-8859-1'
);
$this->ci->load->library('email', $this->config);
}
public function send_email($emailTo, $subject, $msg)
{
$this->ci->email->from($_SERVER['EMAIL_FROM'], $_SERVER['EMAIL_ALIAS']);
$this->ci->email->to($emailTo);
$this->ci->email->subject($subject);
$this->ci->email->message($msg);
$this->ci->email->send();
// TODO: create log table to log all outgoing email
}
}
/* End of file Emailing.php */
/* Location: ./application/libraries/Emailing.php */
| <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Emailing
{
private $ci;
private $config;
public function __construct()
{
$this->ci =& get_instance();
// initialize email configuration
$this->config = array(
'protocol' => 'smtp',
'smtp_host' => $_SERVER['SMTP_HOST'],
'smtp_user' => $_SERVER['SMTP_USER'],
'smtp_pass' => $_SERVER['SMTP_PASS'],
'mailtype' => 'html',
'smtp_port' => $_SERVER['SMTP_PORT'],
);
$this->ci->load->library('email', $this->config);
}
public function send_email($emailTo, $subject, $msg)
{
$this->ci->email->from($_SERVER['EMAIL_FROM'], $_SERVER['EMAIL_ALIAS']);
$this->ci->email->to($emailTo);
$this->ci->email->subject($subject);
$this->ci->email->message($msg);
$this->ci->email->send();
// TODO: create log table to log all outgoing email
}
}
/* End of file Emailing.php */
/* Location: ./application/libraries/Emailing.php */
|
Add location path to console | myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
$scope.inventories = inventoryService.loadInventories();
$scope.inventory = inventoryService.getInventory($routeParams.id);
$scope.headerIcon = $scope.inventory ? "arrow_back" : "";
console.log("Path: " + $location.path());
$scope.goBack = function() {
$window.history.go(-1);
};
$scope.newInventory = function() {
var inventory = inventoryService.newInventory();
$location.path(`/new/${inventory.id}`);
};
$scope.editInventory = function(inv) {
$location.path(`/edit/${inv.id}`);
};
$scope.addInventory = function() {
var id = $routeParams.id;
$scope.inventories[id] = $scope.inventory;
inventoryService.storeInventories();
$location.path(`/view/${id}`);
};
$scope.newItem = function() {
var id = $scope.inventory.id;
var item = inventoryService.newItem();
$location.path(`/edit/${id}/item/new/${item.id}`);
};
$scope.addItem = function() {
var { id, itemId } = $routeParams;
var inventory = $scope.inventories[id];
inventory.items[itemId] = $scope.item;
inventoryService.storeInventories();
$location.path(`/view/${id}`);
};
$scope.removeItem = function() {
};
});
| myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
$scope.inventories = inventoryService.loadInventories();
$scope.inventory = inventoryService.getInventory($routeParams.id);
$scope.headerIcon = $scope.inventory ? "arrow_back" : "";
$scope.goBack = function() {
$window.history.go(-1);
};
$scope.newInventory = function() {
var inventory = inventoryService.newInventory();
$location.path(`/new/${inventory.id}`);
};
$scope.editInventory = function(inv) {
$location.path(`/edit/${inv.id}`);
};
$scope.addInventory = function() {
var id = $routeParams.id;
$scope.inventories[id] = $scope.inventory;
inventoryService.storeInventories();
$location.path(`/view/${id}`);
};
$scope.newItem = function() {
var id = $scope.inventory.id;
var item = inventoryService.newItem();
$location.path(`/edit/${id}/item/new/${item.id}`);
};
$scope.addItem = function() {
var { id, itemId } = $routeParams;
var inventory = $scope.inventories[id];
inventory.items[itemId] = $scope.item;
inventoryService.storeInventories();
$location.path(`/view/${id}`);
};
$scope.removeItem = function() {
};
});
|
Rewrite test with utility methods | var expect = require('expect.js')
var utils = require('./utils')
describe("User registration", () => {
var user = { username: "KtorZ", password: "password" }
beforeEach(done => {
utils.mongo(db => {
return db.collection('users')
.deleteOne({ username: user.username })
.then(() => done())
.catch(done)
})
})
context("Given a non-existing user", () => {
it("Should be able to register", done => {
utils.request({
path: '/users',
method: 'POST'
}, user)
.then(res => {
expect(res.code).to.equal(201)
expect(res.result.id).to.be.ok()
expect(res.result.token).to.be.ok()
expect(res.result.username).to.equal(user.username)
expect(res.result.createdAt).to.be.below(Date.now())
expect(Object.keys(res.result).length).to.equal(4)
done()
})
.catch(done)
})
})
})
| var expect = require('expect.js')
var mongo = require('mongodb')
var http = require('http')
describe("User registration", function () {
var user = { username: "KtorZ", password: "password" }
beforeEach(function (done) {
mongo.MongoClient
.connect("mongodb://localhost:27017/hexode")
.then(function (db) {
db.collection('users')
.deleteOne({ username: user.username })
.then(function () {
db.close()
done()
})
.catch(function (e) {
db.close()
throw e
})
})
.catch(function (e) {
throw e
})
})
context("Given a non-existing user", function () {
it("Should be able to register", function (done) {
var req = http.request({
hostname: 'localhost',
port: 8080,
path: '/users',
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json'
}
}, function (res) {
expect(res.statusCode).to.equal(201)
var buf = ""
res.setEncoding('utf8')
res.on('data', function (b) { buf += b })
res.on('end', function () {
var result = JSON.parse(buf)
expect(result.id).to.be.ok()
expect(result.token).to.be.ok()
expect(result.username).to.equal(user.username)
expect(result.createdAt).to.be.below(Date.now())
expect(Object.keys(result).length).to.equal(4)
done()
})
})
req.write(JSON.stringify(user))
req.end()
})
})
})
|
Add display for running states | import os
import time
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
start_time = time.time()
for filename in os.listdir(base_directory + "/Annotation"):
# print the percentage.
stage_counter += 1
print(stage_counter, "/", total_stage, end=" ", sep=" ")
print("(", int(stage_counter / total_stage * 100), "%)", sep="")
# check the given file is a valid txt file.
if not filename.endswith(".txt"):
continue
# get filename without .txt extension
base_filename = truncate_extension(filename, 3)
# read data from the file
image_size = read_image_size(base_directory + "/Image/" + concatenate_extension(base_filename, "jpg"))
annotation_data = read_annotation_data(base_directory + "/Annotation/"
+ concatenate_extension(base_filename, "txt"), image_size)
# write the xml file
write_xml_tag(base_directory + "/XML/" + concatenate_extension(base_filename, "xml"),
concatenate_extension(base_filename, "jpg"), image_size, annotation_data)
end_time = time.time()
print()
print("%d annotations converted into xml. Total running time: %lf secs." % (total_stage, end_time - start_time))
# main function
if __name__ == "__main__":
main() | import os
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
for filename in os.listdir(base_directory + "/Annotation"):
# print the percentage.
stage_counter += 1
print(stage_counter, "/", total_stage, end=" ", sep=" ")
print("(", int(stage_counter / total_stage * 100), "%)", sep="")
# check the given file is a valid txt file.
if not filename.endswith(".txt"):
continue
# get filename without .txt extension
base_filename = truncate_extension(filename, 3)
# read data from the file
image_size = read_image_size(base_directory + "/Image/" + concatenate_extension(base_filename, "jpg"))
annotation_data = read_annotation_data(base_directory + "/Annotation/"
+ concatenate_extension(base_filename, "txt"), image_size)
# write the xml file
write_xml_tag(base_directory + "/XML/" + concatenate_extension(base_filename, "xml"),
concatenate_extension(base_filename, "jpg"), image_size, annotation_data)
if __name__ == "__main__":
main() |
Include url attribute in created Collection | define(['streamhub-sdk/collection'], function (Collection) {
'use strict';
var HotCollectionToCollection = function () {};
/**
* Transform an Object from StreamHub's Hot Collection endpoint into a
* streamhub-sdk/collection model
* @param hotCollection {object}
*/
HotCollectionToCollection.transform = function (hotCollection) {
var collection = new Collection({
network: networkFromHotCollection(hotCollection),
siteId: hotCollection.siteId,
articleId: hotCollection.articleId,
id: hotCollection.id,
environment: environmentFromHotCollection(hotCollection)
});
collection.heatIndex = hotCollection.heat;
collection.title = hotCollection.title;
collection.url = hotCollection.url;
return collection;
};
var NETWORK_IN_INITURL = /([^.\/]+\.fyre\.co|livefyre\.com)\/\d+\//;
function networkFromHotCollection(hotCollection) {
var initUrl = hotCollection.initUrl;
var match = initUrl.match(NETWORK_IN_INITURL);
if ( ! match) {
return;
}
return match[1];
}
var ENVIRONMENT_IN_INITURL = /\/bs3\/([^\/]+)\/[^\/]+\/\d+\//;
function environmentFromHotCollection(hotCollection) {
var initUrl = hotCollection.initUrl;
var match = initUrl.match(ENVIRONMENT_IN_INITURL);
if ( ! match) {
return;
}
return match[1];
}
return HotCollectionToCollection;
});
| define(['streamhub-sdk/collection'], function (Collection) {
'use strict';
var HotCollectionToCollection = function () {};
/**
* Transform an Object from StreamHub's Hot Collection endpoint into a
* streamhub-sdk/collection model
* @param hotCollection {object}
*/
HotCollectionToCollection.transform = function (hotCollection) {
var collection = new Collection({
network: networkFromHotCollection(hotCollection),
siteId: hotCollection.siteId,
articleId: hotCollection.articleId,
id: hotCollection.id,
environment: environmentFromHotCollection(hotCollection)
});
collection.heatIndex = hotCollection.heat;
collection.title = hotCollection.title;
return collection;
};
var NETWORK_IN_INITURL = /([^.\/]+\.fyre\.co|livefyre\.com)\/\d+\//;
function networkFromHotCollection(hotCollection) {
var initUrl = hotCollection.initUrl;
var match = initUrl.match(NETWORK_IN_INITURL);
if ( ! match) {
return;
}
return match[1];
}
var ENVIRONMENT_IN_INITURL = /\/bs3\/([^\/]+)\/[^\/]+\/\d+\//;
function environmentFromHotCollection(hotCollection) {
var initUrl = hotCollection.initUrl;
var match = initUrl.match(ENVIRONMENT_IN_INITURL);
if ( ! match) {
return;
}
return match[1];
}
return HotCollectionToCollection;
}); |
Fix DropPrivileges component to be compatible with python3 | from pwd import getpwnam
from grp import getgrnam
from traceback import format_exc
from os import getuid, setgroups, setgid, setuid, umask
from circuits.core import handler, BaseComponent
class DropPrivileges(BaseComponent):
def init(self, user="nobody", group="nobody", **kwargs):
self.user = user
self.group = group
def drop_privileges(self):
if getuid() > 0:
# Running as non-root. Ignore.
return
try:
# Get the uid/gid from the name
uid = getpwnam(self.user).pw_uid
gid = getgrnam(self.group).gr_gid
except KeyError as error:
print("ERROR: Could not drop privileges {0:s}".format(error))
print(format_exc())
raise SystemExit(-1)
try:
# Remove group privileges
setgroups([])
# Try setting the new uid/gid
setgid(gid)
setuid(uid)
# Ensure a very conservative umask
umask(0o077)
except Exception as error:
print("ERROR: Could not drop privileges {0:s}".format(error))
print(format_exc())
raise SystemExit(-1)
@handler("ready", channel="*")
def on_ready(self, server, bind):
try:
self.drop_privileges()
finally:
self.unregister()
| from pwd import getpwnam
from grp import getgrnam
from traceback import format_exc
from os import getuid, setgroups, setgid, setuid, umask
from circuits.core import handler, BaseComponent
class DropPrivileges(BaseComponent):
def init(self, user="nobody", group="nobody", **kwargs):
self.user = user
self.group = group
def drop_privileges(self):
if getuid() > 0:
# Running as non-root. Ignore.
return
try:
# Get the uid/gid from the name
uid = getpwnam(self.user).pw_uid
gid = getgrnam(self.group).gr_gid
except KeyError as error:
print("ERROR: Could not drop privileges {0:s}".format(error))
print(format_exc())
raise SystemExit(-1)
try:
# Remove group privileges
setgroups([])
# Try setting the new uid/gid
setgid(gid)
setuid(uid)
# Ensure a very conservative umask
umask(077)
except Exception as error:
print("ERROR: Could not drop privileges {0:s}".format(error))
print(format_exc())
raise SystemExit(-1)
@handler("ready", channel="*")
def on_ready(self, server, bind):
try:
self.drop_privileges()
finally:
self.unregister()
|
Update StringBuilder formatting to use "by" for dateTime and double quotes for description | package seedu.address.testutil;
import seedu.emeraldo.model.tag.UniqueTagList;
import seedu.emeraldo.model.task.*;
/**
* A mutable person object. For testing only.
*/
public class TestPerson implements ReadOnlyTask {
private Description name;
private DateTime dateTime;
private Phone phone;
private UniqueTagList tags;
public TestPerson() {
tags = new UniqueTagList();
}
public void setName(Description name) {
this.name = name;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
public Description getDescription() {
return name;
}
@Override
public DateTime getDateTime() {
return dateTime;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add \"" + this.getDescription().fullName + "\" ");
sb.append("by " + this.getDateTime().value + " ");
this.getTags().getInternalList().stream().forEach(s -> sb.append("#" + s.tagName + " "));
return sb.toString();
}
}
| package seedu.address.testutil;
import seedu.emeraldo.model.tag.UniqueTagList;
import seedu.emeraldo.model.task.*;
/**
* A mutable person object. For testing only.
*/
public class TestPerson implements ReadOnlyTask {
private Description name;
private DateTime dateTime;
private Phone phone;
private UniqueTagList tags;
public TestPerson() {
tags = new UniqueTagList();
}
public void setName(Description name) {
this.name = name;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
public Description getDescription() {
return name;
}
@Override
public DateTime getDateTime() {
return dateTime;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add " + this.getDescription().fullName + " ");
sb.append("a/" + this.getDateTime().value + " ");
this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
return sb.toString();
}
}
|
Return False early if mailgun API key isn't set locally | # -*- coding: utf-8 -*-
import hmac
import hashlib
from rest_framework import permissions
from rest_framework import exceptions
from framework import sentry
from website import settings
class RequestComesFromMailgun(permissions.BasePermission):
"""Verify that request comes from Mailgun.
Adapted here from conferences/message.py
Signature comparisons as recomended from mailgun docs:
https://documentation.mailgun.com/en/latest/user_manual.html#webhooks
"""
def has_permission(self, request, view):
if request.method != 'POST':
raise exceptions.MethodNotAllowed(method=request.method)
data = request.data
if not data:
raise exceptions.ParseError('Request body is empty')
if not settings.MAILGUN_API_KEY:
return False
signature = hmac.new(
key=settings.MAILGUN_API_KEY,
msg='{}{}'.format(
data['timestamp'],
data['token'],
),
digestmod=hashlib.sha256,
).hexdigest()
if 'signature' not in data:
error_message = 'Signature required in request body'
sentry.log_message(error_message)
raise exceptions.ParseError(error_message)
if not hmac.compare_digest(unicode(signature), unicode(data['signature'])):
raise exceptions.ParseError('Invalid signature')
return True
| # -*- coding: utf-8 -*-
import hmac
import hashlib
from rest_framework import permissions
from rest_framework import exceptions
from framework import sentry
from website import settings
class RequestComesFromMailgun(permissions.BasePermission):
"""Verify that request comes from Mailgun.
Adapted here from conferences/message.py
Signature comparisons as recomended from mailgun docs:
https://documentation.mailgun.com/en/latest/user_manual.html#webhooks
"""
def has_permission(self, request, view):
if request.method != 'POST':
raise exceptions.MethodNotAllowed(method=request.method)
data = request.data
if not data:
raise exceptions.ParseError('Request body is empty')
signature = hmac.new(
key=settings.MAILGUN_API_KEY,
msg='{}{}'.format(
data['timestamp'],
data['token'],
),
digestmod=hashlib.sha256,
).hexdigest()
if 'signature' not in data:
error_message = 'Signature required in request body'
sentry.log_message(error_message)
raise exceptions.ParseError(error_message)
if not hmac.compare_digest(unicode(signature), unicode(data['signature'])):
raise exceptions.ParseError('Invalid signature')
return True
|
DatabaseBackend: Make it possible to override the models used to store task/taskset state | from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
TaskModel = TaskMeta
TaskSetModel = TaskSetMeta
def _store_result(self, task_id, result, status, traceback=None):
"""Store return value and status of an executed task."""
self.TaskModel._default_manager.store_result(task_id, result, status,
traceback=traceback)
return result
def _save_taskset(self, taskset_id, result):
"""Store the result of an executed taskset."""
self.TaskModel._default_manager.store_result(taskset_id, result)
return result
def _get_task_meta_for(self, task_id):
"""Get task metadata for a task by id."""
meta = self.TaskModel._default_manager.get_task(task_id)
if meta:
return meta.to_dict()
def _restore_taskset(self, taskset_id):
"""Get taskset metadata for a taskset by id."""
meta = self.TaskSetModel._default_manager.restore_taskset(taskset_id)
if meta:
return meta.to_dict()
def cleanup(self):
"""Delete expired metadata."""
for model in self.TaskModel, self.TaskSetModel:
model._default_manager.delete_expired()
| from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
def _store_result(self, task_id, result, status, traceback=None):
"""Store return value and status of an executed task."""
TaskMeta.objects.store_result(task_id, result, status,
traceback=traceback)
return result
def _save_taskset(self, taskset_id, result):
"""Store the result of an executed taskset."""
TaskSetMeta.objects.store_result(taskset_id, result)
return result
def _get_task_meta_for(self, task_id):
"""Get task metadata for a task by id."""
meta = TaskMeta.objects.get_task(task_id)
if meta:
return meta.to_dict()
def _restore_taskset(self, taskset_id):
"""Get taskset metadata for a taskset by id."""
meta = TaskSetMeta.objects.restore_taskset(taskset_id)
if meta:
return meta.to_dict()
def cleanup(self):
"""Delete expired metadata."""
TaskMeta.objects.delete_expired()
TaskSetMeta.objects.delete_expired()
|
Make the template and static folders be inside bitHopper | import logging, json
import bitHopper.Tracking
import bitHopper.util
import bitHopper.Network
import flask
app = flask.Flask(__name__, template_folder='bitHopper/templates',
static_folder = 'bitHopper/static')
app.Debug = False
@app.teardown_request
def teardown_request_wrap(exception):
"""
Prints tracebacks and handles bugs
"""
if exception:
logging.error(traceback.format_exc())
return json.dumps({"result":None, 'error':{'message':'Invalid request'}, 'id':1})
@app.route("/", methods=['POST'])
@app.route("/mine", methods=['POST','GET'])
def mine():
"""
Function that does basic handling of work requests
"""
try:
rpc_request = json.loads(request.data)
except ValueError, e:
return bitHopper.util.error_rpc()
#Check for valid rpc_request
if not bitHopper.util.validate_rpc(rpc_request):
return bitHopper.util.error_rpc()
#If getworks just feed them data
if rpc_request['params'] == []:
#TODO, pass in headers
content, headers = bitHopper.Network.get_work()
#Otherwise submit the work unit
else:
content, headers = bitHopper.Network.submit_work(rpc_request)
return content
| import logging, json
import bitHopper.Tracking
import bitHopper.util
import bitHopper.Network
import flask
app = flask.Flask(__name__, template_folder='./templates',
static_folder = './static')
app.Debug = False
@app.teardown_request
def teardown_request_wrap(exception):
"""
Prints tracebacks and handles bugs
"""
if exception:
logging.error(traceback.format_exc())
return json.dumps({"result":None, 'error':{'message':'Invalid request'}, 'id':1})
@app.route("/", methods=['POST'])
@app.route("/mine", methods=['POST','GET'])
def mine():
"""
Function that does basic handling of work requests
"""
try:
rpc_request = json.loads(request.data)
except ValueError, e:
return bitHopper.util.error_rpc()
#Check for valid rpc_request
if not bitHopper.util.validate_rpc(rpc_request):
return bitHopper.util.error_rpc()
#If getworks just feed them data
if rpc_request['params'] == []:
#TODO, pass in headers
content, headers = bitHopper.Network.get_work()
#Otherwise submit the work unit
else:
content, headers = bitHopper.Network.submit_work(rpc_request)
return content
|
Fix prototype template loading error | import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = settings.PROJECT_DIR / 'seimas/website'
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if (base / 'templates' / template).exists():
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
| import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = os.path.join('seimas', 'website')
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if os.path.exists(os.path.join(base, 'templates', template)):
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
|
Fix double error message when "tour" is missing | 'use strict';
angular.module('alienUiApp').factory('restTechnicalErrorInterceptor', ['$rootScope', '$q', '$window', 'toaster', '$translate',
function($rootScope, $q, $window, toaster, $translate) {
var extractErrorMessage = function(rejection) {
if (UTILS.isDefinedAndNotNull(rejection.data)) {
if (UTILS.isDefinedAndNotNull(rejection.data.error)) {
var error = rejection.data.error;
// Redirect to homepage when the user is not authenticated
if (error.code === 100) {
$window.location.href = '/';
} else {
return {
status: rejection.status,
data: 'ERRORS.' + error.code
};
}
} else {
// Error not defined ==> return the data part
return {
status: rejection.status,
data: rejection.data
};
}
} else {
// rejection.data not defined ==> unknown error
return {
status: rejection.status,
data: 'ERRORS.UNKNOWN'
};
}
};
return {
'responseError': function(rejection) {
var error = extractErrorMessage(rejection);
// Display the toaster message on top with 4000 ms display timeout
// Don't shot toaster for "tour" guides
if (rejection.config.url.indexOf('data/guides') < 0) {
toaster.pop('error', $translate('ERRORS.INTERNAL') + ' - ' + error.status, $translate(error.data), 4000, 'trustedHtml', null);
}
return $q.reject(rejection);
}
};
}
]);
| 'use strict';
angular.module('alienUiApp').factory('restTechnicalErrorInterceptor', ['$rootScope', '$q', '$window', 'toaster', '$translate',
function($rootScope, $q, $window, toaster, $translate) {
var extractErrorMessage = function(rejection) {
if (UTILS.isDefinedAndNotNull(rejection.data)) {
if (UTILS.isDefinedAndNotNull(rejection.data.error)) {
var error = rejection.data.error;
// Redirect to homepage when the user is not authenticated
if (error.code === 100) {
$window.location.href = '/';
} else {
return {
status: rejection.status,
data: 'ERRORS.' + error.code
};
}
} else {
// Error not defined ==> return the data part
return {
status: rejection.status,
data: rejection.data
};
}
} else {
// rejection.data not defined ==> unknown error
return {
status: rejection.status,
data: 'ERRORS.UNKNOWN'
};
}
};
return {
'responseError': function(rejection) {
var error = extractErrorMessage(rejection);
// Display the toaster message on top with 4000 ms display timeout
// Don't shot toaster for "tour" guides
if (error.data.indexOf('/data/guides') < 0) {
toaster.pop('error', $translate('ERRORS.INTERNAL') + ' - ' + error.status, $translate(error.data), 4000, 'trustedHtml', null);
}
return $q.reject(rejection);
}
};
}
]);
|
Use new GitBook 3 API to get plugin configuration |
import { uuid } from './util';
import * as chartFns from './chart';
const FORMAT_YAML = 'yaml';
let chartScriptFn = () => {};
module.exports = {
book: {
assets: './assets'
},
hooks: {
init: function () {
let pluginConfig = this.config.get('pluginsConfig.chart');
let type = pluginConfig.type;
chartScriptFn = chartFns[type];
}
},
blocks: {
chart: {
process: function (blk) {
let id = uuid();
let body = {};
try {
// get string in {% chart %}
let bodyString = blk.body.trim();
if (blk.kwargs.format === FORMAT_YAML) {
// load yaml into body:
body = require('js-yaml').safeLoad(bodyString);
} else {
// just think it as json:
// TODO: Avoiding `eval`
// https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval
eval('body=' + bodyString);
}
} catch (e) {
console.error(e);
}
let scripts = chartScriptFn(id, body);
return `<div>
<div id="${id}"></div>
<script>${scripts}</script>
</div>`;
}
}
}
};
|
import { uuid } from './util';
import * as chartFns from './chart';
const FORMAT_YAML = 'yaml';
let chartScriptFn = () => {};
module.exports = {
book: {
assets: './assets'
},
hooks: {
init: function () {
let pluginConfig = (this.options.pluginsConfig || {}).chart || {};
let type = pluginConfig.type;
chartScriptFn = chartFns[type];
}
},
blocks: {
chart: {
process: function (blk) {
let id = uuid();
let body = {};
try {
// get string in {% chart %}
let bodyString = blk.body.trim();
if (blk.kwargs.format === FORMAT_YAML) {
// load yaml into body:
body = require('js-yaml').safeLoad(bodyString);
} else {
// just think it as json:
// TODO: Avoiding `eval`
// https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval
eval('body=' + bodyString);
}
} catch (e) {
console.error(e);
}
let scripts = chartScriptFn(id, body);
return `<div>
<div id="${id}"></div>
<script>${scripts}</script>
</div>`;
}
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.