text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Enhance view with button to next setup: vacancies | @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.services.index.title') }}</div>
<div class="panel-body">
<table class="table table-condensed">
<tr>
<th>{{ trans('manager.services.index.th.name') }}</th>
</tr>
@foreach ($services as $service)
<tr>
<td title="{{ $service->description }}">
<div class="btn-group">
{!! Button::normal()->withIcon(Icon::edit())->asLinkTo( route('manager.business.service.edit', [$business->id, $service->id]) ) !!}
{!! Button::normal($service->name)->asLinkTo( route('manager.business.service.show', [$business->id, $service->id]) ) !!}
</div>
</td>
</tr>
@endforeach
</table>
{!! Button::primary(trans('manager.services.btn.create'))->withIcon(Icon::plus())->asLinkTo( route('manager.business.service.create', [$business->id]) )->block() !!}
</div>
</div>
@if ($business->services()->count())
{!! Alert::success(trans('manager.services.create.alert.got_to_vacancies')) !!}
{!! Button::normal(trans('manager.services.create.btn.got_to_vacancies'))->withIcon(Icon::time())->block()->asLinkTo(route('manager.business.vacancy.create', $business->id)) !!}
@endif
</div>
</div>
</div>
@endsection
| @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.services.index.title') }}</div>
<div class="panel-body">
<table class="table table-condensed">
<tr>
<th>{{ trans('manager.services.index.th.name') }}</th>
</tr>
@foreach ($services as $service)
<tr>
<td title="{{ $service->description }}">
<div class="btn-group">
{!! Button::normal()->withIcon(Icon::edit())->asLinkTo( route('manager.business.service.edit', [$business->id, $service->id]) ) !!}
{!! Button::normal($service->name)->asLinkTo( route('manager.business.service.show', [$business->id, $service->id]) ) !!}
</div>
</td>
</tr>
@endforeach
</table>
<div class="panel-footer">
{!! Button::primary(trans('manager.services.btn.create'))->withIcon(Icon::plus())->asLinkTo( route('manager.business.service.create', [$business->id]) )->block() !!}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
|
Install npm packages with unsafe permissions | <?php
namespace Opifer\CmsBundle\Composer;
use Composer\Script\Event;
class ScriptHandler
{
public static function installAssets(Event $event)
{
$event->getIO()->write('<info>Installing CmsBundle assets</info>');
$currentDirectory = getcwd();
$cmdDirectory = __DIR__.'/..';
chdir($cmdDirectory);
exec('bower update --allow-root', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running bower install failed with $return_var\n");
}
exec('npm install --unsafe-perm', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running npm failed with $return_var\n");
}
exec('gulp default', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running gulp failed with $return_var\n");
}
exec('npm run build', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running npm build failed with $return_var\n");
}
chdir($currentDirectory);
}
}
| <?php
namespace Opifer\CmsBundle\Composer;
use Composer\Script\Event;
class ScriptHandler
{
public static function installAssets(Event $event)
{
$event->getIO()->write('<info>Installing CmsBundle assets</info>');
$currentDirectory = getcwd();
$cmdDirectory = __DIR__.'/..';
chdir($cmdDirectory);
exec('bower update --allow-root', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running bower install failed with $return_var\n");
}
exec('npm install', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running npm failed with $return_var\n");
}
exec('gulp default', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running gulp failed with $return_var\n");
}
exec('npm run build', $output, $return_var);
$event->getIO()->write('<info>'.implode("\n", $output).'</info>');
if ($return_var) {
throw new \RuntimeException("Running npm build failed with $return_var\n");
}
chdir($currentDirectory);
}
}
|
Load conda tab at startup if url points there | define(function(require) {
var $ = require('jquery');
var IPython = require('base/js/namespace');
var models = require('./models');
var views = require('./views');
function load() {
if (!IPython.notebook_list) return;
var base_url = IPython.notebook_list.base_url;
$('head').append(
$('<link>')
.attr('rel', 'stylesheet')
.attr('type', 'text/css')
.attr('href', base_url + 'nbextensions/nb_conda/conda.css')
);
$.ajax(base_url + 'nbextensions/nb_conda/tab.html', {
dataType: 'html',
success: function(env_html, status, xhr) {
// Configure Conda tab
$(".tab-content").append($(env_html));
$("#tabs").append(
$('<li>')
.append(
$('<a>')
.attr('id', 'conda_tab')
.attr('href', '#conda')
.attr('data-toggle', 'tab')
.text('Conda')
.click(function (e) {
window.history.pushState(null, null, '#conda');
models.environments.load();
models.available.load();
})
)
);
views.EnvView.init();
views.AvailView.init();
views.InstalledView.init();
models.environments.view = views.EnvView;
models.available.view = views.AvailView;
models.installed.view = views.InstalledView;
if(window.location.hash === '#conda') {
$('#conda_tab').click();
}
}
});
}
return {
load_ipython_extension: load
};
});
| define(function(require) {
var $ = require('jquery');
var IPython = require('base/js/namespace');
var models = require('./models');
var views = require('./views');
function load() {
if (!IPython.notebook_list) return;
var base_url = IPython.notebook_list.base_url;
$('head').append(
$('<link>')
.attr('rel', 'stylesheet')
.attr('type', 'text/css')
.attr('href', base_url + 'nbextensions/nb_conda/conda.css')
);
$.ajax(base_url + 'nbextensions/nb_conda/tab.html', {
dataType: 'html',
success: function(env_html, status, xhr) {
// Configure Conda tab
$(".tab-content").append($(env_html));
$("#tabs").append(
$('<li>')
.append(
$('<a>')
.attr('href', '#conda')
.attr('data-toggle', 'tab')
.text('Conda')
.click(function (e) {
window.history.pushState(null, null, '#conda');
models.environments.load();
models.available.load();
})
)
);
views.EnvView.init();
views.AvailView.init();
views.InstalledView.init();
models.environments.view = views.EnvView;
models.available.view = views.AvailView;
models.installed.view = views.InstalledView;
}
});
}
return {
load_ipython_extension: load
};
});
|
Use trailing if last param starts with a semicolon | let MessageTags = require('./messagetags');
module.exports = class IrcMessage {
constructor(command, ...args) {
this.tags = Object.create(null);
this.prefix = '';
this.nick = '';
this.ident = '';
this.hostname = '';
this.command = command || '';
this.params = args || [];
}
to1459() {
let parts = [];
let tags = MessageTags.encode(this.tags);
if (tags) {
parts.push('@' + tags);
}
if (this.prefix) {
// TODO: If prefix is empty, build it from the nick!ident@hostname
parts.push(':' + this.prefix);
}
parts.push(this.command);
if (this.params.length > 0) {
this.params.forEach((param, idx) => {
if (idx === this.params.length - 1 && (param.indexOf(' ') > -1 || param.indexOf(':') === 0)) {
parts.push(':' + param);
} else {
parts.push(param);
}
});
}
return parts.join(' ');
}
toJson() {
return {
tags: Object.assign({}, this.tags),
source: this.prefix,
command: this.command,
params: this.params,
};
}
};
| let MessageTags = require('./messagetags');
module.exports = class IrcMessage {
constructor(command, ...args) {
this.tags = Object.create(null);
this.prefix = '';
this.nick = '';
this.ident = '';
this.hostname = '';
this.command = command || '';
this.params = args || [];
}
to1459() {
let parts = [];
let tags = MessageTags.encode(this.tags);
if (tags) {
parts.push('@' + tags);
}
if (this.prefix) {
// TODO: If prefix is empty, build it from the nick!ident@hostname
parts.push(':' + this.prefix);
}
parts.push(this.command);
if (this.params.length > 0) {
this.params.forEach((param, idx) => {
if (idx === this.params.length - 1 && param.indexOf(' ') > -1) {
parts.push(':' + param);
} else {
parts.push(param);
}
});
}
return parts.join(' ');
}
toJson() {
return {
tags: Object.assign({}, this.tags),
source: this.prefix,
command: this.command,
params: this.params,
};
}
};
|
Correct error where && was used instead of and | from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph quantifying the amount of green land between two locations")
parser.add_argument("--start", nargs="+",
help="The starting location, defaults to London ")
parser.add_argument("--end", nargs="+",
help="The ending location, defaults to Durham")
parser.add_argument("--steps", type=int,
help="An integer number of steps between the starting and ending locations, defaults to 10")
parser.add_argument("--out",
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
if arguments.start and arguments.end:
mygraph = Greengraph(arguments.start, arguments.end)
else:
mygraph = Greengraph("London", "Durham")
if arguments.steps:
data = mygraph.green_between(arguments.steps)
else:
data = mygraph.green_between(10)
plt.plot(data)
plt.xlabel("Step")
plt.ylabel("Number of green pixels (Max 160000)")
if arguments.start and arguments.end:
plt.title("Graph of green land between " +
" ".join(arguments.start) + " and " + " ".join(arguments.end))
else:
plt.title("Graph of green land between London and Durham")
if arguments.out:
plt.savefig(arguments.out)
else:
plt.savefig("graph.png")
if __name__ == "__main__":
process()
| from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph quantifying the amount of green land between two locations")
parser.add_argument("--start", nargs="+",
help="The starting location, defaults to London ")
parser.add_argument("--end", nargs="+",
help="The ending location, defaults to Durham")
parser.add_argument("--steps", type=int,
help="An integer number of steps between the starting and ending locations, defaults to 10")
parser.add_argument("--out",
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
if arguments.start & & arguments.end:
mygraph = Greengraph(arguments.start, arguments.end)
else:
mygraph = Greengraph("London", "Durham")
if arguments.steps:
data = mygraph.green_between(arguments.steps)
else:
data = mygraph.green_between(10)
plt.plot(data)
plt.xlabel("Step")
plt.ylabel("Greenness")
if arguments.start & & arguments.end:
plt.title("Graph of green land between " +
" ".join(arguments.start) + " and " + " ".join(arguments.end))
else:
plt.title("Graph of green land between London and Durham")
if arguments.out:
plt.savefig(arguments.out)
else:
plt.savefig("graph.png")
if __name__ == "__main__":
process()
|
Improve vector property error message | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
"""
_sphinx_prefix = 'properties.spatial'
@property
def default(self):
return getattr(self, '_default', [] if self.repeated else None)
@default.setter
def default(self, value):
self._default = self.validator(None, value).copy()
def validator(self, instance, value):
"""return a Vector based on input if input is valid"""
if isinstance(value, vmath.Vector):
return value
if isinstance(value, six.string_types):
if value.upper() == 'X':
return vmath.Vector(1, 0, 0)
if value.upper() == 'Y':
return vmath.Vector(0, 1, 0)
if value.upper() == 'Z':
return vmath.Vector(0, 0, 1)
try:
return vmath.Vector(value)
except Exception:
raise ValueError('{}: must be Vector with '
'3 elements'.format(self.name))
def from_json(self, value):
return vmath.Vector(*value)
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
"""
_sphinx_prefix = 'properties.spatial'
@property
def default(self):
return getattr(self, '_default', [] if self.repeated else None)
@default.setter
def default(self, value):
self._default = self.validator(None, value).copy()
def validator(self, instance, value):
"""return a Vector based on input if input is valid"""
if isinstance(value, vmath.Vector):
return value
if isinstance(value, six.string_types):
if value.upper() == 'X':
return vmath.Vector(1, 0, 0)
if value.upper() == 'Y':
return vmath.Vector(0, 1, 0)
if value.upper() == 'Z':
return vmath.Vector(0, 0, 1)
try:
return vmath.Vector(value)
except Exception:
raise ValueError('{} must be a Vector'.format(self.name))
def from_json(self, value):
return vmath.Vector(*value)
|
Use Cython version of toolz
Usage of activitysim within popultionsim fails with missing module cytoolz - i believe that activitysim is using cytoolz internally rather than toolz | from ez_setup import use_setuptools
use_setuptools() # nopep8
from setuptools import setup, find_packages
import os
import re
with open(os.path.join('activitysim', '__init__.py')) as f:
info = re.search(r'__.*', f.read(), re.S)
exec(info[0])
setup(
name='activitysim',
version=__version__,
description=__doc__,
author='contributing authors',
author_email='[email protected]',
license='BSD-3',
url='https://github.com/activitysim/activitysim',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
include_package_data=True,
entry_points={'console_scripts': ['activitysim=activitysim.cli.main:main']},
install_requires=[
'pyarrow >= 2.0',
'numpy >= 1.16.1',
'openmatrix >= 0.3.4.1',
'pandas >= 1.1.0',
'pyyaml >= 5.1',
'tables >= 3.5.1',
'cytoolz >= 0.8.1',
'psutil >= 4.1',
'requests >= 2.7',
'numba >= 0.51.2',
'orca >= 1.6',
]
)
| from ez_setup import use_setuptools
use_setuptools() # nopep8
from setuptools import setup, find_packages
import os
import re
with open(os.path.join('activitysim', '__init__.py')) as f:
info = re.search(r'__.*', f.read(), re.S)
exec(info[0])
setup(
name='activitysim',
version=__version__,
description=__doc__,
author='contributing authors',
author_email='[email protected]',
license='BSD-3',
url='https://github.com/activitysim/activitysim',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
include_package_data=True,
entry_points={'console_scripts': ['activitysim=activitysim.cli.main:main']},
install_requires=[
'pyarrow >= 2.0',
'numpy >= 1.16.1',
'openmatrix >= 0.3.4.1',
'pandas >= 1.1.0',
'pyyaml >= 5.1',
'tables >= 3.5.1',
'toolz >= 0.8.1',
'psutil >= 4.1',
'requests >= 2.7',
'numba >= 0.51.2',
'orca >= 1.6',
]
)
|
Check if relation objects are class of SerializeMixin | from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
:type: bool
:param include_hybrid: flag to include hybrid attributes if true
:return: dict
"""
result = dict()
if exclude is None:
view_cols = self.columns
else :
view_cols = filter(lambda e: e not in exclude, self.columns)
for key in view_cols :
result[key] = getattr(self, key)
if hybrid_attributes:
for key in self.hybrid_properties:
result[key] = getattr(self, key)
if nested:
for key in self.relations:
obj = getattr(self, key)
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
result[key] = [
o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj
if isinstance(o, SerializeMixin)
]
return result
| from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
:type: bool
:param include_hybrid: flag to include hybrid attributes if true
:return: dict
"""
result = dict()
if exclude is None:
view_cols = self.columns
else :
view_cols = filter(lambda e: e not in exclude, self.columns)
for key in view_cols :
result[key] = getattr(self, key)
if hybrid_attributes:
for key in self.hybrid_properties:
result[key] = getattr(self, key)
if nested:
for key in self.relations:
obj = getattr(self, key)
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
result[key] = [o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj]
return result
|
Add metadata to event payloads | 'use strict';
const { getReason } = require('../../error');
const { MODEL_TYPES } = require('../../constants');
const { defaultFormat } = require('../../formats');
// Builds requestinfo from request mInput
const buildRequestinfo = function ({
requestid,
timestamp,
responsetime,
ip,
protocol,
url,
origin,
path,
method,
protocolstatus,
status = 'SERVER_ERROR',
pathvars,
queryvars,
requestheaders,
responseheaders,
format: { name: format = 'raw' } = defaultFormat,
charset,
payload,
rpc,
summary,
topargs: args,
commandpath,
command,
collname: collection,
metadata,
response: {
content: response,
type: responsetype,
} = {},
modelscount,
uniquecount,
error,
}) {
const responsedata = MODEL_TYPES.includes(responsetype)
? response.data
: response;
const errorReason = error && getReason({ error });
return {
requestid,
timestamp,
responsetime,
ip,
protocol,
url,
origin,
path,
method,
protocolstatus,
status,
pathvars,
queryvars,
requestheaders,
responseheaders,
format,
charset,
payload,
rpc,
summary,
args,
commandpath,
command,
collection,
responsedata,
responsetype,
metadata,
modelscount,
uniquecount,
error: errorReason,
};
};
module.exports = {
buildRequestinfo,
};
| 'use strict';
const { getReason } = require('../../error');
const { MODEL_TYPES } = require('../../constants');
const { defaultFormat } = require('../../formats');
// Builds requestinfo from request mInput
const buildRequestinfo = function ({
requestid,
timestamp,
responsetime,
ip,
protocol,
url,
origin,
path,
method,
protocolstatus,
status = 'SERVER_ERROR',
pathvars,
queryvars,
requestheaders,
responseheaders,
format: { name: format = 'raw' } = defaultFormat,
charset,
payload,
rpc,
summary,
topargs: args,
commandpath,
command,
collname: collection,
response: {
content: response,
type: responsetype,
} = {},
modelscount,
uniquecount,
error,
}) {
const responsedata = MODEL_TYPES.includes(responsetype)
? response.data
: response;
const errorReason = error && getReason({ error });
return {
requestid,
timestamp,
responsetime,
ip,
protocol,
url,
origin,
path,
method,
protocolstatus,
status,
pathvars,
queryvars,
requestheaders,
responseheaders,
format,
charset,
payload,
rpc,
summary,
args,
commandpath,
command,
collection,
responsedata,
responsetype,
modelscount,
uniquecount,
error: errorReason,
};
};
module.exports = {
buildRequestinfo,
};
|
[BUGFIX] Correct extension manager dependencies to match composer requirements | <?php
/*
* This file is part of the package bk2k/bootstrap-package.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
$EM_CONF[$_EXTKEY] = [
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => [
'depends' => [
'typo3' => '10.4.0-11.1.99',
'rte_ckeditor' => '10.4.0-11.1.99',
'seo' => '10.4.0-11.1.99'
],
'conflicts' => [
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
],
],
'autoload' => [
'psr-4' => [
'BK2K\\BootstrapPackage\\' => 'Classes'
],
],
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'version' => '12.0.0-dev',
];
| <?php
/*
* This file is part of the package bk2k/bootstrap-package.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
$EM_CONF[$_EXTKEY] = [
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => [
'depends' => [
'typo3' => '9.5.0-11.0.99',
'rte_ckeditor' => '9.5.0-11.0.99',
'seo' => '9.5.0-11.0.99'
],
'conflicts' => [
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
],
],
'autoload' => [
'psr-4' => [
'BK2K\\BootstrapPackage\\' => 'Classes'
],
],
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'version' => '11.1.0-dev',
];
|
Use relative_to instead of string manipulation | #!/usr/bin/env python3
"""Remake the ziptestdata.zip file.
Run this to rebuild the importlib_resources/tests/data/ziptestdata.zip file,
e.g. if you want to add a new file to the zip.
This will replace the file with the new build, but it won't commit anything to
git.
"""
import contextlib
import os
import pathlib
from zipfile import ZipFile
def main():
suffixes = '01', '02'
tuple(map(generate, suffixes))
def generate(suffix):
basepath = pathlib.Path('ziptestdata')
base = pathlib.Path('importlib_resources/tests')
zfpath = base / f'zipdata{suffix}/ziptestdata.zip'
with ZipFile(zfpath, 'w') as zf:
datapath = base / f'data{suffix}'
for dirpath, dirnames, filenames in os.walk(datapath):
with contextlib.suppress(KeyError):
dirnames.remove('__pycache__')
loc = pathlib.Path(dirpath).relative_to(datapath)
for filename in filenames:
src = os.path.join(dirpath, filename)
if src == zfpath:
continue
dst = basepath / loc / filename
print(src, '->', dst)
zf.write(src, dst)
__name__ == '__main__' and main()
| #!/usr/bin/env python3
"""Remake the ziptestdata.zip file.
Run this to rebuild the importlib_resources/tests/data/ziptestdata.zip file,
e.g. if you want to add a new file to the zip.
This will replace the file with the new build, but it won't commit anything to
git.
"""
import contextlib
import os
import pathlib
from zipfile import ZipFile
def main():
suffixes = '01', '02'
tuple(map(generate, suffixes))
def generate(suffix):
basepath = pathlib.Path('ziptestdata')
base = pathlib.Path('importlib_resources/tests')
zfpath = base / f'zipdata{suffix}/ziptestdata.zip'
with ZipFile(zfpath, 'w') as zf:
relpath = base / f'data{suffix}'
for dirpath, dirnames, filenames in os.walk(relpath):
with contextlib.suppress(KeyError):
dirnames.remove('__pycache__')
for filename in filenames:
src = os.path.join(dirpath, filename)
if src == zfpath:
continue
commonpath = os.path.commonpath((relpath, dirpath))
dst = basepath / dirpath[len(commonpath) + 1 :] / filename
print(src, '->', dst)
zf.write(src, dst)
__name__ == '__main__' and main()
|
Fix issue where options['param'] can be None. | import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with',
action='append',
dest='param',
help='Pass key=val style param to generate_sampledata'),
)
def handle(self, *args, **options):
if options.get('param'):
for item in options['param']:
if '=' in item:
key, val = item.split('=')
else:
key, val = item, True
options[key] = val
# Allows you to specify which apps to generate sampledata for.
if not args:
args = []
for app in settings.INSTALLED_APPS:
if args and app not in args:
continue
try:
app_path = import_module(app).__path__
except AttributeError:
continue
try:
imp.find_module('sampledata', app_path)
except ImportError:
continue
module = import_module('%s.sampledata' % app)
if hasattr(module, 'generate_sampledata'):
self.stdout.write('Generating sample data from %s...' % app)
module.generate_sampledata(options)
self.stdout.write('Done!\n')
| import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with',
action='append',
dest='param',
help='Pass key=val style param to generate_sampledata'),
)
def handle(self, *args, **options):
for item in options.get('param', []):
if '=' in item:
key, val = item.split('=')
else:
key, val = item, True
options[key] = val
# Allows you to specify which apps to generate sampledata for.
if not args:
args = []
for app in settings.INSTALLED_APPS:
if args and app not in args:
continue
try:
app_path = import_module(app).__path__
except AttributeError:
continue
try:
imp.find_module('sampledata', app_path)
except ImportError:
continue
module = import_module('%s.sampledata' % app)
if hasattr(module, 'generate_sampledata'):
self.stdout.write('Generating sample data from %s...' % app)
module.generate_sampledata(options)
self.stdout.write('Done!\n')
|
Fix scanning page for phone numbers after reload/restart. | (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === null) {
storage.put(key, defaults[key]);
}
}
}
console.info('current storage:');
for(var i = 0; i < localStorage.length; i++) {
console.info(localStorage.key(i)+'='+localStorage.getItem(localStorage.key(i)));
}
// keep track of some notifications
storage.put('notifications', {});
panels.MainPanel(widgets);
// widgets initialization
for(var widget in widgets) {
widgets[widget].init();
}
// continue last session if credentials are available
if(storage.get('user') && storage.get('username') && storage.get('password')) {
for(var widget in widgets) {
widgets[widget].restore();
}
// look for phone numbers in tabs from now on
page.init();
}
});
window.logout = function() {
console.info('logout');
chrome.runtime.sendMessage('logout');
panels.resetStorage();
panels.resetWidgets();
page.reset();
storage.remove('user');
storage.remove('username');
storage.remove('password');
};
})();
| (function() {
'use strict';
window.widgets = {};
$(function() {
var defaults = {
platformUrl: 'https://partner.voipgrid.nl/',
c2d: 'true',
};
for(var key in defaults) {
if(defaults.hasOwnProperty(key)) {
if(storage.get(key) === null) {
storage.put(key, defaults[key]);
}
}
}
console.info('current storage:');
for(var i = 0; i < localStorage.length; i++) {
console.info(localStorage.key(i)+'='+localStorage.getItem(localStorage.key(i)));
}
// keep track of some notifications
storage.put('notifications', {});
panels.MainPanel(widgets);
// widgets initialization
for(var widget in widgets) {
widgets[widget].init();
}
// continue last session if credentials are available
if(storage.get('user') && storage.get('username') && storage.get('password')) {
for(var widget in widgets) {
widgets[widget].restore();
}
}
});
window.logout = function() {
console.info('logout');
chrome.runtime.sendMessage('logout');
panels.resetStorage();
panels.resetWidgets();
page.reset();
storage.remove('user');
storage.remove('username');
storage.remove('password');
};
})();
|
Adjust LPA cost from 110 GBP to 82 GBP | <?php
namespace Opg\Lpa\DataModel\Lpa\Payment;
use Opg\Lpa\DataModel\Lpa\Lpa;
class Calculator
{
const STANDARD_FEE = 82;
/**
* Calculate LPA payment amount
*
* @param Lpa $lpa
* @return NULL|Payment
*/
public static function calculate(Lpa $lpa)
{
if (!$lpa->payment instanceof Payment) {
return null;
}
if ($lpa->payment->reducedFeeReceivesBenefits && $lpa->payment->reducedFeeAwardedDamages) {
$amount = self::getBenefitsFee();
} else {
$isRepeatApplication = ($lpa->repeatCaseNumber != null);
if ($lpa->payment->reducedFeeUniversalCredit) {
$amount = null;
} elseif ($lpa->payment->reducedFeeLowIncome) {
$amount = self::getLowIncomeFee($isRepeatApplication);
} else {
$amount = self::getFullFee($isRepeatApplication);
}
}
$lpa->payment->amount = $amount;
return $lpa->payment;
}
public static function getFullFee($isRepeatApplication = false)
{
$fee = self::STANDARD_FEE / ($isRepeatApplication ? 2 : 1);
return (float) $fee;
}
public static function getLowIncomeFee($isRepeatApplication = false)
{
return (float) self::getFullFee($isRepeatApplication) / 2;
}
public static function getBenefitsFee()
{
return (float) 0;
}
}
| <?php
namespace Opg\Lpa\DataModel\Lpa\Payment;
use Opg\Lpa\DataModel\Lpa\Lpa;
class Calculator
{
const STANDARD_FEE = 110;
/**
* Calculate LPA payment amount
*
* @param Lpa $lpa
* @return NULL|Payment
*/
static public function calculate(Lpa $lpa)
{
if(!($lpa->payment instanceof Payment)) return null;
$isRepeatApplication = ($lpa->repeatCaseNumber != null);
if(($lpa->payment->reducedFeeReceivesBenefits) && ($lpa->payment->reducedFeeAwardedDamages)) {
$amount = self::getBenefitsFee();
} else {
if($lpa->payment->reducedFeeUniversalCredit) {
$amount = null;
}
elseif($lpa->payment->reducedFeeLowIncome) {
$amount = self::getLowIncomeFee( $isRepeatApplication );
}
else {
$amount = self::getFullFee( $isRepeatApplication );
}
}
$lpa->payment->amount = $amount;
return $lpa->payment;
}
public static function getFullFee( $isRepeatApplication = false ){
$denominator = ($isRepeatApplication) ? 2 : 1;
return (float) self::STANDARD_FEE / $denominator;
}
public static function getLowIncomeFee( $isRepeatApplication = false ){
return (float) self::getFullFee( $isRepeatApplication ) / 2;
}
public static function getBenefitsFee(){
return (float)0;
}
}
|
Add include property to babel loader | 'use strict';
const NODE_ENV = process.env.NODE_ENV || 'development';
const webpack = require('webpack');
const path = require('path');
const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build')
};
module.exports = {
entry: {
app: PATHS.app
},
output: {
path: PATHS.build,
filename: 'bundle.js'
},
watch: NODE_ENV === 'development',
watchOptions: {
aggregateTimeout: 100
},
devtool: NODE_ENV === 'development' ? 'cheap-module-inline-source-map' : null,
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
],
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js']
},
resolveLoader: {
modulesDirectories: ['node_modules'],
modulesTemplates: ['*-loader', '*'],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
},
include: [
PATHS.app
]
}
]
}
}; | 'use strict';
const NODE_ENV = process.env.NODE_ENV || 'development';
const webpack = require('webpack');
const path = require('path');
const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build')
};
module.exports = {
entry: {
app: PATHS.app
},
output: {
path: PATHS.build,
filename: 'bundle.js'
},
watch: NODE_ENV === 'development',
watchOptions: {
aggregateTimeout: 100
},
devtool: NODE_ENV === 'development' ? 'cheap-module-inline-source-map' : null,
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
],
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js']
},
resolveLoader: {
modulesDirectories: ['node_modules'],
modulesTemplates: ['*-loader', '*'],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}; |
Bump version for next release | from distutils.core import setup
setup(name='pyresttest',
version='1.6.1.dev',
description='Python RESTful API Testing & Microbenchmarking Tool',
long_description='Python RESTful API Testing & Microbenchmarking Tool \n Documentation at https://github.com/svanoort/pyresttest',
maintainer='Sam Van Oort',
maintainer_email='[email protected]',
url='https://github.com/svanoort/pyresttest',
keywords=['rest', 'web', 'http', 'testing'],
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Utilities'
],
py_modules=['pyresttest.resttest', 'pyresttest.generators', 'pyresttest.binding',
'pyresttest.parsing', 'pyresttest.validators', 'pyresttest.contenthandling',
'pyresttest.benchmarks', 'pyresttest.tests', 'pyresttest.ext.validator_jsonschema'],
license='Apache License, Version 2.0',
install_requires=['pyyaml', 'pycurl'],
# Make this executable from command line when installed
scripts=['util/pyresttest', 'util/resttest.py'],
provides=['pyresttest']
)
| from distutils.core import setup
setup(name='pyresttest',
version='1.6.0',
description='Python RESTful API Testing & Microbenchmarking Tool',
long_description='Python RESTful API Testing & Microbenchmarking Tool \n Documentation at https://github.com/svanoort/pyresttest',
maintainer='Sam Van Oort',
maintainer_email='[email protected]',
url='https://github.com/svanoort/pyresttest',
keywords=['rest', 'web', 'http', 'testing'],
classifiers=[
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Utilities'
],
py_modules=['pyresttest.resttest', 'pyresttest.generators', 'pyresttest.binding',
'pyresttest.parsing', 'pyresttest.validators', 'pyresttest.contenthandling',
'pyresttest.benchmarks', 'pyresttest.tests', 'pyresttest.ext.validator_jsonschema'],
license='Apache License, Version 2.0',
install_requires=['pyyaml', 'pycurl'],
# Make this executable from command line when installed
scripts=['util/pyresttest', 'util/resttest.py'],
provides=['pyresttest']
)
|
Fix rotation doubles text for free response bug | package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
beforeAddViewHook(mFreeText);
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} | package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
beforeAddViewHook(mFreeText);
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} |
Fix !events always returning no events | 'use strict';
const Promise = require('bluebird');
const i18next = Promise.promisifyAll(require('i18next'));
const MentionableCommandMiddleware = require('../../middleware/MentionableCommandMiddleware');
const RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
const CommandDatabaseSchedule = require('./CommandDatabaseSchedule');
class CommandEvents extends CommandDatabaseSchedule {
constructor(module) {
super(module, 'list', {
defaultTrigger: 'events'
});
i18next.loadNamespacesAsync('schedule').then(() => {
this.helpText = i18next.t('schedule:events.help');
this.shortHelpText = i18next.t('schedule:events.short-help');
});
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionableCommandMiddleware()
];
}
formatResult(response, result) {
const list = [];
if (result.length === 0) {
return i18next.t('schedule:events.response-empty');
}
for (let event of result) {
const id = event.id;
const title = event.title || i18next.t('schedule:events.missing-title');
const start = event.start;
if (start) {
list.push(i18next.t('schedule:events.response-item', { id, title, start }));
}
}
return i18next.t('schedule:events.response-list', { events: list.join('\n') });
}
}
module.exports = CommandEvents;
| 'use strict';
const Promise = require('bluebird');
const i18next = Promise.promisifyAll(require('i18next'));
const MentionableCommandMiddleware = require('../../middleware/MentionableCommandMiddleware');
const RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
const CommandDatabaseSchedule = require('./CommandDatabaseSchedule');
class CommandEvents extends CommandDatabaseSchedule {
constructor(module) {
super(module, 'list', {
defaultTrigger: 'events'
});
i18next.loadNamespacesAsync('schedule').then(() => {
this.helpText = i18next.t('schedule:events.help');
this.shortHelpText = i18next.t('schedule:events.short-help');
});
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionableCommandMiddleware()
];
}
formatResult(response, result) {
const list = [];
if (list.length === 0) {
return i18next.t('schedule:events.response-empty');
}
for (let event of result) {
const id = event.id;
const title = event.title || i18next.t('schedule:events.missing-title');
const start = event.start;
if (start) {
list.push(i18next.t('schedule:events.response-item', { id, title, start }));
}
}
return i18next.t('schedule:events.response-list', { events: list.join('\n') });
}
}
module.exports = CommandEvents;
|
Update the function which return the unique colors | <?php
class Database_operations {
private $database;
private $bird_db;
// Class constructor
function __construct($bird) {
try {
$this->bird_db = $bird;
$this->database = new PDO(
'mysql:host=localhost;dbname=gonm;charset=utf8',
'root',
'');
}
catch(Exception $e) {
die('Error : '.$e->getMessage());
}
}
// Return an bird with all the informations
function get_birds($code, $color) {
$request = $this->database->prepare("SELECT * FROM " . $this->bird_db .
" WHERE number = :number AND color = :color LIMIT 1");
$request->execute(array(
"number" => $code,
"color" => $color)
);
return $request;
}
// Get all the colors from the database
function get_unique_colors_rings() {
return $this->database->query("SELECT DISTINCT color FROM " . $this->bird_db);
}
}
?> | <?php
class Database_operations {
private $database;
private $bird_db;
// Class constructor
function __construct($bird) {
try {
$this->bird_db = $bird;
$this->database = new PDO(
'mysql:host=localhost;dbname=gonm;charset=utf8',
'root',
'');
}
catch(Exception $e) {
die('Error : '.$e->getMessage());
}
}
// Return an bird with all the informations
function get_birds($code, $color) {
$request = $this->database->prepare("SELECT * FROM " . $this->bird_db .
" WHERE number = :number AND color = :color LIMIT 1");
$request->execute(array(
"number" => $code,
"color" => $color)
);
return $request;
}
function get_unique_colors_rings() {
return $this->database->query("SELECT DISTINCT color FROM kentish_plover"); //. $this->bird_db . "");
}
}
?> |
Add WordPress thema as package type | <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
$this->hasName() &&
(
$this->hasPackageType() ||
$this->isSatisPackage()
);
}
/**
* Whether or not this composer file has a name
*/
protected function hasName()
{
return ! empty($this->content->name);
}
/**
* Whether or not this composer.json has a type that is a package
*
* @return bool
*/
protected function hasPackageType()
{
$allowableTypes = array(
'library',
'wordpress-plugin',
'wordpress-muplugin',
'wordpress-theme',
'symfony-bundle',
'drupal-module'
);
return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
}
/**
* Whether or not this composer is a satis package
*
* @return bool
*/
protected function isSatisPackage()
{
return
isset($this->content->extra) &&
isset($this->content->extra->{'satis-package'}) &&
true === $this->content->extra->{'satis-package'};
}
}
| <?php
namespace BeanstalkSatisGen\File;
class Composer extends Json
{
/**
* Returns whether or not this composer file is a satis package based on the
* contents.
*
* @return boolean
*/
public function isComposerPackage()
{
return
! empty($this->content) &&
$this->hasName() &&
(
$this->hasPackageType() ||
$this->isSatisPackage()
);
}
/**
* Whether or not this composer file has a name
*/
protected function hasName()
{
return ! empty($this->content->name);
}
/**
* Whether or not this composer.json has a type that is a package
*
* @return bool
*/
protected function hasPackageType()
{
$allowableTypes = array(
'library',
'wordpress-plugin',
'wordpress-muplugin',
'symfony-bundle',
'drupal-module'
);
return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
}
/**
* Whether or not this composer is a satis package
*
* @return bool
*/
protected function isSatisPackage()
{
return
isset($this->content->extra) &&
isset($this->content->extra->{'satis-package'}) &&
true === $this->content->extra->{'satis-package'};
}
}
|
Make check function a static function so it works better with Composer scripts | <?php namespace Kielabokkie\DotenvCheck;
use League\CLImate\CLImate;
class DotenvCheck
{
public static function check()
{
$cli = new CLImate;
$file = fopen(".env", "r");
$env = [];
while (feof($file) === false) {
$line = fgets($file);
$lineAry = explode("=", $line);
$key = trim($lineAry[0]);
if (empty($key) === false) {
$env[] = $key;
}
}
$file = fopen(".env.example", "r");
$envExample = [];
while (feof($file) === false) {
$line = fgets($file);
$lineAry = explode("=", $line);
$key = trim($lineAry[0]);
if (empty($key) === false) {
$envExample[] = $key;
}
}
$cli->br()->yellow('The following variables are missing from your .env file');
$result = array_diff($envExample, $env);
foreach ($result as $variable) {
$cli->red(sprintf('- %s', $variable));
}
$cli->br()->yellow('The following variables are in your .env file but not in .env.example');
$result = array_diff($env, $envExample);
foreach ($result as $variable) {
$cli->red(sprintf('- %s', $variable));
}
}
}
| <?php namespace Kielabokkie\DotenvCheck;
use League\CLImate\CLImate;
class DotenvCheck
{
private $cli;
public function __construct()
{
$this->cli = new CLImate;
}
public function check()
{
$file = fopen(".env", "r");
$env = [];
while (feof($file) === false) {
$line = fgets($file);
$lineAry = explode("=", $line);
$key = trim($lineAry[0]);
if (empty($key) === false) {
$env[] = $key;
}
}
$file = fopen(".env.example", "r");
$envExample = [];
while (feof($file) === false) {
$line = fgets($file);
$lineAry = explode("=", $line);
$key = trim($lineAry[0]);
if (empty($key) === false) {
$envExample[] = $key;
}
}
$this->cli->br()->yellow('The following variables are missing from your .env file');
$result = array_diff($envExample, $env);
foreach ($result as $variable) {
$this->cli->red(sprintf('- %s', $variable));
}
$this->cli->br()->yellow('The following variables are in your .env file but not in .env.example');
$result = array_diff($env, $envExample);
foreach ($result as $variable) {
$this->cli->red(sprintf('- %s', $variable));
}
}
}
|
Add AAT.stringifyResults to console.log the failures | 'use strict';
describe("Accessibility Test", function () {
var originalTimeout;
var testcasesHTML = window.__html__;
for (var testFile in testcasesHTML) {
(function (testFile) {
describe("\"" + testFile + "\"", function () {
beforeEach(function () {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 180000;
});
it('should have no accessibility violations', function (done) {
var testDataFileContent = testcasesHTML[testFile];
// Perform the accessibility scan using the AAT.getCompliance API
AAT.getCompliance(testDataFileContent, testFile, function (results) {
// Call the AAT.assertCompliance API which is used to compare the results with baseline object if we can find one that
// matches the same label which was provided.
var returnCode = AAT.assertCompliance(results);
if (returnCode !== 0) {
console.log(AAT.stringifyResults(results));
}
// In the case that the violationData is not defined then trigger an error right away.
expect(returnCode).toBe(0, "Scanning " + testFile + " failed.");
// Mark the testcases as done, when using jasmine as the test framework.
done();
});
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
});
})(testFile);
}
}); | 'use strict';
describe("Accessibility Test", function () {
var originalTimeout;
var testcasesHTML = window.__html__;
for (var testFile in testcasesHTML) {
(function (testFile) {
describe("\"" + testFile + "\"", function () {
beforeEach(function () {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 180000;
});
it('should have no accessibility violations', function (done) {
var testDataFileContent = testcasesHTML[testFile];
// Perform the accessibility scan using the AAT.getCompliance API
AAT.getCompliance(testDataFileContent, testFile, function (results) {
// Call the AAT.assertCompliance API which is used to compare the results with baseline object if we can find one that
// matches the same label which was provided.
var returnCode = AAT.assertCompliance(results);
// In the case that the violationData is not defined then trigger an error right away.
expect(returnCode).toBe(0, "Scanning " + testFile + " failed." + JSON.stringify(results));
// Mark the testcases as done, when using jasmine as the test framework.
done();
});
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
});
})(testFile);
}
}); |
Add trace option for Sass. | // Compile SCSS files to CSS
module.exports = function(grunt) {
grunt.config('sass', {
dev: {
options: {
sourcemap: true,
trace: false,
style: 'nested',
precision: 5
},
files: [{
expand: true,
cwd: 'scss',
src: ['*.scss'],
dest: 'styles',
ext: '.css'
}],
},
deploy: {
options: {
sourcemap: true,
trace: false,
style: 'compressed',
precision: 5
},
files: [{
expand: true,
cwd: 'scss',
src: ['*.scss'],
dest: 'dist/styles',
ext: '.css'
}],
},
});
grunt.loadNpmTasks('grunt-contrib-sass');
};
| // Compile SCSS files to CSS
module.exports = function(grunt) {
grunt.config('sass', {
dev: {
options: {
sourcemap: true,
style: 'nested',
precision: 5
},
files: [{
expand: true,
cwd: 'scss',
src: ['*.scss'],
dest: 'styles',
ext: '.css'
}],
},
deploy: {
options: {
sourcemap: true,
style: 'compressed',
precision: 5
},
files: [{
expand: true,
cwd: 'scss',
src: ['*.scss'],
dest: 'dist/styles',
ext: '.css'
}],
},
});
grunt.loadNpmTasks('grunt-contrib-sass');
};
|
Add type filter by slug | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter
from falmer.events.models import Curator
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
'student_group',
'from_time',
'to_time',
'audience_just_for_pgs',
'audience_suitable_kids_families',
'audience_good_to_meet_people',
'is_over_18_only',
'cost',
'alcohol',
'type',
'ticket_level',
'curated_by'
)
title = CharFilter(lookup_expr='icontains')
brand = CharFilter(field_name='brand__slug')
bundle = CharFilter(field_name='bundle__slug')
type = CharFilter(field_name='type__slug')
student_group = CharFilter(field_name='student_group__slug')
to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte')
from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
uncurated = BooleanFilter(field_name='curated_by', lookup_expr='isnull')
curated_by = ModelChoiceFilter(queryset=Curator.objects.all(), field_name='curated_by')
#
# class BrandingPeriodFilerSet(FilterSet):
# class Meta:
# model = BrandingPeriod
| from django_filters import FilterSet, CharFilter, IsoDateTimeFilter, BooleanFilter, ModelChoiceFilter
from falmer.events.models import Curator
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
'student_group',
'from_time',
'to_time',
'audience_just_for_pgs',
'audience_suitable_kids_families',
'audience_good_to_meet_people',
'is_over_18_only',
'cost',
'alcohol',
'type',
'ticket_level',
'curated_by'
)
title = CharFilter(lookup_expr='icontains')
brand = CharFilter(field_name='brand__slug')
bundle = CharFilter(field_name='bundle__slug')
student_group = CharFilter(field_name='student_group__slug')
to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte')
from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
uncurated = BooleanFilter(field_name='curated_by', lookup_expr='isnull')
curated_by = ModelChoiceFilter(queryset=Curator.objects.all(), field_name='curated_by')
#
# class BrandingPeriodFilerSet(FilterSet):
# class Meta:
# model = BrandingPeriod
|
Fix wrong privacy for attributes | <?php
namespace HiPay\Fullservice\Gateway\Model;
use HiPay\Fullservice\Gateway\Model\AbstractTransaction;
/**
*
* @package HiPay\Fullservice
* @author Kassim Belghait <[email protected]>
* @copyright Copyright (c) 2016 - HiPay
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 License
* @link https://github.com/hipay/hipay-fullservice-sdk-php
* @api
*/
class Operation extends AbstractTransaction
{
/**
*
* {@inheritDoc}
*
* @see \HiPay\Fullservice\Gateway\Model\AbstractTransaction::__construct()
*/
public function __construct(
$mid,
$authorizationCode,
$transactionReference,
$dateCreated,
$dateUpdated,
$dateAuthorized,
$status,
$state,
$message,
$authorizedAmount,
$capturedAmount,
$refundedAmount,
$decimals,
$currency,
$operation
) {
parent::__construct(
$mid,
$authorizationCode,
$transactionReference,
$dateCreated,
$dateUpdated,
$dateAuthorized,
$status,
$state,
$message,
$authorizedAmount,
$capturedAmount,
$refundedAmount,
$decimals,
$currency
);
$this->_operation = $operation;
}
public function getOperation()
{
return $this->_operation;
}
}
| <?php
namespace HiPay\Fullservice\Gateway\Model;
use HiPay\Fullservice\Gateway\Model\AbstractTransaction;
/**
*
* @package HiPay\Fullservice
* @author Kassim Belghait <[email protected]>
* @copyright Copyright (c) 2016 - HiPay
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 License
* @link https://github.com/hipay/hipay-fullservice-sdk-php
* @api
*/
class Operation extends AbstractTransaction
{
/**
* @var string $_operation Type of maintenance operation
*/
protected $_operation;
/**
*
* {@inheritDoc}
*
* @see \HiPay\Fullservice\Gateway\Model\AbstractTransaction::__construct()
*/
public function __construct(
$mid,
$authorizationCode,
$transactionReference,
$dateCreated,
$dateUpdated,
$dateAuthorized,
$status,
$state,
$message,
$authorizedAmount,
$capturedAmount,
$refundedAmount,
$decimals,
$currency,
$operation
) {
parent::__construct(
$mid,
$authorizationCode,
$transactionReference,
$dateCreated,
$dateUpdated,
$dateAuthorized,
$status,
$state,
$message,
$authorizedAmount,
$capturedAmount,
$refundedAmount,
$decimals,
$currency
);
$this->_operation = $operation;
}
public function getOperation()
{
return $this->_operation;
}
}
|
Fix pylint presubmit check, related to buildbot 0.8.x vs 0.7.x
[email protected]
BUG=
TEST=
Review URL: http://codereview.chromium.org/7631036
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@97254 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.scheduler import Scheduler
# This is due to buildbot 0.7.12 being used for the presubmit check.
from buildbot.changes.filter import ChangeFilter # pylint: disable=E0611,F0401
from master.factory import syzygy_factory
def win():
return syzygy_factory.SyzygyFactory('src/syzygy',
target_platform='win32')
def _VersionFileFilter(change):
"""A change filter function that disregards all changes that don't
touch src/syzygy/VERSION.
Args:
change: a buildbot Change object.
"""
return change.branch == 'trunk' and 'syzygy/VERSION' in change.files
#
# Official build scheduler for Syzygy
#
official_scheduler = Scheduler('syzygy_version',
treeStableTimer=0,
change_filter=ChangeFilter(
filter_fn=_VersionFileFilter),
builderNames=['Syzygy Official'])
#
# Windows official Release builder
#
official_factory = win().SyzygyFactory(official_release=True)
official_builder = {
'name': 'Syzygy Official',
'factory': official_factory,
'schedulers': 'syzygy_version',
'auto_reboot': False,
'category': 'official',
}
def Update(config, active_master, c):
c['schedulers'].append(official_scheduler)
c['builders'].append(official_builder)
| # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.scheduler import Scheduler
from buildbot.changes.filter import ChangeFilter
from master.factory import syzygy_factory
def win():
return syzygy_factory.SyzygyFactory('src/syzygy',
target_platform='win32')
def _VersionFileFilter(change):
"""A change filter function that disregards all changes that don't
touch src/syzygy/VERSION.
Args:
change: a buildbot Change object.
"""
return change.branch == 'trunk' and 'syzygy/VERSION' in change.files
#
# Official build scheduler for Syzygy
#
official_scheduler = Scheduler('syzygy_version',
treeStableTimer=0,
change_filter=ChangeFilter(
filter_fn=_VersionFileFilter),
builderNames=['Syzygy Official'])
#
# Windows official Release builder
#
official_factory = win().SyzygyFactory(official_release=True)
official_builder = {
'name': 'Syzygy Official',
'factory': official_factory,
'schedulers': 'syzygy_version',
'auto_reboot': False,
'category': 'official',
}
def Update(config, active_master, c):
c['schedulers'].append(official_scheduler)
c['builders'].append(official_builder)
|
Make url column data clickable | @extends('layouts.master')
@section('content')
@if ($message !== null)
<div class="alert alert-success alert-dismissible" role="alert">{{ $message }}</div>
@endif
<div class="container-fluid">
<div class="row">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>id</th>
<th>shortened url</th>
<th>original url</th>
<th>created</th>
<th>last updated</th>
</tr>
</thead>
<tbody>
@if (count($urls))
@foreach ($urls as $url)
<tr>
<td>{{ $url->id }}</td>
<td><a href="{{ $url->shortened_url }}">{{ $url->shortened_url }}</a></td>
<td><a href="{{ $url->original_url }}">{{ $url->original_url }}</a></td>
<td>{{ $url->formatDate($url->created_at) }}</td>
<td>{{ $url->formatDate($url->updated_at) }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
</div>
@endsection
| @extends('layouts.master')
@section('content')
@if ($message !== null)
<div class="alert alert-success alert-dismissible" role="alert">{{ $message }}</div>
@endif
<div class="container-fluid">
<div class="row">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>id</th>
<th>shortened url</th>
<th>original url</th>
<th>created</th>
<th>last updated</th>
</tr>
</thead>
<tbody>
@if (count($urls))
@foreach ($urls as $url)
<tr>
<td>{{ $url->id }}</td>
<td>{{ $url->shortened_url }}</td>
<td>{{ $url->original_url }}</td>
<td>{{ $url->formatDate($url->created_at) }}</td>
<td>{{ $url->formatDate($url->updated_at) }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
</div>
@endsection
|
Add third graph for Totals plugin | # Copyright 2013 John Reese
# Licensed under the MIT license
from ..lib import is_bot
from ..ent import Message
from ..graphs import NetworkKeyComparison, NetworkUserComparison
from .base import Plugin
class Totals(Plugin):
"""Gathers total message type statistics, broken down by channel, day
and user."""
def process_message(self, message):
nick = message.nick
mtype = Message.type_to_name(message.type)
kwargs = {
mtype: 1,
}
self.inc_shared_stats(nick, **kwargs)
def generate_graphs(self):
return [
NetworkKeyComparison(title='Logged Events',
network=self.network,
bars=True,
keys={k: k
for k in Message.type_names.values()},
),
NetworkUserComparison(title='Channel Joins',
network=self.network,
key=Message.type_to_name(Message.JOIN),
),
NetworkUserComparison(title='Messages Sent',
network=self.network,
bars=True,
key=Message.type_to_name(Message.MESSAGE)
),
]
class Wordcount(Plugin):
"""Tracks the average word count of messages."""
def process_message(self, message):
if is_bot(message) or not message.content:
return
nick = message.nick
word_count = len(message.content.split())
self.inc_shared_stats(nick,
word_count_total=word_count,
word_count_messages=1,
)
| # Copyright 2013 John Reese
# Licensed under the MIT license
from ..lib import is_bot
from ..ent import Message
from ..graphs import NetworkKeyComparison, NetworkUserComparison
from .base import Plugin
class Totals(Plugin):
"""Gathers total message type statistics, broken down by channel, day
and user."""
def process_message(self, message):
nick = message.nick
mtype = Message.type_to_name(message.type)
kwargs = {
mtype: 1,
}
self.inc_shared_stats(nick, **kwargs)
def generate_graphs(self):
return [
NetworkKeyComparison(title='Logged Events',
network=self.network,
bars=True,
keys={k: k
for k in Message.type_names.values()},
),
NetworkUserComparison(title='Channel Joins',
network=self.network,
bars=True,
key=Message.type_to_name(Message.JOIN),
log=True,
),
]
class Wordcount(Plugin):
"""Tracks the average word count of messages."""
def process_message(self, message):
if is_bot(message) or not message.content:
return
nick = message.nick
word_count = len(message.content.split())
self.inc_shared_stats(nick,
word_count_total=word_count,
word_count_messages=1,
)
|
Add __repr__ for elements for easier debugging | try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from inspect import isgenerator
class Element(object):
tag = ''
self_closing = False
def __init__(self, *children, **attrs):
if children and isinstance(children[0], dict):
self.attrs = children[0]
children = children[1:]
else:
self.attrs = attrs
# Some helpers for the `class` attribute
if 'classes' in attrs:
attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c)
elif 'class_' in attrs:
attrs['class'] = attrs.pop('class_')
self.children = []
self.add_children(children)
def __call__(self, *children):
self.add_children(children)
return self
def __repr__(self):
attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val)
return '<{}{}>'.format(self.tag, attr_string)
def add_children(self, children):
if self.self_closing and children:
raise ValueError("Self-closing tags can't have children.")
if children and isgenerator(children[0]):
children = children[0]
for child in children:
if child is not None:
if isinstance(child, list):
self.add_children(child)
else:
self.children.append(child)
| try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from inspect import isgenerator
class Element(object):
tag = ''
self_closing = False
def __init__(self, *children, **attrs):
if children and isinstance(children[0], dict):
self.attrs = children[0]
children = children[1:]
else:
self.attrs = attrs
# Some helpers for the `class` attribute
if 'classes' in attrs:
attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c)
elif 'class_' in attrs:
attrs['class'] = attrs.pop('class_')
self.children = []
self.add_children(children)
def __call__(self, *children):
self.add_children(children)
return self
def add_children(self, children):
if self.self_closing and children:
raise ValueError("Self-closing tags can't have children.")
if children and isgenerator(children[0]):
children = children[0]
for child in children:
if child is not None:
if isinstance(child, list):
self.add_children(child)
else:
self.children.append(child)
|
Add a nested class for nested menus | "use strict";
angular.module('arethusa.relation').directive('nestedMenu', [
'$compile',
'relation',
function($compile, relation) {
return {
restrict: 'A',
scope: {
relObj: '=',
labelObj: '=',
label: '=',
property: '=',
ancestors: '='
},
link: function(scope, element, attrs) {
var html = '\
<ul\
nested-menu-collection\
current="relObj"\
property="property"\
ancestors="ancestors"\
all="labelObj.nested">\
</ul>\
';
if (scope.labelObj.nested) {
element.append($compile(html)(scope));
element.addClass('nested');
}
scope.selectLabel = function() {
scope.relObj[scope.property] = scope.label;
relation.buildLabel(scope.relObj);
};
element.bind('click', function(event) {
scope.$apply(function() {
if (event.eventPhase === 2) { // at target, three would be bubbling!
scope.selectLabel();
if (scope.ancestors) {
relation.resetAncestors(scope.relObj);
}
}
if (scope.ancestors) {
relation.addAncestor(scope.relObj, scope.label);
}
});
});
},
template: '{{ label }}'
};
}
]);
| "use strict";
angular.module('arethusa.relation').directive('nestedMenu', [
'$compile',
'relation',
function($compile, relation) {
return {
restrict: 'A',
scope: {
relObj: '=',
labelObj: '=',
label: '=',
property: '=',
ancestors: '='
},
link: function(scope, element, attrs) {
var html = '\
<ul\
nested-menu-collection\
current="relObj"\
property="property"\
ancestors="ancestors"\
all="labelObj.nested">\
</ul>\
';
if (scope.labelObj.nested) {
element.append($compile(html)(scope));
}
scope.selectLabel = function() {
scope.relObj[scope.property] = scope.label;
relation.buildLabel(scope.relObj);
};
element.bind('click', function(event) {
scope.$apply(function() {
if (event.eventPhase === 2) { // at target, three would be bubbling!
scope.selectLabel();
if (scope.ancestors) {
relation.resetAncestors(scope.relObj);
}
}
if (scope.ancestors) {
relation.addAncestor(scope.relObj, scope.label);
}
});
});
},
template: '{{ label }}'
};
}
]);
|
Fix for user PS analysis. | 'use strict';
var User = require('../models/user');
var Person = require('../models/person');
var OperationalNumber = require('../models/psquare/op-number');
var _ = require('underscore');
var express = require('express');
var pSquare = require('../psquare_module/main');
function getUser(analystId) {
return User
.find({analystId: analystId})
.exec()
.then(function (data) {
return data[0];
});
}
var router = express.Router();
router.route('/psquare/:id')
.get(function (req, res) {
Person.findOne({_id: req.params.id}, function (err, person) {
if (err) {
res.send(err);
}
else {
getUser(person.analystId)
.then(function (user) {
var userLevel = _.isUndefined(user) ? 1 : user.level;
pSquare(person, res).make(userLevel);
}, function(err) {
res.send(err);
});
}
});
});
router.route('/psquare-data/numbers/:number')
.get(function (req, res) {
OperationalNumber.find({number: req.params.number}, function (err, opNumbers) {
if (err)
res.send(err);
res.json(opNumbers);
});
});
module.exports = router;
| 'use strict';
var User = require('../models/user');
var Person = require('../models/person');
var OperationalNumber = require('../models/psquare/op-number');
var express = require('express');
var pSquare = require('../psquare_module/main');
function getUser(analystId) {
return User
.find({analystId: analystId})
.exec()
.then(function (data) {
return data[0];
});
}
var router = express.Router();
router.route('/psquare/:id')
.get(function (req, res) {
Person.findOne({_id: req.params.id}, function (err, person) {
if (err) {
res.send(err);
}
else {
getUser(analystId)
.then(function (user) {
var userLevel = _.isUndefined(user) ? 1 : user.level;
pSquare(person, res).make(userLevel);
}, function(err) {
res.send(err);
});
}
});
});
router.route('/psquare-data/numbers/:number')
.get(function (req, res) {
OperationalNumber.find({number: req.params.number}, function (err, opNumbers) {
if (err)
res.send(err);
res.json(opNumbers);
});
});
module.exports = router;
|
Fix test for output skeleton plot | import os
import pytest
import tempfile
import pandas
from skan import pipe
@pytest.fixture
def image_filename():
rundir = os.path.abspath(os.path.dirname(__file__))
datadir = os.path.join(rundir, 'data')
return os.path.join(datadir, 'retic.tif')
def test_pipe(image_filename):
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight')
assert type(data) == pandas.DataFrame
assert data.shape[0] > 0
def test_pipe_figure(image_filename):
with tempfile.TemporaryDirectory() as tempdir:
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight',
save_skeleton='skeleton-plot-',
output_folder=tempdir)
assert type(data) == pandas.DataFrame
assert data.shape[0] > 0
expected_output = os.path.join(tempdir, 'skeleton-plot-' +
os.path.basename(image_filename)[:-4] +
'.png')
assert os.path.exists(expected_output)
| import os
import pytest
import tempfile
import pandas
from skan import pipe
@pytest.fixture
def image_filename():
rundir = os.path.abspath(os.path.dirname(__file__))
datadir = os.path.join(rundir, 'data')
return os.path.join(datadir, 'retic.tif')
def test_pipe(image_filename):
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight')
assert type(data) == pandas.DataFrame
assert data.shape[0] > 0
def test_pipe_figure(image_filename):
with tempfile.TemporaryDirectory() as tempdir:
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight',
save_skeleton='skeleton-plot-',
output_folder=tempdir)
assert type(data) == pandas.DataFrame
assert data.shape[0] > 0
assert os.path.exists(os.path.join(tempdir,
'skeleton-plot-' +
image_filename[:-4] +
'.png'))
|
Remove stray Git conflict markers | 'use strict';
module.exports = {
name: 'singleLinePerSelector',
nodeTypes: ['ruleset'],
message: 'Each selector should be on its own line.',
lint: function singleLinePerSelectorLinter (config, node) {
var report = false;
var results = [];
var self = this;
node.forEach('delimiter', function (element, index) {
element = node.get(index + 1);
// Check if the delimiter is on the next line
if (!element.is('space')) {
element = node.get(index - 1);
}
switch (config.style) {
case '18f':
node.forEach('selector', function (selector) {
selector = selector.first().first('ident').content;
if (selector.length >= 5) {
report = true;
return;
}
});
break;
default:
report = true;
break;
}
if (report && element.content.indexOf('\n') === -1) {
results.push({
column: element.start.column,
line: element.start.line,
message: self.message
});
}
});
if (results.length) {
return results;
}
}
};
| 'use strict';
module.exports = {
name: 'singleLinePerSelector',
nodeTypes: ['ruleset'],
message: 'Each selector should be on its own line.',
lint: function singleLinePerSelectorLinter (config, node) {
var report = false;
var results = [];
var self = this;
node.forEach('delimiter', function (element, index) {
element = node.get(index + 1);
// Check if the delimiter is on the next line
if (!element.is('space')) {
element = node.get(index - 1);
}
<<<<<<< HEAD
if (element.content.indexOf('\n') === -1) {
=======
switch (config.style) {
case '18f':
node.forEach('selector', function (selector) {
selector = selector.first().first('ident').content;
if (selector.length >= 5) {
report = true;
return;
}
});
break;
default:
report = true;
break;
}
if (report && element.content.indexOf('\n') === -1) {
>>>>>>> singleLinePerSelector-18f-option
results.push({
column: element.start.column,
line: element.start.line,
message: self.message
});
}
});
if (results.length) {
return results;
}
}
};
|
[UPADTE] Change router to history mode | import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Team from '@/components/Team'
import Events from '@/components/Events'
import Timeline from '@/components/Timeline'
import Blog from '@/components/Blog'
import Post from '@/components/Post'
import Linit from '@/components/Linit'
import PrivacyPolicy from '@/components/PrivacyPolicy'
import PageNotFound from '@/components/PageNotFound'
Vue.use(Router)
export default new Router({
mode: "history",
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/team',
name: 'Team',
component: Team
},
{
path: '/events',
name: 'Events',
component: Events
},
{
path: '/timeline',
name: 'Timeline',
component: Timeline
},
{
path: '/blog',
name: 'Blog',
component: Blog
},
{
path: '/blog/:post',
name: 'Post',
component: Post
},
{
path: '/linit',
name: 'Linit',
component: Linit
},
{
path: '/privacy',
name: 'PrivacyPolicy',
component: PrivacyPolicy
},
{
path: '*',
name: 'PageNotFound',
component: PageNotFound
}
]
})
| import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Team from '@/components/Team'
import Events from '@/components/Events'
import Timeline from '@/components/Timeline'
import Blog from '@/components/Blog'
import Post from '@/components/Post'
import Linit from '@/components/Linit'
import PrivacyPolicy from '@/components/PrivacyPolicy'
import PageNotFound from '@/components/PageNotFound'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/team',
name: 'Team',
component: Team
},
{
path: '/events',
name: 'Events',
component: Events
},
{
path: '/timeline',
name: 'Timeline',
component: Timeline
},
{
path: '/blog',
name: 'Blog',
component: Blog
},
{
path: '/blog/:post',
name: 'Post',
component: Post
},
{
path: '/linit',
name: 'Linit',
component: Linit
},
{
path: '/privacy',
name: 'PrivacyPolicy',
component: PrivacyPolicy
},
{
path: '*',
name: 'PageNotFound',
component: PageNotFound
}
]
})
|
Add id field to quotes table
Specify names for insert fields | import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY,
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes (author, quote, created_at) VALUES (?, ?, ?)
''', (author, quote, created_at))
| import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect to database with name {}'.format(name))
class DBClient(object):
"""Client for interacting with database for the application"""
def __init__(self, database_name: str):
self.conn = sqlite3.connect(database_name)
self._create_quotes_table()
def _create_quotes_table(self):
"""
Create the table used for storing quotes if it does not exist already
"""
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
author TEXT,
quote TEXT,
created_at TEXT
);
''')
def close_connection(self):
"""
Close connection to the database
"""
self.conn.close()
def insert_quote(self, author: str, quote: str, created_at: str):
"""
Insert a quote into the database
:param author: (str) Name of the author that said the quote
:param quote: (str) The quote for the author
:param created_at: (str) Timestamp for when the quote was saved to database
"""
with self.conn:
self.conn.execute('''
INSERT INTO quotes VALUES (?, ?, ?)
''', (author, quote, created_at))
|
Update image every 0.5s till button gets pressed again | #! /usr/bin/python3
import sys
import time
from PyQt5.QtWidgets import (QWidget, QHBoxLayout,
QLabel, QApplication, QPushButton)
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QObject
class FreakingQtImageViewer(QWidget):
def __init__(self, function):
super().__init__()
self.function = function
self.initUI(function)
self.refresh = False
def refresh(self):
if !self.refresh:
self.refresh = True
while self.refresh:
self.function()
pixmap = QPixmap("tmp.png")
pixmap = pixmap.scaledToWidth(800)
self.lbl.setPixmap(pixmap)
time.sleep(0.5)
else:
self.refresh = False
def initUI(self, function):
hbox = QHBoxLayout(self)
self.lbl = QLabel(self)
self.refresh()
btn = QPushButton(self)
btn.setText('Drück mich')
btn.clicked.connect(self.refresh)
hbox.addWidget(self.lbl)
hbox.addWidget(btn)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Freaking Qt Image Viewer')
self.show()
| #! /usr/bin/python3
import sys
from PyQt5.QtWidgets import (QWidget, QHBoxLayout,
QLabel, QApplication, QPushButton)
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QObject
class FreakingQtImageViewer(QWidget):
def __init__(self, function):
super().__init__()
self.function = function
self.initUI(function)
def refresh(self):
self.function()
pixmap = QPixmap("tmp.png")
pixmap = pixmap.scaledToWidth(800)
self.lbl.setPixmap(pixmap)
def initUI(self, function):
hbox = QHBoxLayout(self)
self.lbl = QLabel(self)
self.refresh()
btn = QPushButton(self)
btn.setText('Drück mich')
btn.clicked.connect(self.refresh)
hbox.addWidget(self.lbl)
hbox.addWidget(btn)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Freaking Qt Image Viewer')
self.show()
|
Update docs for prometheus path config | package io.quarkus.micrometer.runtime.config;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
@ConfigGroup
public class PrometheusConfigGroup implements MicrometerConfig.CapabilityEnabled {
/**
* Support for export to Prometheus.
* <p>
* Support for Prometheus will be enabled if Micrometer
* support is enabled, the PrometheusMeterRegistry is on the classpath
* and either this value is true, or this value is unset and
* {@code quarkus.micrometer.registry-enabled-default} is true.
*/
@ConfigItem
public Optional<Boolean> enabled;
/**
* The path for the prometheus metrics endpoint (produces text/plain). The default value is
* `metrics` and is resolved relative to the non-application endpoint (`q`), e.g.
* `${quarkus.http.root-path}/${quarkus.http.non-application-root-path}/metrics`.
* If an absolute path is specified (`/metrics`), the prometheus endpoint will be served
* from the configured path.
*
* @asciidoclet
*/
@ConfigItem(defaultValue = "metrics")
public String path;
/**
* By default, this extension will create a Prometheus MeterRegistry instance.
* <p>
* Use this attribute to veto the creation of the default Prometheus MeterRegistry.
*/
@ConfigItem(defaultValue = "true")
public boolean defaultRegistry;
@Override
public Optional<Boolean> getEnabled() {
return enabled;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "{path='" + path
+ ",enabled=" + enabled
+ ",defaultRegistry=" + defaultRegistry
+ '}';
}
}
| package io.quarkus.micrometer.runtime.config;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.quarkus.runtime.annotations.ConfigItem;
@ConfigGroup
public class PrometheusConfigGroup implements MicrometerConfig.CapabilityEnabled {
/**
* Support for export to Prometheus.
* <p>
* Support for Prometheus will be enabled if Micrometer
* support is enabled, the PrometheusMeterRegistry is on the classpath
* and either this value is true, or this value is unset and
* {@code quarkus.micrometer.registry-enabled-default} is true.
*/
@ConfigItem
public Optional<Boolean> enabled;
/**
* The path for the prometheus metrics endpoint (produces text/plain).
* The default value is {@code metrics}.
*/
@ConfigItem(defaultValue = "metrics")
public String path;
/**
* By default, this extension will create a Prometheus MeterRegistry instance.
* <p>
* Use this attribute to veto the creation of the default Prometheus MeterRegistry.
*/
@ConfigItem(defaultValue = "true")
public boolean defaultRegistry;
@Override
public Optional<Boolean> getEnabled() {
return enabled;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "{path='" + path
+ ",enabled=" + enabled
+ ",defaultRegistry=" + defaultRegistry
+ '}';
}
}
|
Make a real json response. | from flask import Flask, abort, jsonify
from flask_caching import Cache
from flask_cors import CORS
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +
'</head>' +
'<body>' +
'<p><a href="ki">Campus Solna (KI)</a></p>' +
'<p><a href="uu">Campus Uppsala (BMC)</a></p>' +
'</body>' +
'</html>')
return content
@app.route('/api/restaurants')
@cache.cached(timeout=3600)
def api_list_restaurants():
return jsonify(main.list_restaurants())
@app.route('/api/restaurant/<name>')
@cache.cached(timeout=3600)
def api_get_restaurant(name):
data = main.get_restaurant(name)
if not data:
abort(404)
return jsonify(data)
@app.route('/ki')
@cache.cached(timeout=3600)
def make_menu_ki():
return main.gen_ki_menu()
@app.route('/uu')
@cache.cached(timeout=3600)
def make_menu_uu():
return main.gen_uu_menu()
| import json
from flask import abort
from flask import Flask
from flask_caching import Cache
from flask_cors import CORS
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +
'</head>' +
'<body>' +
'<p><a href="ki">Campus Solna (KI)</a></p>' +
'<p><a href="uu">Campus Uppsala (BMC)</a></p>' +
'</body>' +
'</html>')
return content
@app.route('/api/restaurants')
@cache.cached(timeout=3600)
def api_list_restaurants():
return json.dumps(main.list_restaurants())
@app.route('/api/restaurant/<name>')
@cache.cached(timeout=3600)
def api_get_restaurant(name):
data = main.get_restaurant(name)
if not data:
abort(404)
return json.dumps(data)
@app.route('/ki')
@cache.cached(timeout=3600)
def make_menu_ki():
return main.gen_ki_menu()
@app.route('/uu')
@cache.cached(timeout=3600)
def make_menu_uu():
return main.gen_uu_menu()
|
Update accept header according to Github API documentation | const Request = require('request');
const env2 = require('env2');
const HapiCookie = require('hapi-auth-cookie');
env2('./config.env');
module.exports = {
path: '/welcome',
method: 'GET',
handler: (req, rep) => {
const accessUrl = `https://github.com/login/oauth/access_token`;
Request.post({
headers: {
// as recommended by the API documentation
Accept: `application/vnd.github.v3+json`
},
url: accessUrl,
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code
}
}, (err, res, body) => {
if (err) throw err;
let parsed = JSON.parse(body);
const userToken = {
access_token: parsed.access_token
};
Request.get({
headers: {
'User-Agent': 'GitPom',
// as recommended by the API documentation
Accept: `application/vnd.github.v3+json`,
Authorization: `token ${userToken.access_token}`
},
url: `https://api.github.com/user`
}, (err, res, body) => {
if (err) throw err;
parsed = JSON.parse(body);
const userDetails = {
userName: parsed.login,
avatarUrl: parsed.avatar_url
};
// set the cookie containing the token, the username and the avatar url
req.cookieAuth.set(Object.assign(userToken, userDetails));
rep.redirect('/');
});
});
}
};
| const Request = require('request');
const env2 = require('env2');
const HapiCookie = require('hapi-auth-cookie');
env2('./config.env');
module.exports = {
path: '/welcome',
method: 'GET',
handler: (req, rep) => {
const accessUrl = `https://github.com/login/oauth/access_token`;
Request.post({
headers: {
accept: 'application/json'
},
url: accessUrl,
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code
}
}, (err, res, body) => {
if (err) throw err;
let parsed = JSON.parse(body);
const userToken = {
access_token: parsed.access_token
};
Request.get({
headers: {
'User-Agent': 'GitPom',
// as recommended by the API documentation
Accept: `application/vnd.github.v3+json`,
Authorization: `token ${userToken.access_token}`
},
url: `https://api.github.com/user`
}, (err, res, body) => {
if (err) throw err;
parsed = JSON.parse(body);
const userDetails = {
userName: parsed.login,
avatarUrl: parsed.avatar_url
};
// set the cookie containing the token, the username and the avatar url
req.cookieAuth.set(Object.assign(userToken, userDetails));
rep.redirect('/');
});
});
}
};
|
Add in overwrite output file | from os import chmod, unlink, stat, makedirs
from os.path import isfile, split, exists
from shutil import copyfile
def move_verify_delete(in_file, out_file, overwrite=False):
'''
Moves in_file to out_file, verifies that the filesizes are the same and
then does a chmod 666
'''
if not exists(split(out_file)[0]):
makedirs(split(out_file)[0])
if isfile(in_file) and (overwrite or not isfile(out_file)):
orig_file_size = stat(in_file).st_size
copyfile(in_file, out_file)
new_file_size = stat(out_file).st_size
if new_file_size != orig_file_size:
raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size))
unlink(in_file)
#chmod(out_file, 666)
else:
raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file,
isfile(in_file),
out_file,
isfile(out_file))) | from os import chmod, unlink, stat, makedirs
from os.path import isfile, split, exists
from shutil import copyfile
def move_verify_delete(in_file, out_file):
'''
Moves in_file to out_file, verifies that the filesizes are the same and
then does a chmod 666
'''
if not exists(split(out_file)[0]):
makedirs(split(out_file)[0])
if isfile(in_file) and not isfile(out_file):
orig_file_size = stat(in_file).st_size
copyfile(in_file, out_file)
new_file_size = stat(out_file).st_size
if new_file_size != orig_file_size:
raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size))
unlink(in_file)
#chmod(out_file, 666)
else:
raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file,
isfile(in_file),
out_file,
isfile(out_file))) |
Exclude some wide categories for faster generation | <?php
get_header();
if (have_posts()) {
while (have_posts()) {
the_post();
?>
<div class="blogPost">
<?php the_content(); ?>
<?php
if (is_page("tags")) {
?>
<ul class="tagList">
<?php
wp_list_categories(
array(
"hierarchical" => 1,
"title_li" => __(""),
"show_count" => 1,
"depth" => 0,
"exclude" => "1,7,9,11,19,100,104,148"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "yearly"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "monthly"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "daily"
)
);
?>
</ul>
<?php
}
?>
</div>
<?php
}
}
get_footer();
?>
| <?php
get_header();
if (have_posts()) {
while (have_posts()) {
the_post();
?>
<div class="blogPost">
<?php the_content(); ?>
<?php
if (is_page("tags")) {
?>
<ul class="tagList">
<?php
wp_list_categories(
array(
"hierarchical" => 1,
"title_li" => __(""),
"show_count" => 1,
"depth" => 0,
"exclude" => "1,7,11,148"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "yearly"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "monthly"
)
);
?>
</ul>
<ul class="tagList">
<?php
wp_get_archives(
array(
"type" => "daily"
)
);
?>
</ul>
<?php
}
?>
</div>
<?php
}
}
get_footer();
?>
|
Add watch to grunt defaults | /*jslint node:true */
/*globals module:false */
"use strict";
module.exports = function (grunt) {
var files = {
allSource: ['Gruntfile.js', 'package.json', 'lib/**/*.js', 'test/**/*.js'],
tests: ['test/**/*.js']
};
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jslint: {
allSource: {
src: files.allSource,
directives: {
todo: true
},
options: {
errorsOnly: true
}
}
},
simplemocha: {
options: {
reporter: 'tap'
},
all: {
src: files.tests
}
},
watch: {
files: files.allSource,
tasks: ['jslint', 'simplemocha']
}
});
grunt.loadNpmTasks('grunt-jslint');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('test', ['jslint', 'simplemocha']);
grunt.registerTask('default', ['jslint', 'simplemocha', 'watch']);
};
| /*jslint node:true */
/*globals module:false */
"use strict";
module.exports = function (grunt) {
var files = {
allSource: ['Gruntfile.js', 'package.json', 'lib/**/*.js', 'test/**/*.js'],
tests: ['test/**/*.js']
};
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jslint: {
allSource: {
src: files.allSource,
directives: {
todo: true
},
options: {
errorsOnly: true
}
}
},
simplemocha: {
options: {
reporter: 'tap'
},
all: {
src: files.tests
}
},
watch: {
files: files.allSource,
tasks: ['jslint', 'simplemocha']
}
});
grunt.loadNpmTasks('grunt-jslint');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('test', ['jslint', 'simplemocha']);
grunt.registerTask('default', ['jslint', 'simplemocha']);
};
|
Change to courses page in stead of lecture 1 when logging in | (function() {
'use strict';
angular
.module('lecturer')
.controller('LoginCtrl', LoginController);
/* @ngInject */
function LoginController(lecturerFactory, $location) {
console.log('Ready (Login Controller)');
angular.element('#login-btn').addClass('active');
if (lecturerFactory.isLoggedIn()) {
$location.path('/courses');
}
var vm = this;
vm.loginAttempt = false;
vm.form = {};
vm.loginUser = loginUser;
function loginUser() {
lecturerFactory.login(vm.form,
function() {
$location.path('/courses');
},
function() {
vm.loginAttempt = true;
vm.feedbackMessage = 'Wrong user credentials';
vm.feedbackType = 'alert-danger';
vm.feedbackIcon = 'glyphicon-exclamation-sign';
}
);
}
}
})();
| (function() {
'use strict';
angular
.module('lecturer')
.controller('LoginCtrl', LoginController);
/* @ngInject */
function LoginController(lecturerFactory, $location) {
console.log('Ready (Login Controller)');
angular.element('#login-btn').addClass('active');
if (lecturerFactory.isLoggedIn()) {
$location.path('/courses');
}
var vm = this;
vm.loginAttempt = false;
vm.form = {};
vm.loginUser = loginUser;
function loginUser() {
lecturerFactory.login(vm.form,
function() {
$location.path('/lectures/1');
},
function() {
vm.loginAttempt = true;
vm.feedbackMessage = 'Wrong user credentials';
vm.feedbackType = 'alert-danger';
vm.feedbackIcon = 'glyphicon-exclamation-sign';
}
);
}
}
})();
|
Make the timing tasks parallel aware. | package com.lhkbob.entreri.task;
import java.util.Collections;
import java.util.Set;
import com.lhkbob.entreri.ComponentData;
import com.lhkbob.entreri.EntitySystem;
public final class Timers {
public static Task fixedDelta(double dt) {
return new FixedDeltaTask(dt);
}
public static Task measuredDelta() {
return new MeasuredDeltaTask();
}
private static class FixedDeltaTask implements Task, ParallelAware {
private final ElapsedTimeResult delta;
public FixedDeltaTask(double dt) {
delta = new ElapsedTimeResult(dt);
}
@Override
public Task process(EntitySystem system, Job job) {
job.report(delta);
return null;
}
@Override
public void reset(EntitySystem system) {
// do nothing
}
@Override
public Set<Class<? extends ComponentData<?>>> getAccessedComponents() {
return Collections.emptySet();
}
@Override
public boolean isEntitySetModified() {
return false;
}
}
private static class MeasuredDeltaTask implements Task, ParallelAware {
private long lastStart = -1L;
@Override
public Task process(EntitySystem system, Job job) {
long now = System.nanoTime();
if (lastStart <= 0) {
job.report(new ElapsedTimeResult(0));
} else {
job.report(new ElapsedTimeResult((now - lastStart) / 1e9));
}
lastStart = now;
return null;
}
@Override
public void reset(EntitySystem system) {
// do nothing
}
@Override
public Set<Class<? extends ComponentData<?>>> getAccessedComponents() {
return Collections.emptySet();
}
@Override
public boolean isEntitySetModified() {
return false;
}
}
}
| package com.lhkbob.entreri.task;
import com.lhkbob.entreri.EntitySystem;
public final class Timers {
public static Task fixedDelta(double dt) {
return new FixedDeltaTask(dt);
}
public static Task measuredDelta() {
return new MeasuredDeltaTask();
}
private static class FixedDeltaTask implements Task {
private final ElapsedTimeResult delta;
public FixedDeltaTask(double dt) {
delta = new ElapsedTimeResult(dt);
}
@Override
public Task process(EntitySystem system, Job job) {
job.report(delta);
return null;
}
@Override
public void reset(EntitySystem system) {
// do nothing
}
}
private static class MeasuredDeltaTask implements Task {
private long lastStart = -1L;
@Override
public Task process(EntitySystem system, Job job) {
long now = System.nanoTime();
if (lastStart <= 0) {
job.report(new ElapsedTimeResult(0));
} else {
job.report(new ElapsedTimeResult((now - lastStart) / 1e9));
}
lastStart = now;
return null;
}
@Override
public void reset(EntitySystem system) {
// do nothing
}
}
}
|
Fix high scores displaying for more than one board | package com.gunshippenguin.openflood;
import android.content.SharedPreferences;
public class HighScoreManager {
SharedPreferences sp;
public HighScoreManager(SharedPreferences sp) {
this.sp = sp;
}
public boolean isHighScore(int boardSize, int numColors, int steps) {
if (!highScoreExists(boardSize, numColors)) {
return true;
} else {
return sp.getInt(getKey(boardSize, numColors), -1) > steps;
}
}
public boolean highScoreExists(int boardSize, int numColors) {
return sp.contains(getKey(boardSize, numColors));
}
public int getHighScore(int boardSize, int numColors) {
return sp.getInt(getKey(boardSize, numColors), -1);
}
public void setHighScore(int boardSize, int numColors, int steps) {
SharedPreferences.Editor editor = sp.edit();
editor.putInt(getKey(boardSize, numColors), steps);
editor.apply();
}
public void removeHighScore(int boardSize, int numColors) {
SharedPreferences.Editor editor = sp.edit();
editor.remove(getKey(boardSize, numColors));
editor.apply();
return;
}
private String getKey(int boardSize, int numColors) {
return String.format("highscore_%1$d_%2$d", boardSize, numColors);
}
}
| package com.gunshippenguin.openflood;
import android.content.SharedPreferences;
public class HighScoreManager {
SharedPreferences sp;
public HighScoreManager(SharedPreferences sp) {
this.sp = sp;
}
public boolean isHighScore(int boardSize, int numColors, int steps) {
if (!highScoreExists(boardSize, numColors)) {
return true;
} else {
return sp.getInt(getKey(boardSize, numColors), -1) > steps;
}
}
public boolean highScoreExists(int boardSize, int numColors) {
return sp.contains(getKey(boardSize, numColors));
}
public int getHighScore(int boardSize, int numColors) {
return sp.getInt(getKey(boardSize, numColors), -1);
}
public void setHighScore(int boardSize, int numColors, int steps) {
SharedPreferences.Editor editor = sp.edit();
editor.putInt(getKey(boardSize, numColors), steps);
editor.apply();
}
public void removeHighScore(int boardSize, int numColors) {
SharedPreferences.Editor editor = sp.edit();
editor.remove(getKey(boardSize, numColors));
editor.apply();
return;
}
private String getKey(int boardSize, int numColors) {
return String.format("highscore_%1$d_%1$d", boardSize, numColors);
}
}
|
Add error response to properties resource | package etomica.server.resources;
import etomica.meta.SimulationModel;
import etomica.meta.properties.Property;
import etomica.meta.wrappers.Wrapper;
import etomica.server.dao.SimulationStore;
import etomica.server.representations.PropertyUpdate;
import io.dropwizard.jersey.PATCH;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.UUID;
@Path("/simulations/{simId}/properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PropertiesResource {
private final SimulationStore simStore;
@Inject
public PropertiesResource(SimulationStore simStore) {
this.simStore = simStore;
}
@PUT
public void updateProperty(@PathParam("simId") String simId, PropertyUpdate propUpdate) {
SimulationModel model = simStore.get(UUID.fromString(simId));
Wrapper<?> wrapper = model.getWrapperById(propUpdate.getId());
Property wrapperProp = wrapper.getValueProperties().stream()
.filter(p -> p.getName().equalsIgnoreCase(propUpdate.getProperty()))
.findFirst().orElseThrow(() -> new WebApplicationException(Response.Status.BAD_REQUEST));
model.getSimulation().getController().doActionNow(() -> {
wrapperProp.invokeWriter(propUpdate.getNewValue());
});
}
}
| package etomica.server.resources;
import etomica.meta.SimulationModel;
import etomica.meta.properties.Property;
import etomica.meta.wrappers.Wrapper;
import etomica.server.dao.SimulationStore;
import etomica.server.representations.PropertyUpdate;
import io.dropwizard.jersey.PATCH;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;
@Path("/simulations/{simId}/properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PropertiesResource {
private final SimulationStore simStore;
@Inject
public PropertiesResource(SimulationStore simStore) {
this.simStore = simStore;
}
@PUT
public void updateProperty(@PathParam("simId") String simId, PropertyUpdate propUpdate) {
SimulationModel model = simStore.get(UUID.fromString(simId));
Wrapper<?> wrapper = model.getWrapperById(propUpdate.getId());
Property wrapperProp = wrapper.getValueProperties().stream()
.filter(p -> p.getName().equalsIgnoreCase(propUpdate.getProperty()))
.findFirst().get();
model.getSimulation().getController().doActionNow(() -> {
wrapperProp.invokeWriter(propUpdate.getNewValue());
});
}
}
|
Add tools to package data | #!/usr/bin/env python
from distutils.core import setup
import fedex
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
KEYWORDS = 'fedex soap suds wrapper rate location ship service'
setup(name='fedex',
version=fedex.VERSION,
description='Fedex Web Services API wrapper.',
long_description=LONG_DESCRIPTION,
author='Greg Taylor',
author_email='[email protected]',
maintainer='Python Fedex Developers',
url='https://github.com/python-fedex-devs/python-fedex',
download_url='http://pypi.python.org/pypi/fedex/',
packages=['fedex', 'fedex.services', 'fedex.printers'],
package_dir={'fedex': 'fedex'},
package_data={'fedex': ['wsdl/*.wsdl', 'wsdl/test_server_wsdl/*.wsdl', 'tools/*.py']},
platforms=['Platform Independent'],
license='BSD',
classifiers=CLASSIFIERS,
keywords=KEYWORDS,
requires=['suds'],
install_requires=['suds-jurko'],
)
| #!/usr/bin/env python
from distutils.core import setup
import fedex
LONG_DESCRIPTION = open('README.rst').read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
KEYWORDS = 'fedex soap suds wrapper rate location ship service'
setup(name='fedex',
version=fedex.VERSION,
description='Fedex Web Services API wrapper.',
long_description=LONG_DESCRIPTION,
author='Greg Taylor',
author_email='[email protected]',
maintainer='Python Fedex Developers',
url='https://github.com/python-fedex-devs/python-fedex',
download_url='http://pypi.python.org/pypi/fedex/',
packages=['fedex', 'fedex.services', 'fedex.printers'],
package_dir={'fedex': 'fedex'},
package_data={'fedex': ['wsdl/*.wsdl', 'wsdl/test_server_wsdl/*.wsdl']},
platforms=['Platform Independent'],
license='BSD',
classifiers=CLASSIFIERS,
keywords=KEYWORDS,
requires=['suds'],
install_requires=['suds-jurko'],
)
|
Add forgotten piece of eventlet executor | # Copyright 2013 Red Hat, Inc.
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
def start(self):
if self._thread is not None:
return
def _executor_thread():
try:
while True:
self._process_one_message()
except greenlet.GreenletExit:
return
self._thread = eventlet.spawn(_executor_thread)
def stop(self):
if self._thread is None:
return
self._thread.kill()
def wait(self):
if self._thread is None:
return
try:
self._thread.wait()
except greenlet.GreenletExit:
pass
self._thread = None
| # Copyright 2013 Red Hat, Inc.
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
def start(self):
if self._thread is not None:
return
def _executor_thread():
try:
while True:
except greenlet.GreenletExit:
return
self._thread = eventlet.spawn(_executor_thread)
def stop(self):
if self._thread is None:
return
self._thread.kill()
def wait(self):
if self._thread is None:
return
try:
self._thread.wait()
except greenlet.GreenletExit:
pass
self._thread = None
|
Add all optional dependencies to version info dict | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
import sys
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils and
its dependencies.
"""
versions = {'Python': sys.version.split()[0]}
packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage',
'sklearn', 'matplotlib', 'gwcs', 'bottleneck')
for package in packages:
try:
pkg = __import__(package)
version = pkg.__version__
except ImportError:
version = None
versions[package] = version
return versions
def _get_date(utc=False):
"""
Return a string of the current date/time.
Parameters
----------
utz : bool, optional
Whether to use the UTZ timezone instead of the local timezone.
Returns
-------
result : str
The current date/time.
"""
if not utc:
now = datetime.now().astimezone()
else:
now = datetime.now(timezone.utc)
return now.strftime('%Y-%m-%d %H:%M:%S %Z')
def _get_meta(utc=False):
"""
Return a metadata dictionary with the package versions and current
date/time.
"""
return {'date': _get_date(utc=utc),
'version': _get_version_info()}
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to return the installed astropy and photutils
versions.
"""
from datetime import datetime, timezone
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils and
its dependencies.
"""
versions = {}
packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage')
for package in packages:
try:
pkg = __import__(package)
version = pkg.__version__
except ImportError:
version = None
versions[package] = version
return versions
def _get_date(utc=False):
"""
Return a string of the current date/time.
Parameters
----------
utz : bool, optional
Whether to use the UTZ timezone instead of the local timezone.
Returns
-------
result : str
The current date/time.
"""
if not utc:
now = datetime.now().astimezone()
else:
now = datetime.now(timezone.utc)
return now.strftime('%Y-%m-%d %H:%M:%S %Z')
def _get_meta(utc=False):
"""
Return a metadata dictionary with the package versions and current
date/time.
"""
return {'date': _get_date(utc=utc),
'version': _get_version_info()}
|
Replace q with native Promises | /**
* Chai-Mugshot Plugin
*
* @param mugshot - Mugshot instance
* @param testRunnerCtx - Context of the test runner where the assertions are
* done
*/
module.exports = function(mugshot, testRunnerCtx) {
return function(chai) {
var Assertion = chai.Assertion;
function composeMessage(message) {
var standardMessage = 'expected baseline and screenshot of #{act}';
return {
affirmative: standardMessage + ' to ' + message,
negative: standardMessage + ' to not ' + message
};
}
function mugshotProperty(name, message) {
var msg = composeMessage(message);
Assertion.addProperty(name, function() {
var _this = this,
captureItem = this._obj,
promise, resolve, reject;
promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
mugshot.test(captureItem, function(error, result) {
if (error) {
reject(error);
} else {
if (testRunnerCtx !== undefined) {
testRunnerCtx.result = result;
}
try {
_this.assert(result.isEqual, msg.affirmative, msg.negative);
resolve();
} catch (error) {
reject(error);
}
}
});
return promise;
});
}
mugshotProperty('identical', 'be identical');
}
};
| var Q = require('q');
/**
* Chai-Mugshot Plugin
*
* @param mugshot - Mugshot instance
* @param testRunnerCtx - Context of the test runner where the assertions are
* done
*/
module.exports = function(mugshot, testRunnerCtx) {
return function(chai) {
var Assertion = chai.Assertion;
function composeMessage(message) {
var standardMessage = 'expected baseline and screenshot of #{act}';
return {
affirmative: standardMessage + ' to ' + message,
negative: standardMessage + ' to not ' + message
};
}
function mugshotProperty(name, message) {
var msg = composeMessage(message);
Assertion.addProperty(name, function() {
var captureItem = this._obj;
var deferred = Q.defer();
var _this = this;
mugshot.test(captureItem, function(error, result) {
if (error) {
deferred.reject(error);
} else {
if (testRunnerCtx !== undefined) {
testRunnerCtx.result = result;
}
try {
_this.assert(result.isEqual, msg.affirmative, msg.negative);
deferred.resolve();
} catch (error) {
deferred.reject(error);
}
}
});
return deferred.promise;
});
}
mugshotProperty('identical', 'be identical');
}
};
|
Remove measurement on-end event listener that was preventing the measurement result from being displayed | import Measurement from 'esri/dijit/Measurement';
import React, {
Component,
PropTypes
} from 'react';
export default class InfoWindow extends Component {
static contextTypes = {
map: PropTypes.object.isRequired
}
initialized = false
componentWillUpdate(prevProps) {
if (
this.context.map.loaded
// the Measurement tool depends on navigationManager so we
// need to explicitly check for that before starting the widget
&& this.context.map.navigationManager
&& !this.initialized
) {
this.initialized = true;
const measurementDiv = document.createElement('DIV');
this.measurementContainer.appendChild(measurementDiv);
this.measurement = new Measurement({
map: this.context.map
}, measurementDiv);
this.measurement.startup();
// this.measurement.on('measure-end', (event) => {
// // deactivate the tool after drawing
// const toolName = event.toolName;
// this.measurement.setTool(toolName, false);
// });
}
if (prevProps.activeWebmap !== undefined && prevProps.activeWebmap !== this.props.activeWebmap) {
if (this.context.map.destroy && this.initialized) {
this.measurement.clearResult();
this.initialized = false;
}
}
}
componentWillUnmount() {
this.measurement.destroy();
}
render () {
return <div
ref={(div) => { this.measurementContainer = div; }}
className='measurement-container'
/>;
}
}
| import Measurement from 'esri/dijit/Measurement';
import React, {
Component,
PropTypes
} from 'react';
export default class InfoWindow extends Component {
static contextTypes = {
map: PropTypes.object.isRequired
}
initialized = false
componentWillUpdate(prevProps) {
if (
this.context.map.loaded
// the Measurement tool depends on navigationManager so we
// need to explicitly check for that before starting the widget
&& this.context.map.navigationManager
&& !this.initialized
) {
this.initialized = true;
const measurementDiv = document.createElement('DIV');
this.measurementContainer.appendChild(measurementDiv);
this.measurement = new Measurement({
map: this.context.map
}, measurementDiv);
this.measurement.startup();
this.measurement.on('measure-end', (event) => {
// deactivate the tool after drawing
const toolName = event.toolName;
this.measurement.setTool(toolName, false);
});
}
if (prevProps.activeWebmap !== undefined && prevProps.activeWebmap !== this.props.activeWebmap) {
if (this.context.map.destroy && this.initialized) {
this.measurement.clearResult();
this.initialized = false;
}
}
}
componentWillUnmount() {
this.measurement.destroy();
}
render () {
return <div
ref={(div) => { this.measurementContainer = div; }}
className='measurement-container'
/>;
}
}
|
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend. | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = '';
this.aim = '';
this.status = 'in-progress';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
|
[FrameworkBundle] Allow to use the BrowserKit assertions with Panther and API Platform's test client | <?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\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorAttributeValueSame extends Constraint
{
private $selector;
private $attribute;
private $expectedText;
public function __construct(string $selector, string $attribute, string $expectedText)
{
$this->selector = $selector;
$this->attribute = $attribute;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->attr($this->attribute));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
| <?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\Component\DomCrawler\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;
final class CrawlerSelectorAttributeValueSame extends Constraint
{
private $selector;
private $attribute;
private $expectedText;
public function __construct(string $selector, string $attribute, string $expectedText)
{
$this->selector = $selector;
$this->attribute = $attribute;
$this->expectedText = $expectedText;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function matches($crawler): bool
{
$crawler = $crawler->filter($this->selector);
if (!\count($crawler)) {
return false;
}
return $this->expectedText === trim($crawler->getNode(0)->getAttribute($this->attribute));
}
/**
* @param Crawler $crawler
*
* {@inheritdoc}
*/
protected function failureDescription($crawler): string
{
return 'the Crawler '.$this->toString();
}
}
|
[TASK] Raise allowed TYPO3 version to 9.5.99 | <?php
/*
* This file is part of the package bk2k/bootstrap-package.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
$EM_CONF[$_EXTKEY] = [
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => [
'depends' => [
'typo3' => '8.7.0-9.5.99',
'rte_ckeditor' => '8.7.0-9.5.99'
],
'conflicts' => [
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
],
],
'autoload' => [
'psr-4' => [
'BK2K\\BootstrapPackage\\' => 'Classes'
],
],
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'version' => '9.1.0',
];
| <?php
/*
* This file is part of the package bk2k/bootstrap-package.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
$EM_CONF[$_EXTKEY] = [
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'constraints' => [
'depends' => [
'typo3' => '8.7.0-9.0.99',
'rte_ckeditor' => '8.7.0-9.0.99'
],
'conflicts' => [
'css_styled_content' => '*',
'fluid_styled_content' => '*',
'themes' => '*',
'fluidpages' => '*',
'dyncss' => '*',
],
],
'autoload' => [
'psr-4' => [
'BK2K\\BootstrapPackage\\' => 'Classes'
],
],
'state' => 'stable',
'uploadfolder' => 0,
'createDirs' => '',
'clearCacheOnLoad' => 1,
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'version' => '9.1.0',
];
|
Swap ndcms for generic T3 string. | from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
"srm://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
]
)
processing = Category(
name='processing',
cores=1,
runtime=900,
memory=1000
)
workflows = []
single_mu = Workflow(
label='single_mu',
dataset=cmssw.Dataset(
dataset='/SingleMu/Run2012A-recover-06Aug2012-v1/AOD',
events_per_task=5000
),
category=processing,
pset='slim.py',
publish_label='test',
merge_size='3.5G',
outputs=['output.root']
)
workflows.append(single_mu)
config = Config(
label='shuffle',
workdir='/tmpscratch/users/matze/test_shuffle_take30',
plotdir='/afs/crc.nd.edu/user/m/mwolf3/www/lobster/test_shuffle_take29',
storage=storage,
workflows=workflows,
advanced=AdvancedOptions(log_level=1)
)
| from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://ndcms.crc.nd.edu//store/user/matze/test_shuffle_take29",
"srm://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
]
)
processing = Category(
name='processing',
cores=1,
runtime=900,
memory=1000
)
workflows = []
single_mu = Workflow(
label='single_mu',
dataset=cmssw.Dataset(
dataset='/SingleMu/Run2012A-recover-06Aug2012-v1/AOD',
events_per_task=5000
),
category=processing,
pset='slim.py',
publish_label='test',
merge_size='3.5G',
outputs=['output.root']
)
workflows.append(single_mu)
config = Config(
label='shuffle',
workdir='/tmpscratch/users/matze/test_shuffle_take30',
plotdir='/afs/crc.nd.edu/user/m/mwolf3/www/lobster/test_shuffle_take29',
storage=storage,
workflows=workflows,
advanced=AdvancedOptions(log_level=1)
)
|
Update coverage values to match existing | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 98,
statements: 99
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
| 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 97,
statements: 98
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
|
Use the python MBox class rather than parsing the mailbox manually | #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
| #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
|
Fix for test in IE. Conditions were passing, but due to IE's JS implementation of named functions, it didn't recognise the equality test as equal. Further info in test. | /*jslint*/
(function(){
var testElement = '<div id="testElement">'+
'<a class="link"><a class="sub-link"></a></a>'+
'</div>';
function teardown() {
$('#testElement').remove();
}
function setup() {
$('body').append(testElement);
}
module("Context binding", {teardown: teardown, setup: setup });
test("Context inside viewController init", function() {
var viewController = {
init : function init() {
// IE doesn't recognise named functions reference and contexual function ref as the same in
// in this instance. We must convert toString() to test equality
equal(init.toString(), this.init.toString(), 'context of this, is this view controller');
this.test();
},
test : function() {
ok(true, 'test function can be accessed from init function, using this');
this.test2();
},
test2 : function() {
ok(true, 'test2 function can be accessed from test function, using this');
}
};
$('#testElement').capture(viewController);
expect(3);
});
test("Context inside viewController events", function() {
var viewController = {
onclick : {
'.link': function(e) {
equal(e.target, $('#testElement .link')[0], 'e target is element clicked on');
equal(this.element[0], $('#testElement')[0], 'this.element is the viewController bound unto');
}
}
};
$('#testElement').capture(viewController);
$('#testElement .link').click();
});
}()); | /*jslint*/
(function(){
var testElement = '<div id="testElement">'+
'<a class="link"><a class="sub-link"></a></a>'+
'</div>';
function teardown() {
$('#testElement').remove();
}
function setup() {
$('body').append(testElement);
}
module("Context binding", {teardown: teardown, setup: setup });
test("Context inside viewController init", function() {
var viewController = {
init : function init() {
equal(init, this.init, 'context of this, is this view controller');
this.test();
},
test : function() {
ok(true, 'test function can be accessed from init function, using this');
this.test2();
},
test2 : function() {
ok(true, 'test2 function can be accessed from test function, using this');
}
};
$('#testElement').capture(viewController);
expect(3);
});
test("Context inside viewController events", function() {
var viewController = {
onclick : {
'.link': function(e) {
equal(e.target, $('#testElement .link')[0], 'e target is element clicked on');
equal(this.element[0], $('#testElement')[0], 'this.element is the viewController bound unto');
}
}
};
$('#testElement').capture(viewController);
$('#testElement .link').click();
});
}()); |
Fix value is "" hand value being None in prepare | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""
data_type_name = "Enum"
def __init__(self, enum, **options):
# type: (Type[ET], **Any) -> None
# Generate choices structure from choices
choices = options.pop("choices", None)
options["choices"] = tuple((e, e.name) for e in choices or enum)
super(EnumField, self).__init__(**options)
self.enum = enum
@property
def choices_doc_text(self):
"""
Choices converted for documentation purposes.
"""
return tuple((v.value, n) for v, n in self.choices)
def to_python(self, value):
# type: (Any) -> Optional[ET]
if value is None:
return
# Attempt to convert
try:
return self.enum(value)
except ValueError:
# If value is an empty string return None
# Do this check here to support enums that define an option using
# an empty string.
if value == "":
return
raise ValidationError(self.error_messages["invalid_choice"] % value)
def prepare(self, value):
# type: (Optional[ET]) -> Any
if (value is not None) and (value in self.enum):
return value.value
| from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""
data_type_name = "Enum"
def __init__(self, enum, **options):
# type: (Type[ET], **Any) -> None
# Generate choices structure from choices
choices = options.pop("choices", None)
options["choices"] = tuple((e, e.name) for e in choices or enum)
super(EnumField, self).__init__(**options)
self.enum = enum
@property
def choices_doc_text(self):
"""
Choices converted for documentation purposes.
"""
return tuple((v.value, n) for v, n in self.choices)
def to_python(self, value):
# type: (Any) -> Optional[ET]
if value is None:
return
# Attempt to convert
try:
return self.enum(value)
except ValueError:
# If value is an empty string return None
# Do this check here to support enums that define an option using
# an empty string.
if value is "":
return
raise ValidationError(self.error_messages["invalid_choice"] % value)
def prepare(self, value):
# type: (Optional[ET]) -> Any
if value in self.enum:
return value.value
|
Drop old django version support (1.10) | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_summernote.db',
}
}
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
STATIC_URL = '/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'test_media'
SECRET_KEY = 'django_summernote'
ROOT_URLCONF = 'django_summernote.urls'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django_summernote',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
},
},
]
if django.VERSION >= (3, 0):
X_FRAME_OPTIONS = 'SAMEORIGIN'
| import django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_summernote.db',
}
}
__MIDDLEWARE__ = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
if django.VERSION < (1, 10):
MIDDLEWARE_CLASSES = __MIDDLEWARE__
else:
MIDDLEWARE = __MIDDLEWARE__
STATIC_URL = '/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'test_media'
SECRET_KEY = 'django_summernote'
ROOT_URLCONF = 'django_summernote.urls'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django_summernote',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
},
},
]
if django.VERSION >= (3, 0):
X_FRAME_OPTIONS = 'SAMEORIGIN'
|
Sort Metrics displayed in ASCII Table | <?php declare(strict_types=1);
namespace Wnx\LaravelStats\ShareableMetrics;
use Illuminate\Support\Collection;
class MetricsCollection extends Collection
{
public function toAsciiTableFormat(): array
{
$projectMetrics = $this->items['project_metrics']
->map(function ($metric) {
if (is_array($metric)) {
return json_encode($metric, JSON_PRETTY_PRINT);
}
if ($metric === true) {
return 'true';
}
if ($metric === false) {
return 'false';
}
return $metric;
})
->sort();
return $projectMetrics
->forget('packages')
->keys()
->zip($projectMetrics)
->toArray();
}
public function toHttpPayload(string $projectName): array
{
$projectMetrics = $this->get('project_metrics');
$componentMetrics = $this->get('component_metrics');
return [
'project' => $projectName,
'metrics' => $projectMetrics
->merge($componentMetrics)
->sortKeys()
->toArray()
];
}
}
| <?php declare(strict_types=1);
namespace Wnx\LaravelStats\ShareableMetrics;
use Illuminate\Support\Collection;
class MetricsCollection extends Collection
{
public function toAsciiTableFormat(): array
{
$projectMetrics = $this->items['project_metrics']
->map(function ($metric) {
if (is_array($metric)) {
return json_encode($metric, JSON_PRETTY_PRINT);
}
if ($metric === true) {
return 'true';
}
if ($metric === false) {
return 'false';
}
return $metric;
});
return $projectMetrics
->forget('packages')
->keys()
->zip($projectMetrics)
->toArray();
}
public function toHttpPayload(string $projectName): array
{
$projectMetrics = $this->get('project_metrics');
$componentMetrics = $this->get('component_metrics');
return [
'project' => $projectName,
'metrics' => $projectMetrics
->merge($componentMetrics)
->sortKeys()
->toArray()
];
}
}
|
Initialize the color picker on startup but hide it, so the editor get the correct color. | var session = null;
// instead of windows.onload
$(document).ready( function() {
// hide iphone/ipad URL bar
setTimeout(function() { window.scrollTo(0, 1) }, 100);
// initialize zoness
session = new Session(
SESSION_TYPE_DRAW,
function() {
//console.log("page_draw/ready: session callback ok");
var board = new Board( session, 'session-board');
var drawing = new Editor(session, board, 'session-drawing');
var chat = new Chat(session),
picker = new Color.Picker({
size: Math.floor($(window).width() / 3),
callback: function(hex) {
drawing.color_set( "#" + hex );
}
});
$(picker.el).hide(); // hide color picker on startup
picker.el.style.bottom = "50px";
picker.el.style.left = "10px";
//console.log("page_draw/ready: prepicker");
$("#brush").click(function(event){
event.preventDefault();
if (true === $(picker.el).is(":hidden")) {
$(picker.el).show();
$("#brush-action").text("Hide");
} else {
$(picker.el).hide();
$("#brush-action").text("Show");
}
});
}
);
});
| var session = null, picker;
// instead of windows.onload
$(document).ready( function() {
// hide iphone/ipad URL bar
setTimeout(function() { window.scrollTo(0, 1) }, 100);
// initialize zoness
session = new Session(
SESSION_TYPE_DRAW,
function() {
//console.log("page_draw/ready: session callback ok");
var board = new Board( session, 'session-board');
var drawing = new Editor(session, board, 'session-drawing');
var chat = new Chat(session);
//console.log("page_draw/ready: prepicker");
$("#brush").click(function(event){
event.preventDefault();
var firstClick = false;
if (undefined === picker) {
picker = new Color.Picker({
size: Math.floor($(window).width() / 3),
callback: function(hex) {
drawing.color_set( "#" + hex );
}
});
picker.el.style.bottom = "50px";
picker.el.style.left = "10px";
firstClick = true;
$("#brush-action").text("Hide");
}
if (true === $(picker.el).is(":hidden")) {
$(picker.el).show();
$("#brush-action").text("Hide");
} else if (!firstClick) {
$(picker.el).hide();
$("#brush-action").text("Show");
}
});
}
);
});
|
Remove width and height when the overlay is invisible | import React from 'react';
import {
Animated,
StyleSheet,
View,
Dimensions,
TouchableHighlight
} from 'react-native';
const DEFAULT_ANIMATE_TIME = 300;
const styles = StyleSheet.create({
fullOverlay: {
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'transparent',
position: 'absolute'
},
emptyOverlay: {
width: 0,
height: 0,
backgroundColor: 'transparent',
position: 'absolute'
}
});
export default class Overlay extends React.Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0),
overlayStyle: styles.emptyOverlay
}
}
onAnimatedEnd() {
if(!this.props.visible) {
this.setState({overlayStyle:styles.emptyOverlay});
}
}
componentWillReceiveProps(newProps) {
if(newProps.visible){
this.setState({overlayStyle: styles.fullOverlay});
}
return Animated.timing(this.state.fadeAnim, {
toValue: newProps.visible ? 1 : 0,
duration: DEFAULT_ANIMATE_TIME
}).start(this.onAnimatedEnd.bind(this));
}
render() {
return (
<Animated.View style={[this.state.overlayStyle, {opacity: this.state.fadeAnim}]}>
{this.props.children}
</Animated.View>
);
}
}
| import React from 'react';
import {
Animated,
StyleSheet,
View,
Dimensions,
TouchableHighlight
} from 'react-native';
const DEFAULT_ANIMATE_TIME = 300;
const styles = StyleSheet.create({
fullOverlay: {
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'transparent',
position: 'absolute'
},
emptyOverlay: {
backgroundColor: 'transparent',
position: 'absolute'
}
});
export default class Overlay extends React.Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0),
overlayStyle: styles.emptyOverlay
}
}
onAnimatedEnd() {
if(!this.props.visible) {
this.setState({overlayStyle:styles.emptyOverlay});
}
}
componentWillReceiveProps(newProps) {
if(newProps.visible){
this.setState({overlayStyle: styles.fullOverlay});
}
return Animated.timing(this.state.fadeAnim, {
toValue: newProps.visible ? 1 : 0,
duration: DEFAULT_ANIMATE_TIME
}).start(this.onAnimatedEnd.bind(this));
}
render() {
return (
<Animated.View style={[this.state.overlayStyle, {opacity: this.state.fadeAnim}]}>
{this.props.children}
</Animated.View>
);
}
}
|
Allow symbolic values for vpc | import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:', 'vpc:')
def apply(instance):
def resolve_symbol(original_value):
value = original_value
visited = set()
while isinstance(value, basestring) \
and value.startswith(prefix):
value = value.format(region=config.region, **instance)
if value in instance \
and value not in visited:
visited.add(value)
value = instance[value]
else:
if original_value == value:
raise Exception("Unable to resolve '%s'" % value)
else:
raise Exception(
"While resolving '%s': unable to resolve '%s'"
% (original_value, value))
return value
# Resolve symbols
for prefix in _prefixes:
key = prefix[:-1]
if key not in instance:
continue
if isinstance(instance[key], basestring):
instance[key] = resolve_symbol(instance[key])
elif isinstance(instance[key], list):
instance[key] = map(resolve_symbol, instance[key])
# Drop resolvable symbols
for key in instance.keys():
if key.startswith(_prefixes):
del instance[key]
| import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:')
def apply(instance):
def resolve_symbol(original_value):
value = original_value
visited = set()
while isinstance(value, basestring) \
and value.startswith(prefix):
value = value.format(region=config.region, **instance)
if value in instance \
and value not in visited:
visited.add(value)
value = instance[value]
else:
if original_value == value:
raise Exception("Unable to resolve '%s'" % value)
else:
raise Exception(
"While resolving '%s': unable to resolve '%s'"
% (original_value, value))
return value
# Resolve symbols
for prefix in _prefixes:
key = prefix[:-1]
if key not in instance:
continue
if isinstance(instance[key], basestring):
instance[key] = resolve_symbol(instance[key])
elif isinstance(instance[key], list):
instance[key] = map(resolve_symbol, instance[key])
# Drop resolvable symbols
for key in instance.keys():
if key.startswith(_prefixes):
del instance[key]
|
Add clarifying(?) comment about uid caching | import tornado
from tornado import gen
import json
import os
BASE_PATH = '.'
base_url = '/paws/public/'
@gen.coroutine
def uid_for_user(user):
url = 'https://meta.wikimedia.org/w/api.php?' + \
'action=query&meta=globaluserinfo' + \
'&format=json&formatversion=2' + \
'&guiuser={}'.format(user)
client = tornado.httpclient.AsyncHTTPClient()
resp = yield client.fetch(url)
parsed = json.loads(resp.body.decode('utf-8'))
if 'missing' in parsed['query']['globaluserinfo']:
return None
return parsed['query']['globaluserinfo']['id']
# These do not change, so let's cache them in memory
cached_uids = {}
@gen.coroutine
def path_for_url_segment(url):
"""
Takes a URL segment and returns a full filesystem path
Example:
input: YuviPanda/Something.ipynb
output: 43/public/Something.ipynb
"""
splits = url.split('/')
username = splits[0]
path = '/'.join(splits[1:])
if username in cached_uids:
uid = cached_uids[username]
else:
uid = yield uid_for_user(username)
if uid is None:
raise tornado.web.HTTPError(404)
cached_uids[username] = uid
return os.path.join(BASE_PATH, str(uid), 'public', path)
| import tornado
from tornado import gen
import json
import os
BASE_PATH = '.'
base_url = '/paws/public/'
@gen.coroutine
def uid_for_user(user):
url = 'https://meta.wikimedia.org/w/api.php?' + \
'action=query&meta=globaluserinfo' + \
'&format=json&formatversion=2' + \
'&guiuser={}'.format(user)
client = tornado.httpclient.AsyncHTTPClient()
resp = yield client.fetch(url)
parsed = json.loads(resp.body.decode('utf-8'))
if 'missing' in parsed['query']['globaluserinfo']:
return None
return parsed['query']['globaluserinfo']['id']
cached_uids = {}
@gen.coroutine
def path_for_url_segment(url):
"""
Takes a URL segment and returns a full filesystem path
Example:
input: YuviPanda/Something.ipynb
output: 43/public/Something.ipynb
"""
splits = url.split('/')
username = splits[0]
path = '/'.join(splits[1:])
if username in cached_uids:
uid = cached_uids[username]
else:
uid = yield uid_for_user(username)
if uid is None:
raise tornado.web.HTTPError(404)
cached_uids[username] = uid
return os.path.join(BASE_PATH, str(uid), 'public', path)
|
Add region parameter to geocoding by query function | (function () {
angular
.module("ng-geocoder")
.factory("ngGeocoderService", ngGeocoderService);
ngGeocoderService.$inject = ["$q"];
function ngGeocoderService ($q) {
var geocoder = new google.maps.Geocoder();
var service = {
"geocodeById": geocodeById,
"geocodeByQuery": geocodeByQuery
}
return service;
function handleReply (defer, results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return defer.resolve(results);
} else if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
return defer.resolve([]);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
return defer.reject("Over query limit");
} else if (status === google.maps.GeocoderStatus.REQUEST_DENIED) {
return defer.reject("Request denied");
}
return defer.reject("Unknown error");
}
function geocodeById (placeId) {
return geocode({ "placeId": placeId });
}
function geocodeByQuery (query, region) {
return geocode({ "address": query, "region": region });
}
function geocode (options) {
var defer = $q.defer();
geocoder.geocode(options, function (results, status) {
handleReply(defer, results, status);
});
return defer.promise;
}
}
})();
| (function () {
angular
.module("ng-geocoder")
.factory("ngGeocoderService", ngGeocoderService);
ngGeocoderService.$inject = ["$q"];
function ngGeocoderService ($q) {
var geocoder = new google.maps.Geocoder();
var service = {
"geocodeById": geocodeById,
"geocodeByQuery": geocodeByQuery
}
return service;
function handleReply (defer, results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return defer.resolve(results);
} else if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
return defer.resolve([]);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
return defer.reject("Over query limit");
} else if (status === google.maps.GeocoderStatus.REQUEST_DENIED) {
return defer.reject("Request denied");
}
return defer.reject("Unknown error");
}
function geocodeById (placeId) {
return geocode({ "placeId": placeId });
}
function geocodeByQuery (query) {
return geocode({ "address": query });
}
function geocode (options) {
var defer = $q.defer();
geocoder.geocode(options, function (results, status) {
handleReply(defer, results, status);
});
return defer.promise;
}
}
})();
|
Fix getting request body for non-form data; now uses function that doesn't require a php.ini setting | <?php
namespace Raygun4php
{
class RaygunRequestMessage
{
public $hostName;
public $url;
public $httpMethod;
public $ipAddress;
//
public $queryString;
public $headers;
public $data;
public $form;
public $rawData;
public function __construct()
{
$this->hostName = $_SERVER['HTTP_HOST'];
$this->httpMethod = $_SERVER['REQUEST_METHOD'];
$this->url = $_SERVER['REQUEST_URI'];
$this->ipAddress = $_SERVER['REMOTE_ADDR'];
parse_str($_SERVER['QUERY_STRING'], $this->queryString);
if (empty($this->queryString))
{
$this->queryString = null;
}
$this->headers = getallheaders();
$this->data = $_SERVER;
$this->form = $_POST;
if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['CONTENT_TYPE'] != 'application/x-www-form-urlencoded' &&
$_SERVER['CONTENT_TYPE'] != 'multipart/form-data' &&
$_SERVER['CONTENT_TYPE'] != 'text/html')
{
$this->rawData = file_get_contents('php://input');
}
}
}
} | <?php
namespace Raygun4php
{
class RaygunRequestMessage
{
public $hostName;
public $url;
public $httpMethod;
public $ipAddress;
//
public $queryString;
public $headers;
public $data;
public $form;
public $rawData;
public function __construct()
{
$this->hostName = $_SERVER['HTTP_HOST'];
$this->httpMethod = $_SERVER['REQUEST_METHOD'];
$this->url = $_SERVER['REQUEST_URI'];
$this->ipAddress = $_SERVER['REMOTE_ADDR'];
parse_str($_SERVER['QUERY_STRING'], $this->queryString);
if (empty($this->queryString))
{
$this->queryString = null;
}
$this->headers = getallheaders();
$this->data = $_SERVER;
$this->form = $_POST;
if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['CONTENT_TYPE'] != 'application/x-www-form-urlencoded' &&
$_SERVER['CONTENT_TYPE'] != 'text/html')
{
$this->rawData = http_get_request_body();
}
}
}
} |
Use the pillow master branch directly. | # -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\n' %
version)
sys.stderr.flush()
sys.exit(1)
import os
from setuptools import setup
readme = os.path.join(os.path.dirname(__file__), 'README.md')
setup(
name='colorific',
version='0.2.0',
description='Automatic color palette detection',
long_description=open(readme).read(),
author='Lars Yencken',
author_email='[email protected]',
url='http://github.com/99designs/colorific',
py_modules=['colorific'],
install_requires=[
'Pillow==1.7.8',
'colormath>=1.0.8',
'numpy>=1.6.1',
],
dependency_links=[
'http://github.com/python-imaging/Pillow/tarball/master#egg=Pillow-1.7.8',
],
license='ISC',
entry_points={
'console_scripts': [
'colorific = colorific:main',
],
},
)
| # -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\n' %\
version)
sys.stderr.flush()
sys.exit(1)
import os
from setuptools import setup
readme = os.path.join(os.path.dirname(__file__), 'README.md')
setup(
name='colorific',
version='0.2.0',
description='Automatic color palette detection',
long_description=open(readme).read(),
author='Lars Yencken',
author_email='[email protected]',
url='http://github.com/99designs/colorific',
py_modules=['colorific'],
install_requires=[
'Pillow==1.7.8',
'colormath>=1.0.8',
'numpy>=1.6.1',
],
dependency_links=[
'http://github.com/larsyencken/Pillow/tarball/master#egg=Pillow-1.7.8',
],
license='ISC',
entry_points={
'console_scripts': [
'colorific = colorific:main',
],
},
)
|
Update to use inheritance for GameObject | from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from Game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode', None)
if textonly:
return build_response(
html_status=200,
response_data=GameObject.game_modes,
response_mimetype="application/json"
)
digits = GameObject.digits_used
guesses = GameObject.guesses_allowed
game_modes = GameObject.game_modes
# game_modes = [mode for mode in GameObject.digits_used]
return_list = []
for mode in game_modes:
return_list.append(
{
"mode": mode,
"digits": digits[mode],
"guesses": guesses[mode]
}
)
return build_response(
html_status=200,
response_data=return_list,
response_mimetype="application/json"
)
| from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode', None)
if textonly:
return build_response(
html_status=200,
response_data=GameObject.game_modes,
response_mimetype="application/json"
)
digits = GameObject.digits_used
guesses = GameObject.guesses_allowed
game_modes = GameObject.game_modes
# game_modes = [mode for mode in GameObject.digits_used]
return_list = []
for mode in game_modes:
return_list.append(
{
"mode": mode,
"digits": digits[mode],
"guesses": guesses[mode]
}
)
return build_response(
html_status=200,
response_data=return_list,
response_mimetype="application/json"
)
|
Add a test for a numeric reference | <?php
namespace adrianclay\git;
use adrianclay\git\References\ReferencesArray;
use PHPUnit\Framework\TestCase;
class RevisionResolverTest extends TestCase
{
private $sha = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";
public function testFullSHA()
{
$this->assertEqualSHA( $this->getResolver( [], $this->sha ) );
}
public function testHEAD()
{
$this->assertEqualSHA( $this->getResolver( [ References::HEAD => new SHA( $this->sha ) ], References::HEAD ) );
}
public function testMain()
{
$this->assertEqualSHA( $this->getResolver( [ 'refs/heads/main' => new SHA( $this->sha ) ], 'main' ) );
}
public function testNumericRefIsDereferenced()
{
$this->assertEqualSHA( $this->getResolver( [ 'refs/heads/1111' => new SHA( $this->sha ) ], '1111' ) );
}
public function testOriginMain()
{
$references = [ 'refs/remotes/origin/main' => new SHA( $this->sha ) ];
$this->assertEqualSHA( $this->getResolver( $references, 'origin/main' ) );
}
/**
* @param SHAReference[] $references
* @param string $revision
* @return RevisionResolver
*/
private function getResolver( array $references, $revision )
{
return new RevisionResolver( new ReferencesArray( $references ), $revision );
}
/**
* @param RevisionResolver $revisionResolver
*/
private function assertEqualSHA( RevisionResolver $revisionResolver )
{
$this->assertEquals( $this->sha, $revisionResolver->getSHA() );
}
} | <?php
namespace adrianclay\git;
use adrianclay\git\References\ReferencesArray;
use PHPUnit\Framework\TestCase;
class RevisionResolverTest extends TestCase
{
private $sha = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";
public function testFullSHA()
{
$this->assertEqualSHA( $this->getResolver( [], $this->sha ) );
}
public function testHEAD()
{
$this->assertEqualSHA( $this->getResolver( [ References::HEAD => new SHA( $this->sha ) ], References::HEAD ) );
}
public function testMain()
{
$this->assertEqualSHA( $this->getResolver( [ 'refs/heads/main' => new SHA( $this->sha ) ], 'main' ) );
}
public function testOriginMain()
{
$references = [ 'refs/remotes/origin/main' => new SHA( $this->sha ) ];
$this->assertEqualSHA( $this->getResolver( $references, 'origin/main' ) );
}
/**
* @param SHAReference[] $references
* @param string $revision
* @return RevisionResolver
*/
private function getResolver( array $references, $revision )
{
return new RevisionResolver( new ReferencesArray( $references ), $revision );
}
/**
* @param RevisionResolver $revisionResolver
*/
private function assertEqualSHA( RevisionResolver $revisionResolver )
{
$this->assertEquals( $this->sha, $revisionResolver->getSHA() );
}
} |
Move to the correct catch | import DataLoader from 'dataloader';
import cache from '../cache';
import timer from '../timer';
import { throttled } from '../throttle';
import { error, verbose } from '../loggers';
export default api => {
return new DataLoader(keys => Promise.all(keys.map(key => {
const clock = timer(key);
clock.start();
return new Promise((resolve, reject) => {
cache
.get(key)
.then(data => {
resolve(data);
verbose(`Cached: ${key}`);
clock.end();
throttled(key, () => {
api(key)
.then(({ body }) => {
verbose(`Refreshing: ${key}`);
cache.set(key, body);
})
.catch(err => {
if (err.statusCode === 404) { // Unpublished
cache.delete(key);
}
});
});
}, () => {
api(key)
.then(({ body }) => {
resolve(body);
verbose(`Requested (Uncached): ${key}`);
clock.end();
cache.set(key, body);
})
.catch(err => {
reject(err);
error(key, err);
});
});
});
})), {
batch: false,
cache: true,
});
};
| import DataLoader from 'dataloader';
import cache from '../cache';
import timer from '../timer';
import { throttled } from '../throttle';
import { error, verbose } from '../loggers';
export default api => {
return new DataLoader(keys => Promise.all(keys.map(key => {
const clock = timer(key);
clock.start();
return new Promise((resolve, reject) => {
cache
.get(key)
.then(data => {
resolve(data);
verbose(`Cached: ${key}`);
clock.end();
throttled(key, () => {
api(key)
.then(({ body }) => {
verbose(`Refreshing: ${key}`);
cache.set(key, body);
});
});
}, () => {
api(key)
.then(({ body }) => {
resolve(body);
verbose(`Requested (Uncached): ${key}`);
clock.end();
cache.set(key, body);
})
.catch(err => {
reject(err);
error(key, err);
// If the error is a 404 then the object
// may exist in cache and may have been unpublished
if (err.statusCode === 404) {
cache.delete(key);
}
});
});
});
})), {
batch: false,
cache: true,
});
};
|
Fix issue in flat list | /* @flow */
import React from 'react'
import {TouchableOpacity, View, FlatList} from 'react-native'
export default class NodeView extends React.PureComponent {
componentWillMount = () => {
let rootChildren = this.props.getChildren(this.props.node)
if (rootChildren) {
rootChildren = rootChildren.map((child, index) => {
return this.props.generateIds(rootChildren[index])
})
}
this.setState({data: rootChildren})
}
onNodePressed = (node: any) => {
if (this.state.data) {
const newState = rootChildren = this.state.data.map((child, index) => {
return this.props.searchTree(this.state.data[index], node)
})
this.setState({data: newState})
}
this.props.onNodePressed(node)
}
render() {
const {getChildren, node, nodeStyle, onLayout, onNodePressed, renderNode, renderChildrenNode} = this.props
const children = getChildren(node)
return (
<View onLayout={onLayout}>
<TouchableOpacity onPress={() => this.onNodePressed(node)}>
{renderNode()}
</TouchableOpacity>
{node.opened && this.state.data
? <FlatList
data={this.state.data}
renderItem={({item}) => renderChildrenNode(item)}
keyExtractor={(item) => item.id}/> : null}
</View>
)
}
}
| /* @flow */
import React from 'react'
import {TouchableOpacity, View, FlatList} from 'react-native'
export default class NodeView extends React.PureComponent {
componentWillMount = () => {
let rootChildren = this.props.getChildren(this.props.node)
if (rootChildren) {
rootChildren = rootChildren.map((child, index) => {
return this.props.generateIds(rootChildren[index])
})
}
this.setState({data: rootChildren})
}
onNodePressed = (node: any) => {
const newState = rootChildren = this.state.data.map((child, index) => {
return this.props.searchTree(this.state.data[index], node)
})
this.setState({data: newState})
this.props.onNodePressed(node)
}
render() {
const {getChildren, node, nodeStyle, onLayout, onNodePressed, renderNode, renderChildrenNode} = this.props
const children = getChildren(node)
return (
<View onLayout={onLayout}>
<TouchableOpacity onPress={() => onNodePressed(node)}>
{renderNode()}
</TouchableOpacity>
{node.opened && this.state.data
? <FlatList
data={this.state.data}
renderItem={({item}) => renderChildrenNode(item)}
keyExtractor={(item) => item.id}/> : null}
</View>
)
}
}
|
Add method to retrieve the next tick mark | package io.sigpipe.sing.dataset;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
import io.sigpipe.sing.dataset.feature.Feature;
public class Quantizer {
private NavigableSet<Feature> ticks = new TreeSet<>();
public Quantizer(Object start, Object end, Object step) {
this(
Feature.fromPrimitiveType(start),
Feature.fromPrimitiveType(end),
Feature.fromPrimitiveType(step));
}
public Quantizer(Feature start, Feature end, Feature step) {
if (start.sameType(end) == false || start.sameType(step) == false) {
throw new IllegalArgumentException(
"All feature types must be the same");
}
this.start = start;
this.end = end;
Feature tick = new Feature(start);
while (tick.less(end)) {
insertTick(tick);
tick = tick.add(step);
}
}
public void insertTick(Feature tick) {
ticks.add(tick);
}
public void removeTick(Feature tick) {
ticks.remove(tick);
}
public Feature quantize(Feature feature) {
Feature result = ticks.floor(feature);
if (result == null) {
return ticks.first();
}
return result;
}
public Feature nextTick(Feature feature) {
Feature result = ticks.higher(feature);
//TODO this will return null when feature > highest tick, but should
//actually return 'end'
return result;
}
@Override
public String toString() {
String output = "";
for (Feature f : ticks) {
output += f.getString() + System.lineSeparator();
}
return output;
}
}
| package io.sigpipe.sing.dataset;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
import io.sigpipe.sing.dataset.feature.Feature;
public class Quantizer {
private NavigableSet<Feature> ticks = new TreeSet<>();
public Quantizer(Object start, Object end, Object step) {
this(
Feature.fromPrimitiveType(start),
Feature.fromPrimitiveType(end),
Feature.fromPrimitiveType(step));
}
public Quantizer(Feature start, Feature end, Feature step) {
if (start.sameType(end) == false || start.sameType(step) == false) {
throw new IllegalArgumentException(
"All feature types must be the same");
}
this.start = start;
this.end = end;
Feature tick = new Feature(start);
while (tick.less(end)) {
insertTick(tick);
tick = tick.add(step);
}
}
public void insertTick(Feature tick) {
ticks.add(tick);
}
public void removeTick(Feature tick) {
ticks.remove(tick);
}
public Feature quantize(Feature feature) {
Feature result = ticks.floor(feature);
if (result == null) {
return ticks.first();
}
return result;
}
@Override
public String toString() {
String output = "";
for (Feature f : ticks) {
output += f.getString() + System.lineSeparator();
}
return output;
}
}
|
Add primitive server option for easier debugging | import optparse, os, pickle
config = {'charity':False,
'propagate_factor':2,
'accept_latency':2000}
def setup():
parser = optparse.OptionParser()
parser.add_option('-c',
'--charity',
dest='charity',
default=None,
action="store_true",
help='Sets whether you accept rewardless bounties')
parser.add_option('-l',
'--latency',
dest='accept_latency',
default=None,
help='Maximum acceptable latency from a server')
parser.add_option('-f',
'--propagation-factor',
dest='propagate_factor',
default=None,
help='Minimum funds:reward ratio you\'ll propagate bounties at')
parser.add_option('-S',
'--server',
dest='server',
default=None,
action="store_true",
help='Sets whether you operate as a server or client (Default: client)')
(options, args) = parser.parse_args()
print "options parsed"
overrides = options.__dict__
if os.path.exists("data" + os.sep + "settings.conf"):
config.update(pickle.load(open("settings.conf","r")))
print overrides
print config
else:
if not os.path.exists("data" + os.sep + "settings.conf"):
os.mkdir("data")
pickle.dump(config,open("data" + os.sep + "settings.conf","w"))
kill = []
for key in overrides:
if overrides.get(key) is None:
kill += [key]
for key in kill:
overrides.pop(key)
config.update(overrides)
| import optparse, os, pickle
config = {'charity':False,
'propagate_factor':2,
'accept_latency':2000}
def setup():
parser = optparse.OptionParser()
parser.add_option('-c',
'--charity',
dest='charity',
default=None,
action="store_true",
help='Sets whether you accept rewardless bounties')
parser.add_option('-l',
'--latency',
dest='accept_latency',
default=None,
help='Maximum acceptable latency from a server')
parser.add_option('-f',
'--propagation-factor',
dest='propagate_factor',
default=None,
help='Minimum funds:reward ratio you\'ll propagate bounties at')
(options, args) = parser.parse_args()
print "options parsed"
overrides = options.__dict__
if os.path.exists("data" + os.sep + "settings.conf"):
config.update(pickle.load(open("settings.conf","r")))
print overrides
print config
else:
if not os.path.exists("data" + os.sep + "settings.conf"):
os.mkdir("data")
pickle.dump(config,open("data" + os.sep + "settings.conf","w"))
kill = []
for key in overrides:
if overrides.get(key) is None:
kill += [key]
for key in kill:
overrides.pop(key)
config.update(overrides)
|
Put back changes in observer after unsuccessful commit. | const expect = require('chai').expect;
import { TopicObserver } from "../topic-observer";
describe('topic observer', () => {
const observer = new TopicObserver();
const fn1 = () => {};
it('should observe all', function() {
observer.observe(fn1);
expect(observer.observers['__all__'].length).to.equal(1)
});
it('should remove all', function() {
observer.remove(fn1);
expect(observer.observers['__all__'].length).to.equal(0);
});
it('should receive all', function () {
let subscriberHasBeenCalled = false;
const fn2 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn2);
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.remove(fn2);
});
const fn3 = () => {};
it('should observe topic', function() {
observer.observe(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(1)
});
it('should remove topic', function() {
observer.remove(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(0);
});
it('should receive topic', function () {
let subscriberHasBeenCalled = false;
const fn4 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn4, 'topic');
observer.broadcast(true, 'topic');
expect(subscriberHasBeenCalled).to.equal(true);
observer.observe(fn4, 'topic');
});
});
| const expect = require('chai').expect;
import { TopicObserver } from "../topic-observer";
describe('topic observer', () => {
const observer = new TopicObserver();
const fn1 = () => {};
it('should observe all', function() {
observer.observe(fn1);
expect(observer.observers['__all__'].length).to.equal(1)
});
it('should remove all', function() {
observer.remove(fn1);
expect(observer.observers['__all__'].length).to.equal(0);
});
it('should receive all', function () {
let subscriberHasBeenCalled = false;
const fn2 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn2);
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.remove(fn2);
});
const fn3 = () => {};
it('should observe topic', function() {
observer.observe(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(1)
});
it('should remove topic', function() {
observer.remove(fn3, 'topic');
expect(observer.observers['topic'].length).to.equal(0);
});
it('should receive topic', function () {
let subscriberHasBeenCalled = false;
const fn4 = (data) => subscriberHasBeenCalled = data;
observer.observe(fn4, 'topic');
observer.broadcast(true);
expect(subscriberHasBeenCalled).to.equal(true);
observer.observe(fn4, 'topic');
});
});
|
Change the inherited classes of hoomd.filter.CustomFilter
CustomFilter inherits now from Hashable and Callable | """Contains a class for custom particle filters in Python."""
from abc import ABC, abstractmethod
from collections.abc import Hashable, Callable
class CustomFilter(Hashable, Callable):
"""Abstract base class for custom particle filters.
The class allows the definition of particle filters in Python (see
`hoomd.filter.ParticleFilter`.
"""
@abstractmethod
def __call__(self, state):
"""Return the local particle tags that match the filter.
This can either return the tags that are local to an MPI rank or the
tags of all particles that match in the entire state. Tag numbers in a
`hoomd.Snapshot` object are just their index.
Note:
The exact requirements for custom filters is that the set union of
the returned arrays from each MPI rank be all particles that match
the filter. For general use, it is recommended, however, that each
rank only return the tags for particles that are in the local MPI
rank (excluding ghost particles).
Args:
state (`hoomd.State`):
The simulation state to return the filtered tags from.
Returns:
(*N*,) `numpy.ndarray` of `numpy.uint64`:
An array of MPI local tags that match the filter.
"""
pass
@abstractmethod
def __hash__(self):
"""A hashed value to represent this instance.
This is necessary to allow for proper caching of filter tags internally
in HOOMD-blue.
"""
pass
@abstractmethod
def __eq__(self, other):
"""Whether this filter and another filter are equal.
This is necessary to allow for proper caching of filter tags internally
in HOOMD-blue.
"""
pass
| """Contains a class for custom particle filters in Python."""
from abc import ABCMeta, abstractmethod
class CustomFilter(metaclass=ABCMeta):
"""Abstract base class for custom particle filters.
The class allows the definition of particle filters in Python (see
`hoomd.filter.ParticleFilter`.
"""
@abstractmethod
def __call__(self, state):
"""Return the local particle tags that match the filter.
This can either return the tags that are local to an MPI rank or the
tags of all particles that match in the entire state. Tag numbers in a
`hoomd.Snapshot` object are just their index.
Note:
The exact requirements for custom filters is that the set union of
the returned arrays from each MPI rank be all particles that match
the filter. For general use, it is recommended, however, that each
rank only return the tags for particles that are in the local MPI
rank (excluding ghost particles).
Args:
state (`hoomd.State`):
The simulation state to return the filtered tags from.
Returns:
(*N*,) `numpy.ndarray` of `numpy.uint64`:
An array of MPI local tags that match the filter.
"""
pass
@abstractmethod
def __hash__(self):
"""A hashed value to represent this instance.
This is necessary to allow for proper caching of filter tags internally
in HOOMD-blue.
"""
pass
@abstractmethod
def __eq__(self, other):
"""Whether this filter and another filter are equal.
This is necessary to allow for proper caching of filter tags internally
in HOOMD-blue.
"""
pass
|
Change some name variables improving readability
The calling `diff.toString()` was made only for `blessed`
compatibility. It seems that it doesn't deal too much with real
integers. | var util = require('util');
var hits = require('./hits');
var moment = require('moment');
var duration = require('moment-duration-format');
var _ = require('lodash');
var leave = {
collectHits: function (hits, matchDay) {
var filteredHits = [];
hits.forEach(function (hit){
var isSame = moment(hit.input).isSame(matchDay, 'day');
if (isSame) {
filteredHits.push(hit);
}
});
return filteredHits;
},
parseHits: function (hits) {
var flatHits = [
['Input', 'Output', 'Duration', 'Interval']
];
hits.forEach(function (hit){
var input = moment(hit.input),
output = moment(hit.output);
var outputReferer = output.isValid() ? output : moment();
var diff = outputReferer.diff(input, 'minutes');
var interval = '-';
var component = [
input.format('HH:mm'),
output.isValid() ? output.format('HH:mm') : '-',
diff.toString(),
interval
];
flatHits.push(component);
});
return flatHits;
},
/**
* @todo Add option to avoid headers
*/
sumHitsDuration: function (flatHits) {
var durations = _.pluck(flatHits, 2);
return _.sum(durations);
},
formatDuration: function (minutes) {
return moment.duration(minutes, 'minutes')
.format('HH:mm', { trim: false });
}
};
module.exports = leave; | var util = require('util');
var hits = require('./hits');
var moment = require('moment');
var duration = require('moment-duration-format');
var _ = require('lodash');
var leave = {
collectHits: function (hits, matchDay) {
var filteredHits = [];
hits.forEach(function (hit){
var isSame = moment(hit.input).isSame(matchDay, 'day');
if (isSame) {
filteredHits.push(hit);
}
});
return filteredHits;
},
parseHits: function (hits) {
var flatHits = [
['Input', 'Output', 'Duration', 'Interval']
];
hits.forEach(function (hit){
var input = moment(hit.input),
output = moment(hit.output);
var outputReferer = output.isValid() ? output : moment();
var duration = outputReferer.diff(input, 'minutes');
var interval = '-';
var component = [
input.format('HH:mm'),
output.isValid() ? output.format('HH:mm') : '-',
duration,
interval
];
flatHits.push(component);
});
return flatHits;
},
/**
* @todo Add option to avoid headers
*/
sumHitsDuration: function (flatHits) {
var durations = _.pluck(flatHits, 2);
return _.sum(durations);
},
formatDuration: function (minutes) {
return moment.duration(minutes, 'minutes')
.format('HH:mm', { trim: false });
}
};
module.exports = leave; |
Add path to theme attributes | <?php namespace Pingpong\Themes;
use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;
class Finder {
/**
* The symfony finder instance.
*
* @var SymfonyFinder
*/
protected $finder;
/**
* The constructor.
*
* @param $finder SymfonyFinder
*/
public function __construct(SymfonyFinder $finder = null)
{
$this->finder = $finder ?: new SymfonyFinder;
}
/**
* Find the specified theme by searching a 'theme.json' file as identifier.
*
* @param string $path
* @param string $filename
* @return array
*/
public function find($path, $filename = 'theme.json')
{
$themes = [];
if(is_dir($path))
{
$found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();
foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
}
return $themes;
}
/**
* Get theme info from json file.
*
* @param SplFileInfo $file
* @return array
*/
protected function getInfo($file)
{
$attributes = Json::make($path = $file->getRealPath())->toArray();
$attributes['path'] = dirname($path);
return $attributes;
}
} | <?php namespace Pingpong\Themes;
use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;
class Finder {
/**
* The symfony finder instance.
*
* @var SymfonyFinder
*/
protected $finder;
/**
* The constructor.
*
* @param $finder SymfonyFinder
*/
public function __construct(SymfonyFinder $finder = null)
{
$this->finder = $finder ?: new SymfonyFinder;
}
/**
* Find the specified theme by searching a 'theme.json' file as identifier.
*
* @param string $path
* @param string $filename
* @return array
*/
public function find($path, $filename = 'theme.json')
{
$themes = [];
if(is_dir($path))
{
$found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();
foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
}
return $themes;
}
/**
* Get theme info from json file.
*
* @param SplFileInfo $file
* @return array
*/
protected function getInfo($file)
{
return Json::make($file->getRealPath())->toArray();
}
} |
Change full coverage report to short text summary | module.exports = function karma(config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['mocha', 'chai', 'sinon'],
files: ['tests.webpack.js'],
plugins: [
'karma-phantomjs-launcher',
'karma-mocha',
'karma-chai',
'karma-sinon',
'karma-sourcemap-loader',
'karma-webpack',
'karma-coverage',
'karma-mocha-reporter'
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: ['mocha', 'coverage'],
webpack: {
devtool: 'inline-source-map',
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /(__tests__|node_modules)\//,
loader: 'isparta-instrumenter'
}
],
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules|lib)\//
}
]
},
externals: {
cheerio: 'window',
'react/addons': true,
'react/lib/ReactContext': true,
'react/lib/ExecutionEnvironment': true
}
},
webpackServer: {
noInfo: true
},
coverageReporter: {
reporters: [
{
type: 'lcovonly',
dir: 'coverage/',
subdir: '.',
file: 'lcov.info'
},
{
type: 'text-summary'
}
]
}
});
};
| module.exports = function karma(config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['mocha', 'chai', 'sinon'],
files: ['tests.webpack.js'],
plugins: [
'karma-phantomjs-launcher',
'karma-mocha',
'karma-chai',
'karma-sinon',
'karma-sourcemap-loader',
'karma-webpack',
'karma-coverage',
'karma-mocha-reporter'
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: ['mocha', 'coverage'],
webpack: {
devtool: 'inline-source-map',
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /(__tests__|node_modules)\//,
loader: 'isparta-instrumenter'
}
],
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules|lib)\//
}
]
},
externals: {
cheerio: 'window',
'react/addons': true,
'react/lib/ReactContext': true,
'react/lib/ExecutionEnvironment': true
}
},
webpackServer: {
noInfo: true
},
coverageReporter: {
reporters: [
{
type: 'lcovonly',
dir: 'coverage/',
subdir: '.',
file: 'lcov.info'
},
{
type: 'text'
}
]
}
});
};
|
Fix chess logic in analysis | import { askWorker } from '../../utils';
export default function chessLogic(ctrl) {
const worker = new Worker('vendor/scalachessjs.js');
worker.addEventListener('message', function(msg) {
const payload = msg.data.payload;
switch (msg.data.topic) {
case 'dests':
ctrl.addDests(payload.dests, payload.path);
break;
case 'move':
if (payload.path) {
var sit = payload.situation;
var step = {
ply: sit.ply,
dests: sit.dests,
check: sit.check,
fen: sit.fen,
uci: sit.uciMoves[0],
san: sit.pgnMoves[0]
};
ctrl.addStep(step, payload.path);
}
break;
}
});
return {
sendStepRequest(req) {
worker.postMessage({ topic: 'move', payload: req });
},
sendDestsRequest(req) {
worker.postMessage({ topic: 'dests', payload: req });
},
getSanMoveFromUci(req, callback) {
askWorker(worker, { topic: 'move', payload: req }, callback);
},
onunload() {
if (worker) worker.terminate();
}
};
}
| import { askWorker } from '../../utils';
export default function chessLogic(ctrl) {
const worker = new Worker('vendor/scalachessjs.js');
worker.addEventListener('message', function(msg) {
const payload = msg.data.payload;
switch (msg.data.topic) {
case 'dests':
ctrl.addDests(payload.dests, payload.path);
break;
case 'move':
if (payload.path) {
var sit = payload.situation;
var step = {
ply: sit.ply,
dests: sit.dests,
check: sit.check,
fen: sit.fen,
uci: sit.lastMove.uci,
san: sit.pgnMoves[0]
};
ctrl.addStep(step, payload.path);
}
break;
}
});
return {
sendStepRequest(req) {
worker.postMessage({ topic: 'move', payload: req });
},
sendDestsRequest(req) {
worker.postMessage({ topic: 'dests', payload: req });
},
getSanMoveFromUci(req, callback) {
askWorker(worker, { topic: 'move', payload: req }, callback);
},
onunload() {
if (worker) worker.terminate();
}
};
}
|
Remove dependency of app in generated stubs
ngMockE2E is currently the only Angular module which is needed for ABE generated stubs | exports.generateDefaultStub = function (data) {
angular
.module(data['stub-options']['module_name'], [
'ngMockE2E'
])
.run(function ($httpBackend) {
var createStub = function (method, example, $httpBackend) {
var httpMethod = method.toUpperCase(),
url = new RegExp(example.request.url + '$'),
res = example.response;
$httpBackend
['when' + httpMethod](url)
.respond(function (method, url) {
return [res.status, res.body];
});
},
methodData,
method;
delete data['stub-options'];
for (methodData in data) {
var httpMethod = data[methodData].method,
examples = data[methodData].examples;
for (method in examples) {
createStub(
httpMethod,
examples[method],
$httpBackend
);
}
}
});
};
| exports.generateDefaultStub = function (data) {
angular
.module(data['stub-options']['module_name'], [
'ngMockE2E',
'app'
])
.run(function ($httpBackend) {
var createStub = function (method, example, $httpBackend) {
var httpMethod = method.toUpperCase(),
url = new RegExp(example.request.url + '$'),
res = example.response;
$httpBackend
['when' + httpMethod](url)
.respond(function (method, url) {
return [res.status, res.body];
});
},
methodData,
method;
delete data['stub-options'];
for (methodData in data) {
var httpMethod = data[methodData].method,
examples = data[methodData].examples;
for (method in examples) {
createStub(
httpMethod,
examples[method],
$httpBackend
);
}
}
});
};
|
Improve soft-deleting of past events | <?php
namespace App\Console\Commands;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class MarkPastEventsDeleted extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'harvester:mark-past-events-deleted';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Finds any events and performances that are in the past and soft-deletes them. This is intended to be run at 12:01AM.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
* @throws Exception
*/
public function handle()
{
$now = new Carbon();
$endOfYesterday = new Carbon('midnight today');
$endOfYesterday->subSecond();
$eventCounts = DB::table('events')->where('occurs_at', '<=', $endOfYesterday)->whereNull('deleted_at')->update(['deleted_at' => $now]);
$this->info($eventCounts . ' Events were soft-deleted.');
$performancesCounts = DB::table('performances')->where('occurs_at', '<=', $endOfYesterday)->whereNull('deleted_at')->update(['deleted_at' => $now]);
$this->info($performancesCounts . ' Performances were soft-deleted.');
}
}
| <?php
namespace App\Console\Commands;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class MarkPastEventsDeleted extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'harvester:mark-past-events-deleted';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Finds any events and performances that are in the past and soft-deletes them. This is intended to be run at 12:01AM.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
* @throws Exception
*/
public function handle()
{
$now = new Carbon();
$eventCounts = DB::table('events')->where('occurs_at', '<', $now)->whereNull('deleted_at')->update(['deleted_at' => $now]);
$this->info($eventCounts . ' Events were soft-deleted.');
$performancesCounts = DB::table('performances')->where('occurs_at', '<', $now)->whereNull('deleted_at')->update(['deleted_at' => $now]);
$this->info($performancesCounts . ' Performances were soft-deleted.');
}
}
|
Add form success message + cast amount profile to integer | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Profile Faker / Form / Processing
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class GenerateProfileFormProcess extends Form
{
/** @var string */
private $sProfileType;
/**
* @param string $sProfileType The profile type to generate.
*
* @throws Framework\Mvc\Request\WrongRequestMethodException
*/
public function __construct($sProfileType)
{
$this->sProfileType = $sProfileType;
$this->generate();
\PFBC\Form::setSuccess(
'form_generate_profiles',
nt('%n% profile has been generated.', '%n% profiles have been generated.', $this->httpRequest->post('amount', 'int'))
);
}
private function generate()
{
$oFakerFactory = new FakerFactory(
$this->httpRequest->post('amount', 'int'),
$this->httpRequest->post('locale')
);
switch ($this->sProfileType) {
case ProfileType::MEMBER:
$oFakerFactory->generateMembers();
break;
case ProfileType::AFFILIATE:
$oFakerFactory->generateAffiliates();
break;
case ProfileType::SUBSCRIBER:
$oFakerFactory->generateSubscribers();
break;
}
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Profile Faker / Form / Processing
*/
namespace PH7;
defined('PH7') or exit('Restricted access');
class GenerateProfileFormProcess extends Form
{
/** @var string */
private $sProfileType;
/**
* @param string $sProfileType The profile type to generate.
*/
public function __construct($sProfileType)
{
$this->sProfileType = $sProfileType;
$this->generate();
}
private function generate()
{
$oFakerFactory = new FakerFactory(
$this->httpRequest->post('amount'),
$this->httpRequest->post('locale')
);
switch ($this->sProfileType) {
case ProfileType::MEMBER:
$oFakerFactory->generateMembers();
break;
case ProfileType::AFFILIATE:
$oFakerFactory->generateAffiliates();
break;
case ProfileType::SUBSCRIBER:
$oFakerFactory->generateSubscribers();
break;
}
}
}
|
Add re import for regex | from flask import request, flash, render_template
import re
import bcrypt
from app import app, helpers
@app.route('/create_user', methods=['GET', 'POST'])
def create_user():
if request.method == 'POST':
username = request.form.get('username', None).strip() # Aa09_.- allowed
password = request.form.get('password', None)
role = request.form.get('role', 'Guest')
if re.match(r'^[\w.-]+$', username) and password:
# Form was completed with valid input
matching_user = "SELECT user_pk FROM users WHERE username = %s;"
user_does_exist = helpers.duplicate_check(matching_user, [username])
if user_does_exist:
flash('Username already exists')
else:
salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), bytes(salt))
new_user = ("INSERT INTO users (username, password, salt, role_fk) "
"VALUES (%s, %s, %s, %s);")
helpers.db_change(new_user, [username, password, salt, role])
flash('Your account was created!')
else:
flash('Please enter a username and password.')
return render_template('create_user.html')
| from flask import request, flash, render_template
import bcrypt
from app import app, helpers
@app.route('/create_user', methods=['GET', 'POST'])
def create_user():
if request.method == 'POST':
username = request.form.get('username', None).strip() # Aa09_.- allowed
password = request.form.get('password', None)
role = request.form.get('role', 'Guest')
if re.match(r'^[\w.-]+$', username) and password:
# Form was completed with valid input
matching_user = "SELECT user_pk FROM users WHERE username = %s;"
user_does_exist = helpers.duplicate_check(matching_user, [username])
if user_does_exist:
flash('Username already exists')
else:
salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), bytes(salt))
new_user = ("INSERT INTO users (username, password, salt, role_fk) "
"VALUES (%s, %s, %s, %s);")
helpers.db_change(new_user, [username, password, salt, role])
flash('Your account was created!')
else:
flash('Please enter a username and password.')
return render_template('create_user.html')
|
Enhance exception handling in transformation pipeline | package fr.insee.pogues.transforms;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PipeLine {
private String output;
private List<Runnable> transforms = new ArrayList<>();
public PipeLine from(InputStream input) throws Exception {
try {
output = IOUtils.toString(input, Charset.forName("UTF-8"));
return this;
} catch (IOException e) {
throw e;
}
}
public PipeLine from(String input) {
this.output = input;
return this;
}
public PipeLine map(Transform<String, String> t, Map<String, Object> params) throws Exception {
transforms.add(() -> {
try {
output = t.apply(output, params);
} catch (Exception e) {
throw new RuntimeException(
String.format("Exception occured while executing mapping function: %s", e.getMessage())
);
}
});
return this;
}
public String transform() throws Exception {
for (Runnable t : transforms) {
try {
t.run();
} catch(Exception e){
throw e;
}
}
return output;
}
@FunctionalInterface
public interface Transform<I, O> {
O apply(I i, Map<String, Object> params) throws Exception;
}
}
| package fr.insee.pogues.transforms;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PipeLine {
private String output;
private List<Runnable> transforms = new ArrayList<>();
public PipeLine from(InputStream input) throws Exception {
try {
output = IOUtils.toString(input, Charset.forName("UTF-8"));
return this;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
public PipeLine from(String input) {
this.output = input;
return this;
}
public PipeLine map(Transform<String, String> t, Map<String, Object> params) {
transforms.add(() -> {
try {
output = t.apply(output, params);
} catch (Exception e) {
e.printStackTrace();
}
});
return this;
}
public String transform() {
for (Runnable t : transforms) {
t.run();
}
return output;
}
@FunctionalInterface
public interface Transform<I, O> {
O apply(I i, Map<String, Object> params) throws Exception;
}
}
|
Fix units on wallet info screen | 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
| 'use strict';
angular.module('copayApp.controllers').controller('walletInfoController',
function ($scope, $rootScope, $timeout, profileService, configService, lodash, coloredCoins, walletService) {
function initAssets(assets) {
if (!assets) {
this.assets = [];
return;
}
this.assets = lodash.values(assets)
.map(function(asset) {
return {
assetName: asset.metadata.assetName,
assetId: asset.assetId,
balanceStr: coloredCoins.formatAssetAmount(asset.amount, asset.asset, walletService.walletUnit)
};
})
.concat([{
assetName: 'Bitcoin',
assetId: 'bitcoin',
balanceStr: walletService.btcBalance
}])
.sort(function(a1, a2) {
return a1.assetName > a2.assetName;
});
}
var setAssets = initAssets.bind(this);
if (!coloredCoins.onGoingProcess) {
setAssets(coloredCoins.assets);
} else {
this.assets = null;
}
var disableAssetListener = $rootScope.$on('ColoredCoins/AssetsUpdated', function (event, assets) {
setAssets(assets);
$timeout(function() {
$rootScope.$digest();
});
});
$scope.$on('$destroy', function () {
disableAssetListener();
});
this.walletAsset = walletService.updateWalletAsset();
this.setWalletAsset = function(asset) {
walletService.setWalletAsset(asset);
};
});
|
Fix swiftmailer not using the correct transport | <?php
namespace Common\Mailer;
use PDOException;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Common\ModulesSettings;
class Configurator
{
/**
* @var ModulesSettings
*/
private $modulesSettings;
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ModulesSettings $modulesSettings, ContainerInterface $container)
{
$this->modulesSettings = $modulesSettings;
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event): void
{
$this->configureMail();
}
public function onConsoleCommand(ConsoleCommandEvent $event): void
{
$this->configureMail();
}
private function configureMail(): void
{
try {
$transport = TransportFactory::create(
(string) $this->modulesSettings->get('Core', 'mailer_type', 'sendmail'),
$this->modulesSettings->get('Core', 'smtp_server'),
(int) $this->modulesSettings->get('Core', 'smtp_port', 25),
$this->modulesSettings->get('Core', 'smtp_username'),
$this->modulesSettings->get('Core', 'smtp_password'),
$this->modulesSettings->get('Core', 'smtp_secure_layer')
);
$this->container->get('mailer')->__construct($transport);
$this->container->set(
'swiftmailer.transport',
$transport
);
} catch (PDOException $e) {
// we'll just use the mail transport thats pre-configured
}
}
}
| <?php
namespace Common\Mailer;
use PDOException;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Common\ModulesSettings;
class Configurator
{
/**
* @var ModulesSettings
*/
private $modulesSettings;
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ModulesSettings $modulesSettings, ContainerInterface $container)
{
$this->modulesSettings = $modulesSettings;
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event): void
{
$this->configureMail();
}
public function onConsoleCommand(ConsoleCommandEvent $event): void
{
$this->configureMail();
}
private function configureMail(): void
{
try {
$transport = TransportFactory::create(
(string) $this->modulesSettings->get('Core', 'mailer_type', 'sendmail'),
$this->modulesSettings->get('Core', 'smtp_server'),
(int) $this->modulesSettings->get('Core', 'smtp_port', 25),
$this->modulesSettings->get('Core', 'smtp_username'),
$this->modulesSettings->get('Core', 'smtp_password'),
$this->modulesSettings->get('Core', 'smtp_secure_layer')
);
$this->container->set(
'swiftmailer.transport',
$transport
);
} catch (PDOException $e) {
// we'll just use the mail transport thats pre-configured
}
}
}
|
Make _runQuery to fail if the query fails, but still hide the execution messages | from fabric.api import sudo, hide
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with hide('running', 'output'):
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres',
pty=False)
def grantRead(user, database):
"""
Grant read permissions to C{user} to all tables in C{database}.
"""
def grantReadWrite(user, database):
"""
Grant read and write permissions to C{user} to all tables in C{database}.
"""
| from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres',
pty=False)
def grantRead(user, database):
"""
Grant read permissions to C{user} to all tables in C{database}.
"""
def grantReadWrite(user, database):
"""
Grant read and write permissions to C{user} to all tables in C{database}.
"""
|
[IMP] Order document topics by name | # -*- coding: utf-8 -*-
from odoo import api, fields, models
class DocumentTopic(models.Model):
_name = 'tmc.document_topic'
_description = 'document_topic'
_inherit = 'tmc.category'
_order = 'name'
first_parent_id = fields.Many2one(
comodel_name='tmc.document_topic',
compute='_compute_first_parent',
store=True
)
document_ids = fields.Many2many(
comodel_name='tmc.document',
relation='document_main_topic_rel',
column1='main_topic_ids'
)
parent_id = fields.Many2one(
comodel_name='tmc.document_topic',
string='Main Topic'
)
child_ids = fields.One2many(
comodel_name='tmc.document_topic',
inverse_name='parent_id'
)
important = fields.Boolean()
@api.multi
@api.depends('parent_id',
'parent_id.parent_id')
def _compute_first_parent(self):
for document_topic in self:
first_parent_id = False
parent = document_topic.parent_id
while parent:
first_parent_id = parent.id
parent = parent.parent_id
document_topic.first_parent_id = first_parent_id
| # -*- coding: utf-8 -*-
from odoo import api, fields, models
class DocumentTopic(models.Model):
_name = 'tmc.document_topic'
_description = 'document_topic'
_inherit = 'tmc.category'
first_parent_id = fields.Many2one(
comodel_name='tmc.document_topic',
compute='_compute_first_parent',
store=True
)
document_ids = fields.Many2many(
comodel_name='tmc.document',
relation='document_main_topic_rel',
column1='main_topic_ids'
)
parent_id = fields.Many2one(
comodel_name='tmc.document_topic',
string='Main Topic'
)
child_ids = fields.One2many(
comodel_name='tmc.document_topic',
inverse_name='parent_id'
)
important = fields.Boolean()
@api.multi
@api.depends('parent_id',
'parent_id.parent_id')
def _compute_first_parent(self):
for document_topic in self:
first_parent_id = False
parent = document_topic.parent_id
while parent:
first_parent_id = parent.id
parent = parent.parent_id
document_topic.first_parent_id = first_parent_id
|
Change the input entry to 'lib/index.js' | import path from 'path';
export default {
cache: true,
target: 'web',
entry: path.resolve(__dirname, 'lib/index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename: 'react-sortable.js',
libraryTarget: 'umd',
library: 'SortableMixin'
},
externals: {
'react': {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
'sortablejs': {
root: 'Sortable',
commonjs2: 'sortablejs',
commonjs: 'sortablejs',
amd: 'sortablejs'
}
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loaders: ['eslint'],
exclude: /node_modules/
}
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/,
query: {
presets: ['es2015', 'stage-0', 'react'],
plugins: []
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
| import path from 'path';
export default {
cache: true,
target: 'web',
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.join(__dirname, 'dist'),
filename: 'react-sortable.js',
libraryTarget: 'umd',
library: 'SortableMixin'
},
externals: {
'react': {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
'sortablejs': {
root: 'Sortable',
commonjs2: 'sortablejs',
commonjs: 'sortablejs',
amd: 'sortablejs'
}
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loaders: ['eslint'],
exclude: /node_modules/
}
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/,
query: {
presets: ['es2015', 'stage-0', 'react'],
plugins: []
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
|
Add 'and Contributors' to Author | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name="pylast",
version="2.2.0.dev0",
author="Amr Hassan <[email protected]> and Contributors",
install_requires=['six'],
tests_require=['mock', 'pytest', 'coverage', 'pycodestyle', 'pyyaml',
'pyflakes', 'flaky'],
description="A Python interface to Last.fm and Libre.fm",
author_email="[email protected]",
url="https://github.com/pylast/pylast",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Topic :: Internet",
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
python_requires='>=2.7.10, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
keywords=["Last.fm", "music", "scrobble", "scrobbling"],
packages=find_packages(exclude=('tests*',)),
license="Apache2"
)
# End of file
| #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name="pylast",
version="2.2.0.dev0",
author="Amr Hassan <[email protected]>",
install_requires=['six'],
tests_require=['mock', 'pytest', 'coverage', 'pycodestyle', 'pyyaml',
'pyflakes', 'flaky'],
description="A Python interface to Last.fm and Libre.fm",
author_email="[email protected]",
url="https://github.com/pylast/pylast",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Topic :: Internet",
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
python_requires='>=2.7.10, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
keywords=["Last.fm", "music", "scrobble", "scrobbling"],
packages=find_packages(exclude=('tests*',)),
license="Apache2"
)
# End of file
|
Fix trade signs on Bitfinex
* Trades from all other exchanges are presented with positive amounts (with the trade type indicating direction). On Bitfinex, sells were arriving negative and buys positive. | package info.bitrich.xchangestream.bitfinex.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;
import java.math.BigDecimal;
/**
* Created by Lukas Zaoralek on 7.11.17.
*/
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
public long tradeId;
public long timestamp;
public BigDecimal amount;
public BigDecimal price;
public BitfinexWebSocketTrade() {
}
public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
this.tradeId = tradeId;
this.timestamp = timestamp;
this.amount = amount;
this.price = price;
}
public long getTradeId() {
return tradeId;
}
public long getTimestamp() {
return timestamp;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getPrice() {
return price;
}
public BitfinexTrade toBitfinexTrade() {
String type;
if (amount.compareTo(BigDecimal.ZERO) < 0) {
type = "sell";
} else {
type = "buy";
}
return new BitfinexTrade(price, amount.abs(), timestamp / 1000, "bitfinex", tradeId, type);
}
}
| package info.bitrich.xchangestream.bitfinex.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;
import java.math.BigDecimal;
/**
* Created by Lukas Zaoralek on 7.11.17.
*/
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
public long tradeId;
public long timestamp;
public BigDecimal amount;
public BigDecimal price;
public BitfinexWebSocketTrade() {
}
public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
this.tradeId = tradeId;
this.timestamp = timestamp;
this.amount = amount;
this.price = price;
}
public long getTradeId() {
return tradeId;
}
public long getTimestamp() {
return timestamp;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getPrice() {
return price;
}
public BitfinexTrade toBitfinexTrade() {
String type;
if (amount.compareTo(BigDecimal.ZERO) < 0) {
type = "sell";
} else {
type = "buy";
}
return new BitfinexTrade(price, amount, timestamp / 1000, "bitfinex", tradeId, type);
}
}
|
Add angular service for VariableCategory | angular.module('dplaceServices', ['ngResource'])
.factory('LanguageClass', function ($resource) {
return $resource(
'/api/v1/language_classes/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('Variable', function ($resource) {
return $resource(
'/api/v1/variables/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('VariableCategory', function ($resource) {
return $resource(
'/api/v1/categories/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('CodeDescription', function ($resource) {
return $resource(
'/api/v1/codes/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('FindSocieties', function($resource) {
return $resource(
'/api/v1/find_societies',
{},{
find: {
method: 'GET',
isArray: true
}
}
)
}); | angular.module('dplaceServices', ['ngResource'])
.factory('LanguageClass', function ($resource) {
return $resource(
'/api/v1/language_classes/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('Variable', function ($resource) {
return $resource(
'/api/v1/variables/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('CodeDescription', function ($resource) {
return $resource(
'/api/v1/codes/:id',
{page_size: 1000}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers) {
return JSON.parse(data).results;
}
}
});
})
.factory('FindSocieties', function($resource) {
return $resource(
'/api/v1/find_societies',
{},{
find: {
method: 'GET',
isArray: true
}
}
)
}); |
Add ibutton when importing old people | from django.core.management.base import BaseCommand, CommandError
from barsystem_base.models import Person, Token
class Command(BaseCommand):
args = '<filename>'
help = 'Import list of people'
csv_columns = 'id,first_name,last_name,nick_name,amount,type,token'.split(',')
def handle(self, *args, **kwargs):
if len(args) == 0:
raise CommandError('Please supply filename')
with open(args[0], 'r') as f:
columns = None
for line in [line.strip().split(',') for line in f.readlines() if line[0] != '#']:
# print(line)
# take header
if columns is None:
columns = line
continue
values = dict(zip(columns, line))
values['active'] = values['type'] != 'hidden'
try:
p = Person.objects.get(id=values['id'])
except Person.DoesNotExist:
p = Person()
for key, val in values.items():
if hasattr(p, key):
setattr(p, key, val)
print(p)
p.save()
t = Token()
t.type = 'ibutton'
t.value = values['token']
t.person = p
t.save()
print('Done') | from django.core.management.base import BaseCommand, CommandError
from barsystem_base.models import Person
class Command(BaseCommand):
args = '<filename>'
help = 'Import list of people'
csv_columns = 'id,first_name,last_name,nick_name,amount,type,token'.split(',')
def handle(self, *args, **kwargs):
if len(args) == 0:
raise CommandError('Please supply filename')
with open(args[0], 'r') as f:
columns = None
for line in [line.strip().split(',') for line in f.readlines() if line[0] != '#']:
# print(line)
# take header
if columns is None:
columns = line
continue
values = dict(zip(columns, line))
values['active'] = values['type'] != 'hidden'
try:
p = Person.objects.get(id=values['id'])
except Person.DoesNotExist:
p = Person()
for key, val in values.items():
if hasattr(p, key):
setattr(p, key, val)
print(p)
p.save()
print('Done') |
Bump version number for another release with ducktyping in it | VERSION = (1, 0, 'alpha', 12)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
| VERSION = (1, 0, 'alpha', 11)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
Replace "reloadPage" AJAX response class constructor argument with "redirectUrl". | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\HttpFoundation;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* AJAX response
*/
class AjaxResponse extends JsonResponse
{
/**
* @param string $html HTML
* @param bool $success Is success
* @param string $message Message
* @param array $data Additional data
* @param string $redirectUrl Redirect URL
* @param int $status Response status code
* @param array $headers Response headers
*/
public function __construct(
$html = '',
$success = true,
$message = null,
array $data = array(),
$redirectUrl = null,
$status = 200,
array $headers = array()
) {
parent::__construct(array_merge($data, array(
'html' => $html,
'message' => $message,
'redirectUrl' => $redirectUrl,
'success' => $success,
)), $status, $headers);
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\HttpFoundation;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* AJAX response
*/
class AjaxResponse extends JsonResponse
{
/**
* @param string $html HTML
* @param bool $success Is success
* @param string $message Message
* @param array $data Additional data
* @param bool $reloadPage Whether to reload page
* @param int $status Response status code
* @param array $headers Response headers
*/
public function __construct(
$html = '',
$success = true,
$message = null,
array $data = array(),
$reloadPage = false,
$status = 200,
array $headers = array()
) {
parent::__construct(array_merge($data, array(
'html' => $html,
'message' => $message,
'reloadPage' => $reloadPage,
'success' => $success,
)), $status, $headers);
}
}
|
Test the ability to append new email address to the person | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Person(
'John',
'Doe',
copy(basic_address),
['+79834772053'],
['[email protected]']
)
person.add_address('new address')
self.assertEqual(
person.addresses,
basic_address + ['new address']
)
def test_add_phone(self):
basic_phone = ['+79237778492']
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
copy(basic_phone),
['[email protected]']
)
person.add_phone_number('+79234478810')
self.assertEqual(
person.phone_numbers,
basic_phone + ['+79234478810']
)
def test_add_email(self):
basic_email = ['[email protected]']
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
['+79834772053'],
copy(basic_email)
)
person.add_email('[email protected]')
self.assertEqual(
person.emails,
basic_phone + ['[email protected]']
)
| from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Person(
'John',
'Doe',
copy(basic_address),
['+79834772053'],
['[email protected]']
)
person.add_address('new address')
self.assertEqual(
person.addresses,
basic_address + ['new address']
)
def test_add_phone(self):
basic_phone = ['+79237778492']
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
copy(basic_phone),
['[email protected]']
)
person.add_phone_number('+79234478810')
self.assertEqual(
person.phone_numbers,
basic_phone + ['+79234478810']
)
def test_add_email(self):
pass |
Make the passed arguments to sysctlbyname convertible to c_char_p.
In python3, the default type of strings are unicode which cannot be
converted to c_char_p, resulting a type error from sysctlbyname,
using a b prefix for the string makes it convertible to c_char_p. | import sys, resource
from ctypes import *
import ctypes.util
if sys.platform == "darwin":
def available_memory():
libc = cdll.LoadLibrary(ctypes.util.find_library("libc"))
mem = c_uint64(0)
size = c_size_t(sizeof(mem))
libc.sysctlbyname.argtypes = [
c_char_p, c_void_p, c_void_p, c_void_p, c_ulong
]
libc.sysctlbyname(
b"hw.memsize",
c_voidp(addressof(mem)),
c_voidp(addressof(size)),
None,
0
)
return int(mem.value)
elif "linux" in sys.platform:
def available_memory():
libc = cdll.LoadLibrary(ctypes.util.find_library("libc"))
return libc.getpagesize() * libc.get_phys_pages()
else:
def available_memory():
return int(1024**4)
def set_mem_limit(limit):
bytes = 0
if limit.endswith('%'):
p = float(limit[:-1]) / 100.0
bytes = int(p * available_memory())
elif limit:
bytes = int(limit)
if bytes > 0:
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
bmin = lambda x: min(bytes if x < 0 else x, bytes)
resource.setrlimit(resource.RLIMIT_AS, (bmin(soft), bmin(hard)))
| import sys, resource
from ctypes import *
import ctypes.util
if sys.platform == "darwin":
def available_memory():
libc = cdll.LoadLibrary(ctypes.util.find_library("libc"))
mem = c_uint64(0)
size = c_size_t(sizeof(mem))
libc.sysctlbyname.argtypes = [
c_char_p, c_void_p, c_void_p, c_void_p, c_ulong
]
libc.sysctlbyname(
"hw.memsize",
c_voidp(addressof(mem)),
c_voidp(addressof(size)),
None,
0
)
return int(mem.value)
elif "linux" in sys.platform:
def available_memory():
libc = cdll.LoadLibrary(ctypes.util.find_library("libc"))
return libc.getpagesize() * libc.get_phys_pages()
else:
def available_memory():
return int(1024**4)
def set_mem_limit(limit):
bytes = 0
if limit.endswith('%'):
p = float(limit[:-1]) / 100.0
bytes = int(p * available_memory())
elif limit:
bytes = int(limit)
if bytes > 0:
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
bmin = lambda x: min(bytes if x < 0 else x, bytes)
resource.setrlimit(resource.RLIMIT_AS, (bmin(soft), bmin(hard)))
|
Remove redundant ClientException handling from generic throwable handler | package uk.gov.register.providers;
import org.glassfish.jersey.server.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.gov.register.views.ViewFactory;
import uk.gov.register.views.representations.ExtraMediaType;
import javax.inject.Inject;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class ThrowableExceptionMapper implements ExceptionMapper<Throwable> {
public static final Logger LOGGER = LoggerFactory.getLogger(ThrowableExceptionMapper.class);
private ViewFactory viewFactory;
@Inject
public ThrowableExceptionMapper(ViewFactory viewFactory) {
this.viewFactory = viewFactory;
}
@Override
public Response toResponse(Throwable exception) {
if (exception instanceof ParamException.PathParamException) {
return Response.status(Response.Status.NOT_FOUND)
.header(HttpHeaders.CONTENT_TYPE, ExtraMediaType.TEXT_HTML)
.entity(viewFactory.exceptionNotFoundView())
.build(); }
LOGGER.error("Uncaught exception: {}", exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, ExtraMediaType.TEXT_HTML)
.entity(viewFactory.exceptionServerErrorView())
.build();
}
}
| package uk.gov.register.providers;
import org.glassfish.jersey.server.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.gov.register.views.ViewFactory;
import uk.gov.register.views.representations.ExtraMediaType;
import javax.inject.Inject;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class ThrowableExceptionMapper implements ExceptionMapper<Throwable> {
public static final Logger LOGGER = LoggerFactory.getLogger(ThrowableExceptionMapper.class);
private ViewFactory viewFactory;
@Inject
public ThrowableExceptionMapper(ViewFactory viewFactory) {
this.viewFactory = viewFactory;
}
@Override
public Response toResponse(Throwable exception) {
if (exception instanceof ClientErrorException) {
throw (ClientErrorException) exception;
}
if (exception instanceof ParamException.PathParamException) {
return Response.status(Response.Status.NOT_FOUND)
.header(HttpHeaders.CONTENT_TYPE, ExtraMediaType.TEXT_HTML)
.entity(viewFactory.exceptionNotFoundView())
.build(); }
LOGGER.error("Uncaught exception: {}", exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, ExtraMediaType.TEXT_HTML)
.entity(viewFactory.exceptionServerErrorView())
.build();
}
}
|
Include error message in node status endpoint | var PSQL = require('cartodb-psql');
function AnalysisStatusBackend() {
}
module.exports = AnalysisStatusBackend;
AnalysisStatusBackend.prototype.getNodeStatus = function (params, callback) {
var nodeId = params.nodeId;
var statusQuery = [
'SELECT node_id, status, updated_at, last_error_message as error_message',
'FROM cdb_analysis_catalog where node_id = \'' + nodeId + '\''
].join(' ');
var pg = new PSQL(dbParamsFromReqParams(params));
pg.query(statusQuery, function(err, result) {
if (err) {
return callback(err, result);
}
result = result || {};
var rows = result.rows || [];
var statusResponse = rows[0] || {
node_id: nodeId,
status: 'unknown'
};
if (statusResponse.status !== 'failed') {
delete statusResponse.error_message;
}
return callback(null, statusResponse);
}, true); // use read-only transaction
};
function dbParamsFromReqParams(params) {
var dbParams = {};
if ( params.dbuser ) {
dbParams.user = params.dbuser;
}
if ( params.dbpassword ) {
dbParams.pass = params.dbpassword;
}
if ( params.dbhost ) {
dbParams.host = params.dbhost;
}
if ( params.dbport ) {
dbParams.port = params.dbport;
}
if ( params.dbname ) {
dbParams.dbname = params.dbname;
}
return dbParams;
}
| var PSQL = require('cartodb-psql');
function AnalysisStatusBackend() {
}
module.exports = AnalysisStatusBackend;
AnalysisStatusBackend.prototype.getNodeStatus = function (params, callback) {
var nodeId = params.nodeId;
var statusQuery = 'SELECT node_id, status, updated_at FROM cdb_analysis_catalog where node_id = \'' + nodeId + '\'';
var pg = new PSQL(dbParamsFromReqParams(params));
pg.query(statusQuery, function(err, result) {
if (err) {
return callback(err, result);
}
result = result || {};
var rows = result.rows || [];
return callback(null, rows[0] || {
node_id: nodeId,
status: 'unknown'
});
}, true); // use read-only transaction
};
function dbParamsFromReqParams(params) {
var dbParams = {};
if ( params.dbuser ) {
dbParams.user = params.dbuser;
}
if ( params.dbpassword ) {
dbParams.pass = params.dbpassword;
}
if ( params.dbhost ) {
dbParams.host = params.dbhost;
}
if ( params.dbport ) {
dbParams.port = params.dbport;
}
if ( params.dbname ) {
dbParams.dbname = params.dbname;
}
return dbParams;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.