text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Make tests green to build on Hudson.
Need to check warnings from checkstyle plugin. | package ua.yandex.shad;
public class DoubleArray {
/**
* The default capacity of new DoubleArrays.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Storage for data.
*/
private double[] data;
/**
* Actual size of array.
*/
private int size;
/**
* Construct new DoubleArray with initial capacity.
*
* @param capacity initial capacity of DoubleArray
* @throws IllegalArgumentException if capacity is negative
*/
public DoubleArray(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
data = new double[capacity];
}
/**
* Construct new DoubleArray with default capacity.
*/
public DoubleArray() {
this(DEFAULT_CAPACITY);
}
/**
* Construct new DoubleArray from variable length list
*
* @param nums example of array
*/
public DoubleArray(double... nums) {
data = nums.clone();
size = nums.length;
}
/**
* Returns the number of elements in array.
*
* @return array size
*/
public int size() {
return size;
}
/**
* Converts DoubleArray to array of doubles
*
* @return new instance of array of double with elements from DoubleArray
*/
public double[] toArray() {
return data.clone();
}
/**
* Checks if array is empty.
*
* @return true if there are no elements in array
*/
public boolean isEmpty() {
return size == 0;
}
} | package ua.yandex.shad;
public class DoubleArray {
/**
* The default capacity of new DoubleArrays.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Storage for data.
*/
private double[] data;
/**
* Actual size of array.
*/
private int size;
/**
* Construct new DoubleArray with initial capacity.
*
* @param capacity initial capacity of DoubleArray
* @throws IllegalArgumentException if capacity is negative
*/
public DoubleArray(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
data = new double[capacity];
}
/**
* Construct new DoubleArray with default capacity.
*/
public DoubleArray() {
this(DEFAULT_CAPACITY);
}
/**
* Construct new DoubleArray from variable length list
*
* @param nums example of array
*/
public DoubleArray(double... nums) {
data = nums.clone();
size = nums.length;
}
/**
* Returns the number of elements in array.
*
* @return array size
*/
public int size() {
return size;
}
/**
* Converts DoubleArray to array of doubles
*
* @return new instance of array of double with elements from DoubleArray
*/
public double[] toArray() {
return new double[]{};
}
/**
* Checks if array is empty.
*
* @return true if there are no elements in array
*/
public boolean isEmpty() {
return size == 0;
}
} |
Hide overlay on ajax error | jQuery(document).ready(function($) {
var container = $('#splashing_images');
$.LoadingOverlaySetup({
color : "rgba(241,241,241,0.8)",
maxSize : "80px",
minSize : "20px",
resizeInterval : 0,
size : "30%"
});
$('a.upload').click(function(e){
var element = $(this);
var image = element.find('img');
// If not saving, then proceed
if(!element.hasClass('saving')){
element.addClass('saving');
e.preventDefault();
var payload = { source : $(this).data('source'), author: $(this).data('author'), credit: $(this).data('credit')};
payload[window.csrfTokenName] = window.csrfTokenValue;
$.ajax({
type: 'POST',
url: Craft.getActionUrl('unsplash/download/save'),
dataType: 'JSON',
data: payload,
beforeSend: function() {
image.LoadingOverlay("show");
},
success: function(response) {
image.LoadingOverlay("hide");
Craft.cp.displayNotice(Craft.t('Image saved!'));
},
error: function(xhr, status, error) {
image.LoadingOverlay("hide");
Craft.cp.displayError(Craft.t('Oops, something went wrong!'));
}
});
};
});
}); | jQuery(document).ready(function($) {
var container = $('#splashing_images');
$.LoadingOverlaySetup({
color : "rgba(241,241,241,0.8)",
maxSize : "80px",
minSize : "20px",
resizeInterval : 0,
size : "30%"
});
$('a.upload').click(function(e){
var element = $(this);
var image = element.find('img');
// If not saving, then proceed
if(!element.hasClass('saving')){
element.addClass('saving');
e.preventDefault();
var payload = { source : $(this).data('source'), author: $(this).data('author'), credit: $(this).data('credit')};
payload[window.csrfTokenName] = window.csrfTokenValue;
$.ajax({
type: 'POST',
url: Craft.getActionUrl('unsplash/download/save'),
dataType: 'JSON',
data: payload,
beforeSend: function() {
image.LoadingOverlay("show");
},
success: function(response) {
image.LoadingOverlay("hide");
Craft.cp.displayNotice(Craft.t('Image saved!'));
},
error: function(xhr, status, error) {
Craft.cp.displayError(Craft.t('Oops, something went wrong!'));
}
});
};
});
}); |
Include editUser relationship when editing posts.
Closes flarum/core#214. Hopefully. :) | <?php namespace Flarum\Api\Actions\Posts;
use Flarum\Core\Posts\Commands\EditPost;
use Flarum\Api\Actions\SerializeResourceAction;
use Flarum\Api\JsonApiRequest;
use Illuminate\Contracts\Bus\Dispatcher;
use Tobscure\JsonApi\Document;
class UpdateAction extends SerializeResourceAction
{
/**
* @var Dispatcher
*/
protected $bus;
/**
* @inheritdoc
*/
public $serializer = 'Flarum\Api\Serializers\PostSerializer';
/**
* @inheritdoc
*/
public $include = [
'editUser' => true,
];
/**
* @inheritdoc
*/
public $link = [];
/**
* @inheritdoc
*/
public $limitMax = 50;
/**
* @inheritdoc
*/
public $limit = 20;
/**
* @inheritdoc
*/
public $sortFields = [];
/**
* @inheritdoc
*/
public $sort;
/**
* @param Dispatcher $bus
*/
public function __construct(Dispatcher $bus)
{
$this->bus = $bus;
}
/**
* Update a post according to input from the API request, and return it
* ready to be serialized and assigned to the JsonApi response.
*
* @param JsonApiRequest $request
* @param Document $document
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function data(JsonApiRequest $request, Document $document)
{
return $this->bus->dispatch(
new EditPost($request->get('id'), $request->actor, $request->get('data'))
);
}
}
| <?php namespace Flarum\Api\Actions\Posts;
use Flarum\Core\Posts\Commands\EditPost;
use Flarum\Api\Actions\SerializeResourceAction;
use Flarum\Api\JsonApiRequest;
use Illuminate\Contracts\Bus\Dispatcher;
use Tobscure\JsonApi\Document;
class UpdateAction extends SerializeResourceAction
{
/**
* @var Dispatcher
*/
protected $bus;
/**
* @inheritdoc
*/
public $serializer = 'Flarum\Api\Serializers\PostSerializer';
/**
* @inheritdoc
*/
public $include = [];
/**
* @inheritdoc
*/
public $link = [];
/**
* @inheritdoc
*/
public $limitMax = 50;
/**
* @inheritdoc
*/
public $limit = 20;
/**
* @inheritdoc
*/
public $sortFields = [];
/**
* @inheritdoc
*/
public $sort;
/**
* @param Dispatcher $bus
*/
public function __construct(Dispatcher $bus)
{
$this->bus = $bus;
}
/**
* Update a post according to input from the API request, and return it
* ready to be serialized and assigned to the JsonApi response.
*
* @param JsonApiRequest $request
* @param Document $document
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function data(JsonApiRequest $request, Document $document)
{
return $this->bus->dispatch(
new EditPost($request->get('id'), $request->actor, $request->get('data'))
);
}
}
|
Fix google undefined error (sentry js error) |
$(document).ready(function () {
function setMapByCoords(lng, lat) {
var myLatLng = new google.maps.LatLng(lat, lng);
if (typeof google === 'undefined') {
return;
}
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 17,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker(
{
position: myLatLng,
map: map
});
}
function initMap() {
var map_element = $('#map');
var e_slug = map_element.data('event');
var lng = map_element.data('lng');
var lat = map_element.data('lat');
if (!lng || !lat) {
$.ajax({
type: 'post',
url: Routing.generate('get_event_map_position', {slug: e_slug})
}).done(
function (data) {
if (data.result) {
setMapByCoords(data.lng, data.lat)
} else {
console.log('Error:' + data.error);
}
}
);
} else {
setMapByCoords(lng, lat)
}
}
if ($('#map').length > 0) {
initMap();
}
}); |
$(document).ready(function () {
function setMapByCoords(lng, lat) {
var myLatLng = new google.maps.LatLng(lat, lng);
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 17,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker(
{
position: myLatLng,
map: map
});
}
function initMap() {
var map_element = $('#map');
var e_slug = map_element.data('event');
var lng = map_element.data('lng');
var lat = map_element.data('lat');
if (!lng || !lat) {
$.ajax({
type: 'post',
url: Routing.generate('get_event_map_position', {slug: e_slug})
}).done(
function (data) {
if (data.result) {
setMapByCoords(data.lng, data.lat)
} else {
console.log('Error:' + data.error);
}
}
);
} else {
setMapByCoords(lng, lat)
}
}
if ($('#map').length > 0) {
initMap();
}
}); |
Save compiled JavaScript into the build/js directory | /* browserify task
---------------
Bundle javascripty things with browserify!
If the watch task is running, this uses watchify instead
of browserify for faster bundling using caching.
*/
var browserify = require('browserify');
var watchify = require('watchify');
var bundleLogger = require('../util/bundleLogger');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
gulp.task('browserify', function() {
var bundler = browserify({
// Required watchify args
cache: {}, packageCache: {}, fullPaths: true,
// Specify the entry point of your app
entries: ['./src/main/javascript/displayMRB.js'],
// Add file extentions to make optional in your requires
extensions: ['.coffee', '.hbs'],
// Enable source maps!
debug: true
});
var bundle = function() {
// Log when bundling starts
bundleLogger.start();
return bundler
.bundle()
// Report compile errors
.on('error', handleErrors)
// Use vinyl-source-stream to make the
// stream gulp compatible. Specifiy the
// desired output filename here.
.pipe(source('app.js'))
// Specify the output destination
.pipe(gulp.dest('./build/js/'))
// Log when bundling completes!
.on('end', bundleLogger.end);
};
if(global.isWatching) {
bundler = watchify(bundler);
// Rebundle with watchify on changes.
bundler.on('update', bundle);
}
return bundle();
});
| /* browserify task
---------------
Bundle javascripty things with browserify!
If the watch task is running, this uses watchify instead
of browserify for faster bundling using caching.
*/
var browserify = require('browserify');
var watchify = require('watchify');
var bundleLogger = require('../util/bundleLogger');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
gulp.task('browserify', function() {
var bundler = browserify({
// Required watchify args
cache: {}, packageCache: {}, fullPaths: true,
// Specify the entry point of your app
entries: ['./src/main/javascript/displayMRB.js'],
// Add file extentions to make optional in your requires
extensions: ['.coffee', '.hbs'],
// Enable source maps!
debug: true
});
var bundle = function() {
// Log when bundling starts
bundleLogger.start();
return bundler
.bundle()
// Report compile errors
.on('error', handleErrors)
// Use vinyl-source-stream to make the
// stream gulp compatible. Specifiy the
// desired output filename here.
.pipe(source('app.js'))
// Specify the output destination
.pipe(gulp.dest('./build/'))
// Log when bundling completes!
.on('end', bundleLogger.end);
};
if(global.isWatching) {
bundler = watchify(bundler);
// Rebundle with watchify on changes.
bundler.on('update', bundle);
}
return bundle();
});
|
Support yield alias of block | <?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\BlockToken;
class BlockScanner implements ScannerInterface
{
public function scan(State $state)
{
foreach ($state->scanToken(
BlockToken::class,
'(?:block|yield)(?:[\t ]+(?<mode>append|prepend|replace))?(?:[\t ]+(?<name>[a-zA-Z_][a-zA-Z0-9\-_]*))?'
) as $token) {
if ($token instanceof BlockToken && empty($token->getMode())) {
$token->setMode('replace');
}
yield $token;
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
foreach ($state->scanToken(
BlockToken::class,
'(?<mode>append|prepend|replace)(?:[\t ]+(?<name>[a-zA-ZA-Z][a-zA-Z0-9\-_]*))'
) as $token) {
yield $token;
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
}
}
| <?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\BlockToken;
class BlockScanner implements ScannerInterface
{
public function scan(State $state)
{
foreach ($state->scanToken(
BlockToken::class,
'block(?:[\t ]+(?<mode>append|prepend|replace))?(?:[\t ]+(?<name>[a-zA-Z_][a-zA-Z0-9\-_]*))?'
) as $token) {
if ($token instanceof BlockToken && empty($token->getMode())) {
$token->setMode('replace');
}
yield $token;
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
foreach ($state->scanToken(
BlockToken::class,
'(?<mode>append|prepend|replace)(?:[\t ]+(?<name>[a-zA-ZA-Z][a-zA-Z0-9\-_]*))'
) as $token) {
yield $token;
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
}
}
|
Support Wagtail 1.0 -> 1.3.x | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtailpress',
version='0.1',
packages=['wagtailpress'],
include_package_data=True,
license='BSD License',
description='wagtailpress is an Django app which extends the Wagtail CMS to be similar to WordPress.',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/FlipperPA/wagtailpress',
author='Timothy Allen',
author_email='[email protected]',
install_requires=[
'wagtail>=1.0,<1.4',
'Markdown==2.6.2',
'Pygments==2.0.2',
'django-bootstrap3==6.2.2',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtailpress',
version='0.1',
packages=['wagtailpress'],
include_package_data=True,
license='BSD License',
description='wagtailpress is an Django app which extends the Wagtail CMS to be similar to WordPress.',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/FlipperPA/wagtailpress',
author='Timothy Allen',
author_email='[email protected]',
install_requires=[
'wagtail>=1.0,<2.0',
'Markdown==2.6.2',
'Pygments==2.0.2',
'django-bootstrap3==6.2.2',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix minor bug in length comparison. | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if len(sys.argv) < 3:
print('Usage: %s <package1/module1> <package2/module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3]
diff = set([])
if isdir(old):
assert isdir(new)
for dirpath, dirnames, filenames in walk(new):
for file_ in filenames:
if is_py_file(file_):
new_file = join(dirpath, file_)
old_file = new_file.replace(new, old)
if exists(old_file):
mdiff = diff_files(old_file, new_file)
if mdiff is not None:
diff.add(mdiff)
else:
diff.add(diff_files(old, new))
for module in diff:
print(module)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if sys.argv < 3:
print('Usage: %s <module1> <module2>' % sys.argv[0])
sys.exit(1)
old, new = sys.argv[1:3]
diff = set([])
if isdir(old):
assert isdir(new)
for dirpath, dirnames, filenames in walk(new):
for file_ in filenames:
if is_py_file(file_):
new_file = join(dirpath, file_)
old_file = new_file.replace(new, old)
if exists(old_file):
mdiff = diff_files(old_file, new_file)
if mdiff is not None:
diff.add(mdiff)
else:
diff.add(diff_files(old, new))
for module in diff:
print(module)
if __name__ == '__main__':
main()
|
Add py3.3 to trove classifiers | import multiprocessing # stop tests breaking tox
from setuptools import setup
import tvrenamr
requires = ('pyyaml', 'requests')
packages = ('tvrenamr',)
setup_requires = ('minimock', 'mock', 'nose', 'pyyaml')
setup(
name = tvrenamr.__title__,
version = tvrenamr.__version__,
description = 'Rename tv show files using online databases',
long_description = open('README.rst').read() + '\n\n' +
open('CHANGELOG.rst').read(),
author = tvrenamr.__author__,
author_email = '[email protected]',
url = 'http://tvrenamr.info',
license = open('LICENSE').read(),
packages = packages,
entry_points = {'console_scripts': ['tvr = tvrenamr.frontend:run']},
classifiers = (
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English'
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Topic :: Multimedia',
'Topic :: Utilities',
),
install_requires = requires,
setup_requires=setup_requires,
test_suite='nose.collector',
)
| import multiprocessing # stop tests breaking tox
from setuptools import setup
import tvrenamr
requires = ('pyyaml', 'requests')
packages = ('tvrenamr',)
setup_requires = ('minimock', 'mock', 'nose', 'pyyaml')
setup(
name = tvrenamr.__title__,
version = tvrenamr.__version__,
description = 'Rename tv show files using online databases',
long_description = open('README.rst').read() + '\n\n' +
open('CHANGELOG.rst').read(),
author = tvrenamr.__author__,
author_email = '[email protected]',
url = 'http://tvrenamr.info',
license = open('LICENSE').read(),
packages = packages,
entry_points = {'console_scripts': ['tvr = tvrenamr.frontend:run']},
classifiers = (
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English'
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Multimedia',
'Topic :: Utilities',
),
install_requires = requires,
setup_requires=setup_requires,
test_suite='nose.collector',
)
|
BAP-12479: Create new widget controller buttonsAction
- CR fixes | <?php
namespace Oro\Bundle\ScopeBundle\Tests\Functional;
use Oro\Bundle\ScopeBundle\Entity\Scope;
use Oro\Bundle\ScopeBundle\Tests\Unit\Stub\StubScope;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
use Oro\Component\PropertyAccess\PropertyAccessor;
class AbstractScopeProviderTestCase extends WebTestCase
{
protected function setUp()
{
$this->initClient([], self::generateBasicAuthHeader());
$this->client->useHashNavigation(true);
}
/**
* @param string $scopeProviderCriteriaField
* @param array $scopeTypes
*/
protected static function assertProviderRegisteredWithScopeTypes($scopeProviderCriteriaField, array $scopeTypes)
{
$scopeManager = self::getContainer()->get('oro_scope.scope_manager');
foreach ($scopeTypes as $scopeType) {
$scope = self::createScope($scopeProviderCriteriaField, 'value');
//if provider would be loaded by certain scope type - criteria would be filled with proper value from scope
$criteria = $scopeManager->getCriteriaByScope($scope, $scopeType);
self::assertArraySubset(
[$scopeProviderCriteriaField => 'value'],
$criteria->toArray(),
'Criteria field from correct provider is filled by scope value.'
);
}
}
/**
* @param string $field
* @param mixed $value
* @return Scope
*/
private static function createScope($field, $value)
{
$scope = new StubScope();
$propertyAccessor = new PropertyAccessor();
$propertyAccessor->setValue($scope, $field, $value);
return $scope;
}
}
| <?php
namespace Oro\Bundle\ScopeBundle\Tests\Functional;
use Oro\Bundle\ScopeBundle\Entity\Scope;
use Oro\Bundle\ScopeBundle\Tests\Unit\Stub\StubScope;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
class AbstractScopeProviderTestCase extends WebTestCase
{
protected function setUp()
{
$this->initClient([], self::generateBasicAuthHeader());
$this->client->useHashNavigation(true);
}
/**
* @param string $scopeProviderCriteriaField
* @param array $scopeTypes
*/
protected static function assertProviderRegisteredWithScopeTypes($scopeProviderCriteriaField, array $scopeTypes)
{
$scopeManager = self::getContainer()->get('oro_scope.scope_manager');
foreach ($scopeTypes as $scopeType) {
$scope = self::createScope($scopeProviderCriteriaField, 'value');
//if provider would be loaded by certain scope type - criteria would be filled with proper value from scope
$criteria = $scopeManager->getCriteriaByScope($scope, $scopeType);
self::assertArraySubset(
[$scopeProviderCriteriaField => 'value'],
$criteria->toArray(),
'Criteria field from correct provider is filled by scope value.'
);
}
}
/**
* @param string $field
* @param mixed $value
* @return Scope
*/
private static function createScope($field, $value)
{
$scope = new StubScope();
//using setter method as application would autoload extended entity
$method = 'set' . ucfirst(strtolower($field));
$scope->{$method}($value);
return $scope;
}
}
|
Add support for creating snapshots for program owner | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a program they are automatically given the ProgramOwner role. This
allows them to Edit, Delete, or Map objects to the Program. It also allows
them to add people and assign them roles when their programs are private.
ProgramOwner is the most powerful role.
"""
permissions = {
"read": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole",
"Context",
],
"create": [
"ObjectDocument",
"ObjectPerson",
"ProgramControl",
"Relationship",
"UserRole",
"Audit",
"Snapshot",
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole"
],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole",
]
}
| # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a program they are automatically given the ProgramOwner role. This
allows them to Edit, Delete, or Map objects to the Program. It also allows
them to add people and assign them roles when their programs are private.
ProgramOwner is the most powerful role.
"""
permissions = {
"read": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole",
"Context",
],
"create": [
"ObjectDocument",
"ObjectPerson",
"ProgramControl",
"Relationship",
"UserRole",
"Audit",
],
"view_object_page": [
"__GGRC_ALL__"
],
"update": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole"
],
"delete": [
"ObjectDocument",
"ObjectPerson",
"Program",
"ProgramControl",
"Relationship",
"UserRole",
]
}
|
Tweak watch task configs: separate linting from help generation, and add the templates to the files that trigger help
generation | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['**/*.js', '!**/node_modules/**'],
options: {
newcap: false
}
},
generation: {
docs: {
src: ['lib/components/*.js'],
docs: {
markdown: {
byName: {dest: 'docs/markdown/byName.md', pre: 'docs/templates/markdownNamePre.md' },
byCategory: { dest: 'docs/markdown/byCategory.md', pre: 'docs/templates/markdownCategoryPre.md' }
},
html: {
byName: {
dest: 'docs/html/index.html',
pre: 'docs/templates/HTMLNamePre.html',
post: 'docs/templates/HTMLNamePost.html'
},
byCategory: {
dest: 'docs/html/byCategory.html',
pre: 'docs/templates/HTMLCategoryPre.html',
post: 'docs/templates/HTMLCategoryPost.html'
}
}
}
}
},
watch: {
lint: {
files: ['customGruntTasks/generation.js', 'docgen/**/*.js', 'Gruntfile.js', 'lib/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
},
helpGeneration: {
files: ['customGruntTasks/generation.js', 'docs/templates/*', 'docgen/**/*.js', 'lib/**/*.js'],
tasks: ['generation:docs']
}
}
});
var tasks = ['jshint', 'watch'];
tasks.map(function(task) {
grunt.loadNpmTasks('grunt-contrib-' + task);
});
grunt.loadTasks('customGruntTasks');
grunt.registerTask('default', ['watch']);
};
| module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['**/*.js', '!**/node_modules/**'],
options: {
newcap: false
}
},
generation: {
all: {
src: ['lib/components/*.js'],
docs: {
markdown: {
byName: {dest: 'docs/markdown/byName.md', pre: 'docs/templates/markdownNamePre.md' },
byCategory: { dest: 'docs/markdown/byCategory.md', pre: 'docs/templates/markdownCategoryPre.md' }
},
html: {
byName: {
dest: 'docs/html/index.html',
pre: 'docs/templates/HTMLNamePre.html',
post: 'docs/templates/HTMLNamePost.html'
},
byCategory: {
dest: 'docs/html/byCategory.html',
pre: 'docs/templates/HTMLCategoryPre.html',
post: 'docs/templates/HTMLCategoryPost.html'
}
}
}
}
},
watch: {
files: ['lib/**/*.js', 'test/**/*.js', 'docgen/**/*.js', 'Gruntfile.js'],
tasks: ['jshint', 'generation']
}
});
var tasks = ['jshint', 'watch'];
tasks.map(function(task) {
grunt.loadNpmTasks('grunt-contrib-' + task);
});
grunt.loadTasks('customGruntTasks');
grunt.registerTask('default', ['watch']);
};
|
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS. | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Make dust recipes actually give 40 dust | package com.agilemods.materiamuto.common.core;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class MMRecipes {
public static void initialize() {
ItemStack dustLow = new ItemStack(MMItems.covalenceDust, 40, 0);
ItemStack dustMedium = new ItemStack(MMItems.covalenceDust, 40, 1);
ItemStack dustHigh = new ItemStack(MMItems.covalenceDust, 40, 2);
GameRegistry.addShapelessRecipe(
dustLow,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
new ItemStack(Items.coal, 1, 1)
);
GameRegistry.addShapelessRecipe(
dustMedium,
Items.iron_ingot,
Items.redstone
);
GameRegistry.addShapelessRecipe(
dustHigh,
Items.diamond,
new ItemStack(Items.coal, 1, 0)
);
}
}
| package com.agilemods.materiamuto.common.core;
import com.agilemods.materiamuto.common.core.MMItems;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class MMRecipes {
public static void initialize() {
ItemStack dustLow = new ItemStack(MMItems.covalenceDust, 1, 0);
ItemStack dustMedium = new ItemStack(MMItems.covalenceDust, 1, 1);
ItemStack dustHigh = new ItemStack(MMItems.covalenceDust, 1, 2);
GameRegistry.addShapelessRecipe(
dustLow,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
Blocks.cobblestone,
new ItemStack(Items.coal, 1, 1)
);
GameRegistry.addShapelessRecipe(
dustMedium,
Items.iron_ingot,
Items.redstone
);
GameRegistry.addShapelessRecipe(
dustHigh,
Items.diamond,
new ItemStack(Items.coal, 1, 0)
);
}
}
|
Remove the hard coded process name now that the process name has been set. | (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
$state.go('projects.project.processes.create',
{process: existingProcess.process_name, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
$state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
|
Bump up to version 1.0.4 | #!/usr/bin/env python
import os
import sys
import setuptools.command.egg_info as egg_info_cmd
import shutil
from setuptools import setup, find_packages
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, 'README.rst')
try:
import gittaggers
tagger = gittaggers.EggInfoFromGit
except ImportError:
tagger = egg_info_cmd.egg_info
setup(name='schema-salad',
version='1.0.4',
description='Schema Annotations for Linked Avro Data (SALAD)',
long_description=open(README).read(),
author='Common workflow language working group',
author_email='[email protected]',
url="https://github.com/common-workflow-language/common-workflow-language",
download_url="https://github.com/common-workflow-language/common-workflow-language",
license='Apache 2.0',
packages=["schema_salad"],
package_data={'schema_salad': ['metaschema.yml']},
install_requires=[
'requests',
'PyYAML',
'avro',
'rdflib >= 4.2.0',
'rdflib-jsonld >= 0.3.0',
'mistune'
],
test_suite='tests',
tests_require=[],
entry_points={
'console_scripts': [ "schema-salad-tool=schema_salad.main:main" ]
},
zip_safe=True,
cmdclass={'egg_info': tagger},
)
| #!/usr/bin/env python
import os
import sys
import setuptools.command.egg_info as egg_info_cmd
import shutil
from setuptools import setup, find_packages
SETUP_DIR = os.path.dirname(__file__)
README = os.path.join(SETUP_DIR, 'README.rst')
try:
import gittaggers
tagger = gittaggers.EggInfoFromGit
except ImportError:
tagger = egg_info_cmd.egg_info
setup(name='schema-salad',
version='1.0.3',
description='Schema Annotations for Linked Avro Data (SALAD)',
long_description=open(README).read(),
author='Common workflow language working group',
author_email='[email protected]',
url="https://github.com/common-workflow-language/common-workflow-language",
download_url="https://github.com/common-workflow-language/common-workflow-language",
license='Apache 2.0',
packages=["schema_salad"],
package_data={'schema_salad': ['metaschema.yml']},
install_requires=[
'requests',
'PyYAML',
'avro',
'rdflib >= 4.2.0',
'rdflib-jsonld >= 0.3.0',
'mistune'
],
test_suite='tests',
tests_require=[],
entry_points={
'console_scripts': [ "schema-salad-tool=schema_salad.main:main" ]
},
zip_safe=True,
cmdclass={'egg_info': tagger},
)
|
Make py_version and assertion more readable | """Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
major, minor = version_info[:2]
py_version = 'py%s%s' % (major, minor)
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0, \
'Cookiecutter exits with %(exit_code)s:' \
' %(exception)s' % result.__dict__
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
| """Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
py_version = 'py%s%s' % version_info[:2]
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
|
Correct adding of statusmanager to endpoints | export default [
'config',
'hs.common.laymanService',
function (config, laymanService) {
const me = this;
function getItemsPerPageConfig(ds) {
return angular.isDefined(ds.paging) &&
angular.isDefined(ds.paging.itemsPerPage)
? ds.paging.itemsPerPage
: config.dsPaging || 20;
}
angular.extend(me, {
endpoints: [
...(config.status_manager_url
? [
{
type: 'statusmanager',
title: 'Status manager',
url: config.status_manager_url,
},
]
: []),
...(config.datasources || []).map((ds) => {
return {
url: ds.url,
type: ds.type,
title: ds.title,
datasourcePaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
loaded: false,
},
compositionsPaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
},
paging: {
itemsPerPage: getItemsPerPageConfig(ds),
},
user: ds.user,
liferayProtocol: ds.liferayProtocol,
originalConfiguredUser: ds.user,
getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
};
}),
],
});
return me;
},
];
| export default [
'config',
'hs.common.laymanService',
function (config, laymanService) {
const me = this;
function getItemsPerPageConfig(ds) {
return angular.isDefined(ds.paging) &&
angular.isDefined(ds.paging.itemsPerPage)
? ds.paging.itemsPerPage
: config.dsPaging || 20;
}
angular.extend(me, {
endpoints: [
...(config.status_manager_url
? {
type: 'statusmanager',
title: 'Status manager',
url: config.status_manager_url,
}
: []),
...(config.datasources || []).map((ds) => {
return {
url: ds.url,
type: ds.type,
title: ds.title,
datasourcePaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
loaded: false,
},
compositionsPaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
},
paging: {
itemsPerPage: getItemsPerPageConfig(ds),
},
user: ds.user,
liferayProtocol: ds.liferayProtocol,
originalConfiguredUser: ds.user,
getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
};
}),
],
});
return me;
},
];
|
Make deprecation warning in doc string bold | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
| import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = 'Deprecated function.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
|
Use 2D array instead of 1D to keep track of which edges have been drawn
TODO: this probably isn't necessary | import turtle
import math
import sys
class Paley:
def __init__(self, p, radius = 290):
self.p = p
self.radius = radius
"""Return coordinates of ith vertex"""
def getVertex(self, i):
angle = i * 2 * math.pi / self.p
return (self.radius * math.cos(angle), self.radius * math.sin(angle))
"""Draw the Paley graph"""
def draw(self):
t = turtle.Turtle()
t.speed(0)
t.ht()
visited = [[False for j in xrange(self.p)] for i in xrange(self.p)]
for i in xrange(self.p):
t.pu()
t.goto(self.getVertex(i))
for residue in xrange(1, (self.p - 1) / 2):
j = (i + residue * residue) % self.p
if not visited[i][j]:
t.pd()
t.goto(self.getVertex(j))
t.pu()
t.goto(self.getVertex(i))
visited[i][j] = visited[j][i] = True
turtle.done()
def main():
if len(sys.argv) > 1:
pal = Paley(int(sys.argv[1]))
if len(sys.argv) > 2:
pal.radius = int(sys.argv[2])
pal.draw()
else:
print "Please specify size of Paley graph"
if __name__ == "__main__":
main()
| import turtle
import math
import sys
class Paley:
def __init__(self, p, radius = 290):
self.p = p
self.radius = radius
"""Return coordinates of ith vertex"""
def getVertex(self, i):
angle = i * 2 * math.pi / self.p
return (self.radius * math.cos(angle), self.radius * math.sin(angle))
"""Draw the Paley graph"""
def draw(self):
t = turtle.Turtle()
t.speed(0)
t.ht()
visited = [False for i in xrange(self.p)]
for i in xrange(self.p):
t.pu()
t.goto(self.getVertex(i))
for residue in xrange(1, (self.p - 1) / 2):
j = (i + residue * residue) % self.p
if not visited[j]:
t.pd()
t.goto(self.getVertex(j))
t.pu()
t.goto(self.getVertex(i))
visited[i] = True
turtle.done()
def main():
if len(sys.argv) > 1:
pal = Paley(int(sys.argv[1]))
if len(sys.argv) > 2:
pal.radius = int(sys.argv[2])
pal.draw()
else:
print "Please specify size of Paley graph"
if __name__ == "__main__":
main()
|
Use the newer PostUpdate instead of PostMedia | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
user_tokens = tweet.user.social_auth.all()[0].tokens
api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY,
consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
access_token_key=user_tokens['oauth_token'],
access_token_secret=user_tokens['oauth_token_secret'],)
try:
if tweet.media_path:
status = api.PostUpdate(tweet.text, media=tweet.media_path)
else:
status = api.PostUpdate(tweet.text)
except twitter.TwitterError, e:
print "Something went wrong with #{}: ".format(tweet.pk), e
tweet.failed_trails += 1
tweet.save()
continue
tweet.tweet_id = status.id
tweet.was_sent = True
tweet.save()
| import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trails__lte=5):
user_tokens = tweet.user.social_auth.all()[0].tokens
api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY,
consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
access_token_key=user_tokens['oauth_token'],
access_token_secret=user_tokens['oauth_token_secret'],)
try:
if tweet.media_path:
status = api.PostMedia(tweet.text, tweet.media_path)
else:
status = api.PostUpdate(tweet.text)
except twitter.TwitterError, e:
print "Something went wrong with #{}: ".format(tweet.pk), e
tweet.failed_trails += 1
tweet.save()
continue
tweet.tweet_id = status.id
tweet.was_sent = True
tweet.save()
|
Load from the pre processed data | from __future__ import division
import gzip
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import hdfs
import pandas as pd
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob.step import MRStep
class CascadeCount(MRJob):
OUTPUT_PROTOCOL = JSONValueProtocol
def configure_options(self):
super(CascadeCount, self).configure_options()
def mapper(self, _, line):
client = hdfs.client.Client("http://" + urlparse(line).netloc)
if line[-1] != "#":
with client.read(urlparse(line).path) as r:
# with open(urlparse(line).path) as r:
buf = BytesIO(r.read())
# If the data is in a GZipped file.
if ".gz" in line:
gzip_f = gzip.GzipFile(fileobj=buf)
content = gzip_f.read()
buf = StringIO.StringIO(content)
dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python",
compression=None).drop_duplicates(subset=[2], keep='last')
yield "apple", len(dtf.index)
def steps(self):
return [
MRStep(
mapper=self.mapper
)
]
if __name__ == '__main__':
CascadeCount.run()
| from __future__ import division
import gzip
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import hdfs
import pandas as pd
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob.step import MRStep
class CascadeCount(MRJob):
OUTPUT_PROTOCOL = JSONValueProtocol
def configure_options(self):
super(CascadeCount, self).configure_options()
def mapper(self, _, line):
client = hdfs.client.Client("http://" + urlparse(line).netloc)
if line[-1] != "#":
with client.read(urlparse(line).path) as r:
# with open(urlparse(line).path) as r:
buf = BytesIO(r.read())
# If the data is in a GZipped file.
if ".gz" in line:
gzip_f = gzip.GzipFile(fileobj=buf)
content = gzip_f.read()
buf = StringIO.StringIO(content)
dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python",
compression=None).drop_duplicates(subset=[2], keep='last')
yield "apple", len(dft.index)
def steps(self):
return [
MRStep(
mapper=self.mapper
)
]
if __name__ == '__main__':
CascadeCount.run()
|
Remove unused S3 config vars. | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
|
| Supported: "local", "s3", "rackspace"
|
*/
'default' => env('STORAGE_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
's3' => [
'driver' => 's3',
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'region' => 'us-east-1',
'bucket' => env('S3_BUCKET'),
],
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
|
| Supported: "local", "s3", "rackspace"
|
*/
'default' => env('STORAGE_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
's3' => [
'driver' => 's3',
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'region' => 'us-east-1',
'bucket' => env('S3_BUCKET'),
'base_url' => 'https://s3-external-1.amazonaws.com',
'public_url' => env('S3_URL'),
],
],
],
];
|
Fix duplicate linking with iframes. | window.addEventListener("load", function load() {
window.removeEventListener("load", load, false);
gBrowser.addEventListener("DOMContentLoaded", function(e) {
var document = e.originalTarget,
reGist = /^https?\:\/\/gist\.github\.com\/(\d*)/i,
reRel = /^\/?(\d+)$/,
gist = reGist.test(document.location.href),
anchors = document.querySelectorAll("a[href]"),
anchor,
image,
imageURL = "chrome://bl.ocks.org/content/bl.ocks.png",
i = -1,
n = anchors.length,
href,
match;
while (++i < n) {
match = (href = (anchor = anchors[i]).getAttribute("href")).match(reGist);
if (gist && !(match && match[1])) match = href.match(reRel);
if (match && match[1] && !anchor.matched) {
anchor.matched = true; // avoid duplicate linking on iframes
anchor = anchor.parentNode.insertBefore(document.createElement("a"), anchor.nextSibling);
anchor.setAttribute("href", "http://bl.ocks.org/" + match[1]);
anchor.setAttribute("title", "View bl.ock #" + match[1] + ".");
anchor.style.marginLeft = "2px";
image = anchor.appendChild(document.createElement("img"));
image.setAttribute("src", imageURL);
image.style.width = "16px";
}
}
}, false);
}, false);
| window.addEventListener("load", function(e) {
var run = function() {
var document = content.document;
var reGist = /^https?\:\/\/gist\.github\.com\/(\d*)/i,
reRel = /^\/?(\d+)$/,
gist = reGist.test(document.location.href),
anchors = document.querySelectorAll("a[href]"),
anchor,
image,
imageURL = "chrome://bl.ocks.org/content/bl.ocks.png",
i = -1,
n = anchors.length,
href,
match;
while (++i < n) {
match = (href = (anchor = anchors[i]).getAttribute("href")).match(reGist);
if (gist && !(match && match[1])) match = href.match(reRel);
if (match && match[1]) {
anchor = anchor.parentNode.insertBefore(document.createElement("a"), anchor.nextSibling);
anchor.setAttribute("href", "http://bl.ocks.org/" + match[1]);
anchor.setAttribute("title", "View bl.ock #" + match[1] + ".");
anchor.style.marginLeft = "2px";
image = anchor.appendChild(document.createElement("img"));
image.setAttribute("src", imageURL);
image.style.width = "16px";
}
}
};
var appcontent = document.getElementById("appcontent");
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", run, true);
}
}, false);
|
Fix file inclusion and make new release. | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='3.0.12a',
description='Swagger UI blueprint for Flask',
long_description=long_description,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*.css',
'dist/*.png'
],
}
)
| from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='3.0.12',
description='Swagger UI blueprint for Flask',
long_description=long_description,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*/*.js',
'dist/*/*.css',
'dist/*/*.gif',
'dist/*/*.png',
'dist/*/*.ico',
'dist/*/*.ttf',
],
}
)
|
Update date change for build | import React, {Component} from "react";
import RaisedButton from "material-ui/RaisedButton";
const styles = {
button: {
margin: 12,
},
}
class Home extends Component {
render() {
return (
<div className="buttons">
<h1>Gregory N. Katchmar</h1>
<h2>JavaScript Developer</h2>
<hr></hr>
<h4>More information at:</h4>
<RaisedButton
href="https://www.linkedin.com/in/gregory-katchmar-3a48275a"
target="_blank"
label="LinkedIn"
primary={true}
style={styles.button}
/>
<RaisedButton
href="https://github.com/gnkatchmar"
target="_blank"
label="Github"
primary={true}
style={styles.button}
/>
<RaisedButton
href="https://drive.google.com/open?id=0B-QmArVwrgLGSHJnbFN6VXZGb0k"
target="_blank"
label="Resume (PDF)"
primary={true}
style={styles.button}
/>
<hr></hr>
<h4>Contact me at:</h4>
<a href="mailto:[email protected]">[email protected]</a>
<hr></hr>
<p>Last updated September 6, 2017</p>
<hr></hr>
<p>A React/material-ui site</p>
</div>
);
}
}
export default Home; | import React, {Component} from "react";
import RaisedButton from "material-ui/RaisedButton";
const styles = {
button: {
margin: 12,
},
}
class Home extends Component {
render() {
return (
<div className="buttons">
<h1>Gregory N. Katchmar</h1>
<h2>JavaScript Developer</h2>
<hr></hr>
<h4>More information at:</h4>
<RaisedButton
href="https://www.linkedin.com/in/gregory-katchmar-3a48275a"
target="_blank"
label="LinkedIn"
primary={true}
style={styles.button}
/>
<RaisedButton
href="https://github.com/gnkatchmar"
target="_blank"
label="Github"
primary={true}
style={styles.button}
/>
<RaisedButton
href="https://drive.google.com/open?id=0B-QmArVwrgLGSHJnbFN6VXZGb0k"
target="_blank"
label="Resume (PDF)"
primary={true}
style={styles.button}
/>
<hr></hr>
<h4>Contact me at:</h4>
<a href="mailto:[email protected]">[email protected]</a>
<hr></hr>
<p>Last updated August 26, 2017</p>
<hr></hr>
<p>A React/material-ui site</p>
</div>
);
}
}
export default Home; |
Fix overlooked use case for workdir. | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyQueue(object):
def start(*args):
pass
def put(*args):
pass
def get(*args):
return None
class Actions(object):
def __init__(self, config):
if 'plotdir' not in config:
self.plotq = DummyQueue()
else:
logger.info('plots in {0} will be updated automatically'.format(config['plotdir']))
if 'foremen logs' in config:
logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs'])))
plotter = Plotter(config, config['plotdir'])
def plotf(q):
while q.get() not in ('stop', None):
plotter.make_plots(foremen=config.get('foremen logs'))
self.plotq = multiprocessing.Queue()
self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,))
self.plotp.start()
logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid))
self.__last = datetime.datetime.now()
def __del__(self):
self.plotq.put('stop')
def take(self):
now = datetime.datetime.now()
if (now - self.__last).seconds > 15 * 60:
self.plotq.put('plot')
self.__last = now
| import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyQueue(object):
def start(*args):
pass
def put(*args):
pass
def get(*args):
return None
class Actions(object):
def __init__(self, config):
if 'plotdir' not in config:
self.plotq = DummyQueue()
else:
logger.info('plots in {0} will be updated automatically'.format(config['plotdir']))
if 'foremen logs' in config:
logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs'])))
plotter = Plotter(config['workdir'], config['plotdir'])
def plotf(q):
while q.get() not in ('stop', None):
plotter.make_plots(foremen=config.get('foremen logs'))
self.plotq = multiprocessing.Queue()
self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,))
self.plotp.start()
logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid))
self.__last = datetime.datetime.now()
def __del__(self):
self.plotq.put('stop')
def take(self):
now = datetime.datetime.now()
if (now - self.__last).seconds > 15 * 60:
self.plotq.put('plot')
self.__last = now
|
Fix crash when requesting geocoder for invalid lat/lon coordinates | package org.owntracks.android.support;
import android.content.Context;
import android.location.Address;
import org.owntracks.android.injection.qualifier.AppContext;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import timber.log.Timber;
public class GeocoderGoogle implements Geocoder {
private static android.location.Geocoder geocoder;
@Override
public String reverse(double latitude, double longitude) {
if(!android.location.Geocoder.isPresent()) {
Timber.e("geocoder is not present");
return null;
}
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if ((addresses != null) && (addresses.size() > 0)) {
StringBuilder g = new StringBuilder();
Address a = addresses.get(0);
if (a.getAddressLine(0) != null)
g.append(a.getAddressLine(0));
return g.toString();
} else {
return "not available";
}
} catch (Exception e) {
return null;
}
}
GeocoderGoogle(@AppContext Context context){
geocoder = new android.location.Geocoder(context, Locale.getDefault());
}
}
| package org.owntracks.android.support;
import android.content.Context;
import android.location.Address;
import org.owntracks.android.injection.qualifier.AppContext;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import timber.log.Timber;
public class GeocoderGoogle implements Geocoder {
private static android.location.Geocoder geocoder;
@Override
public String reverse(double latitude, double longitude) {
if(!android.location.Geocoder.isPresent()) {
Timber.e("geocoder is not present");
return null;
}
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if ((addresses != null) && (addresses.size() > 0)) {
StringBuilder g = new StringBuilder();
Address a = addresses.get(0);
if (a.getAddressLine(0) != null)
g.append(a.getAddressLine(0));
return g.toString();
} else {
return "not available";
}
} catch (IOException e) {
return null;
}
}
GeocoderGoogle(@AppContext Context context){
geocoder = new android.location.Geocoder(context, Locale.getDefault());
}
}
|
Fix for text truncation where null or undefined descriptions are used. | (function () {
angular
.module('GVA.Common')
.directive('truncatedText', truncatedText);
truncatedText.$inject = ['$parse'];
function truncatedText($parse) {
function truncateText(text, limit) {
var words = text.split(' ');
var truncatedtext = words.reduce(function (prev, curr) {
if (curr.length + prev.length >= limit) {
return prev;
} else {
return prev + ' ' + curr;
}
});
return truncatedtext;
}
function link(scope, element, attrs) {
activate();
function activate() {
scope.maxChars = parseInt(scope.maxChars) || 160;
scope.fullText = '';
scope.truncatedText = '';
scope.$watch('ngModel', function () {
scope.fullText = scope.ngModel;
if (scope.fullText) {
scope.truncatedText = truncateText(scope.fullText, scope.maxChars);
scope.truncated = scope.fullText !== scope.truncatedText;
} else {
scope.truncated = false;
}
});
}
}
return {
restrict: 'A',
scope: {
ngModel: '=',
maxChars: '@',
},
link: link,
template: '<span ng-if="!truncated">{{fullText}}</span>' +
'<span ng-if="truncated">{{truncatedText}}</span>' +
'<span ng-show="truncated">... <a style="cursor:pointer" ng-click="truncated=false">Show More</a></span>'
};
}
})(); | (function () {
angular
.module('GVA.Common')
.directive('truncatedText', truncatedText);
truncatedText.$inject = ['$parse'];
function truncatedText($parse) {
function truncateText(text, limit) {
var words = text.split(' ');
var truncatedtext = words.reduce(function (prev, curr) {
if (curr.length + prev.length >= limit) {
return prev;
} else {
return prev + ' ' + curr;
}
});
return truncatedtext;
}
function link(scope, element, attrs) {
activate();
function activate() {
scope.maxChars = parseInt(scope.maxChars) || 160;
scope.fullText = '';
scope.truncatedText = '';
scope.$watch('ngModel', function () {
scope.fullText = scope.ngModel;
scope.truncatedText = truncateText(scope.fullText, scope.maxChars);
scope.truncated = scope.fullText !== scope.truncatedText;
});
}
}
return {
restrict: 'A',
scope: {
ngModel: '=',
maxChars: '@',
},
link: link,
template: '<span ng-if="!truncated">{{fullText}}</span>' +
'<span ng-if="truncated">{{truncatedText}}</span>' +
'<span ng-show="truncated">... <a style="cursor:pointer" ng-click="truncated=false">Show More</a></span>'
};
}
})(); |
Use LRUCache correctly (minimal improvement) | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return default
try:
return cache[key]
except KeyError:
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
| from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold = threshold
@property
def cache(self):
if not manager.stack:
return None
threadlocals = manager.stack[0]
if self.name not in threadlocals:
registry = threadlocals['registry']
capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
threadlocals[self.name] = LRUCache(capacity, self.threshold)
return threadlocals[self.name]
def get(self, key, default=None):
cache = self.cache
if cache is None:
return
cached = cache.get(key)
if cached is not None:
return cached[1]
return default
def __contains__(self, key):
cache = self.cache
if cache is None:
return False
return key in cache
def __setitem__(self, key, value):
cache = self.cache
if cache is None:
return
self.cache[key] = value
|
Make sure the opened workflow file gets closed after it's been loaded | #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
with open(args.workflow_path, 'r') as wf_file:
import_uuid = json.load(wf_file).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import argparse
from bioblend import galaxy
import json
def main():
"""
This script uses bioblend to import .ga workflow files into a running instance of Galaxy
"""
parser = argparse.ArgumentParser()
parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
parser.add_argument("-g", "--galaxy",
dest="galaxy_url",
help="Target Galaxy instance URL/IP address (required "
"if not defined in the tools list file)",)
parser.add_argument("-a", "--apikey",
dest="api_key",
help="Galaxy admin user API key (required if not "
"defined in the tools list file)",)
args = parser.parse_args()
gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)
import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
if import_uuid not in existing_uuids:
gi.workflows.import_workflow_from_local_path(args.workflow_path)
if __name__ == '__main__':
main()
|
Remove useless default from migration
- wal-26 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', default=1, to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
|
Fix logoutLink key in AJAX catch for Redux | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logoutLink: links.logout} // eslint-disable-line no-throw-literal
}
}
export const get = async url => {
try {
return await AJAX({
method: 'GET',
url,
})
} catch (error) {
console.error(error)
throw error
}
}
| import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
export const get = async url => {
try {
return await AJAX({
method: 'GET',
url,
})
} catch (error) {
console.error(error)
throw error
}
}
|
Change to empty port in hapi-auth-hawk | /**
* Created by Omnius on 6/15/16.
*/
'use strict';
const Boom = require('boom');
exports.register = (server, options, next) => {
server.auth.strategy('hawk-login-auth-strategy', 'hawk', {
getCredentialsFunc: (sessionId, callback) => {
const redis = server.app.redis;
const methods = server.methods;
const dao = methods.dao;
const userCredentialDao = dao.userCredentialDao;
userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => {
if (err) {
server.log(err);
return callback(Boom.serverUnavailable(err));
}
if (!Object.keys(dbCredentials).length) {
return callback(Boom.forbidden());
}
const credentials = {
hawkSessionToken: dbCredentials.hawkSessionToken,
algorithm: dbCredentials.algorithm,
userId: dbCredentials.userId,
key: dbCredentials.key,
id: dbCredentials.id
};
return callback(null, credentials);
});
},
hawk: {
port: ''
}
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
| /**
* Created by Omnius on 6/15/16.
*/
'use strict';
const Boom = require('boom');
exports.register = (server, options, next) => {
server.auth.strategy('hawk-login-auth-strategy', 'hawk', {
getCredentialsFunc: (sessionId, callback) => {
const redis = server.app.redis;
const methods = server.methods;
const dao = methods.dao;
const userCredentialDao = dao.userCredentialDao;
userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => {
if (err) {
server.log(err);
return callback(Boom.serverUnavailable(err));
}
if (!Object.keys(dbCredentials).length) {
return callback(Boom.forbidden());
}
const credentials = {
hawkSessionToken: dbCredentials.hawkSessionToken,
algorithm: dbCredentials.algorithm,
userId: dbCredentials.userId,
key: dbCredentials.key,
id: dbCredentials.id
};
return callback(null, credentials);
});
},
hawk: {
port: 443
}
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
Fix loaded page name is empty | <?php
class Loader
{
private $instance = array();
public function page($name, $method='index')
{
if ($name==='')
{
$name = 'home';
}
$page = $this->loadClass($name, 'Page');
if ($page === false || method_exists($page, $method) === false)
{
not_found();
}
else
{
$page->$method();
}
}
private function loadFile($name, $package='library', $data=array())
{
$vendors =& loadClass('Vendor', 'Core');
$list = $vendors->lists();
foreach ($list as $vendor)
{
if (file_exists($vendor . '/' . $package . '/' . $name . '.php'))
{
include ($vendor . '/' . $package . '/' . $name . '.php');
return true;
}
}
return false;
}
private function loadClass($name, $package='library')
{
$package = strtolower($package);
$name = strtolower($name);
if (isset($this->instance[$package]) && isset($this->instance[$package][$name]))
{
return $this->instance[$package][$name];
}
$hasFile = $this->loadFile($name, $package);
if ($hasFile === false || class_exists($name) === false)
{
return false;
}
$class = new $name();
$this->instance[$package][$name] = $class;
return $class;
}
}
?>
| <?php
class Loader
{
private $instance = array();
public function page($name, $method='index')
{
$page = $this->loadClass($name, 'Page');
if ($page === false || method_exists($page, $method) === false)
{
not_found();
}
else
{
$page->$method();
}
}
private function loadFile($name, $package='library', $data=array())
{
$vendors =& loadClass('Vendor', 'Core');
$list = $vendors->lists();
foreach ($list as $vendor)
{
if (file_exists($vendor . '/' . $package . '/' . $name . '.php'))
{
include ($vendor . '/' . $package . '/' . $name . '.php');
return true;
}
}
return false;
}
private function loadClass($name, $package='library')
{
$package = strtolower($package);
$name = strtolower($name);
if (isset($this->instance[$package]) && isset($this->instance[$package][$name]))
{
return $this->instance[$package][$name];
}
$hasFile = $this->loadFile($name, $package);
if ($hasFile === false || class_exists($name) === false)
{
return false;
}
$class = new $name();
$this->instance[$package][$name] = $class;
return $class;
}
}
?>
|
Remove some complexity caused by refactorings | <?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
array(
new RoutedApplication(
array(
array('POST', '/form', $html)))));
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
private function filterNotEmpty($html, $filter)
{
$crawler = new Crawler($html);
return $crawler->filter($filter)->count() > 0;
}
private function responseBodyHasClass($response, $class)
{
return $this->filterNotEmpty($response['body'], $class);
}
public function testFormErrorShouldBeShown()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, '.error'));
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
}
}
| <?php
namespace Lily\Test\Usage;
use Symfony\Component\DomCrawler\Crawler;
use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;
use Lily\Util\Request;
use Lily\Util\Response;
class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
private function applicationToTest()
{
$html = file_get_contents(dirname(__FILE__).'/example.html');
return
new MiddlewareApplication(
array(
new RoutedApplication(
array(
array('POST', '/form', $html)))));
}
private function applicationResponse($request)
{
$application = $this->applicationToTest();
return $application($request);
}
private function crawler($html)
{
return new Crawler($html);
}
private function filterNotEmpty($crawler, $filter)
{
return $crawler->filter($filter)->count() > 0;
}
private function responseBodyHasClass($response, $class)
{
return $this->filterNotEmpty($this->crawler($response['body']), $class);
}
public function testFormErrorShouldBeShown()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, '.error'));
}
public function testFormShouldSuccessfullySubmit()
{
$response = $this->applicationResponse(Request::post('/form'));
$this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
}
}
|
Fix rendering an article list | import React from 'react';
import ArticleShort from '../articleShort.react';
import ArticleStore from '../../stores/ArticleStore';
import PageCount from './PageCount.react';
export default class List extends React.Component {
constructor(props) {
super(props);
self.displayName = 'ArticleList';
this.state = {
offset: 0,
limit: 10,
articles: []
};
}
componentDidMount() {
ArticleStore.getList(
this,
this.state.offset,
this.state.limit
);
}
render() {
var article = 'undefined',
index = 'undefined',
rendered = [];
for (index in this.state.articles) {
if (this.state.articles.hasOwnProperty(index)) {
article = this.state.articles[index];
rendered.push(
<ArticleShort
createdAt={article.createdAt}
id={article.id}
key={article.id}
slug={article.slug}
title={article.title}
/>
);
}
}
return (
<div>
<h1 className="text-center">
{'Articles'}<br />
<small>
<PageCount
limit={this.state.limit}
offset={this.state.offset}
/>
</small>
</h1>
{rendered}
</div>
);
}
}
| import React from 'react';
import ArticleShort from '../articleShort.react';
import ArticleStore from '../../stores/ArticleStore';
import PageCount from './PageCount.react';
export default class List extends React.Component {
constructor(props) {
super(props);
self.displayName = 'ArticleList';
self.state = {
offset: 0,
limit: 10,
articles: undefined // eslint-disable-line no-undefined
};
}
componentDidMount() {
ArticleStore.getList(
this,
this.state.offset,
this.state.limit
);
}
render() {
var article = 'undefined',
index = 'undefined',
rendered = [];
for (index in this.state.articles) {
if (this.state.articles.hasOwnProperty(index)) {
article = this.state.articles[index];
rendered.push(
<ArticleShort
createdAt={article.createdAt}
id={article.id}
key={article.id}
slug={article.slug}
title={article.title}
/>
);
}
}
return (
<div>
<h1 className="text-center">
{'Articles'}<br />
<small>
<PageCount
limit={this.state.limit}
offset={this.state.offset}
/>
</small>
</h1>
{rendered}
</div>
);
}
}
|
Use different blog for test data. | from . import google_drive
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import cStringIO
import csv
import json
import unittest
import yaml
class BloggerTestCase(testing.TestCase):
def test_run(self):
pod = testing.create_pod()
fields = {
'preprocessors': [{
'name': 'blogger',
'kind': 'blogger',
'blog_id': '4154157974596966834',
'collection': '/content/posts/',
'markdown': True,
'authenticated': False,
'inject': True,
}],
}
pod.write_yaml('/podspec.yaml', fields)
fields = {
'$path': '/{date}/{slug}/',
'$view': '/views/base.html',
}
pod.write_yaml('/content/posts/_blueprint.yaml', fields)
content = '{{doc.html|safe}}'
pod.write_file('/views/base.html', content)
# Weak test to verify preprocessor runs.
pod.preprocess(['blogger'])
# Verify inject.
collection = pod.get_collection('/content/posts')
doc = collection.docs()[0]
preprocessor = pod.list_preprocessors()[0]
preprocessor.inject(doc)
if __name__ == '__main__':
unittest.main()
| from . import google_drive
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import cStringIO
import csv
import json
import unittest
import yaml
class BloggerTestCase(testing.TestCase):
def test_run(self):
pod = testing.create_pod()
fields = {
'preprocessors': [{
'name': 'blogger',
'kind': 'blogger',
'blog_id': '10861780', # Official Google blog.
'collection': '/content/posts/',
'markdown': True,
'authenticated': False,
'inject': True,
}],
}
pod.write_yaml('/podspec.yaml', fields)
fields = {
'$path': '/{date}/{slug}/',
'$view': '/views/base.html',
}
pod.write_yaml('/content/posts/_blueprint.yaml', fields)
content = '{{doc.html|safe}}'
pod.write_file('/views/base.html', content)
# Weak test to verify preprocessor runs.
pod.preprocess(['blogger'])
# Verify inject.
collection = pod.get_collection('/content/posts')
doc = collection.docs()[0]
preprocessor = pod.list_preprocessors()[0]
preprocessor.inject(doc)
if __name__ == '__main__':
unittest.main()
|
Make this into a partial to get the protocol correctly. | """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
from kyokai.context import HTTPRequestContext
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):
assert check_argument_types()
if not isinstance(app, Kyokai):
self.app = resolve_reference(app)
else:
self.app = app
self.ip = ip
self.port = port
self._extra_cfg = cfg
# Set HTTPRequestContext's `cfg` val to the extra config.
HTTPRequestContext.cfg = self._extra_cfg
self.server = None
self.app.reconfigure(cfg)
def get_protocol(self, ctx: Context):
return KyokaiProtocol(self.app, ctx)
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol = partial(self.get_protocol, ctx)
self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
| """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
from kyokai.context import HTTPRequestContext
logger = logging.getLogger("Kyokai")
class KyoukaiComponent(Component):
def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):
assert check_argument_types()
if not isinstance(app, Kyokai):
self.app = resolve_reference(app)
else:
self.app = app
self.ip = ip
self.port = port
self._extra_cfg = cfg
# Set HTTPRequestContext's `cfg` val to the extra config.
HTTPRequestContext.cfg = self._extra_cfg
self.server = None
self.app.reconfigure(cfg)
def get_protocol(self, ctx: Context):
return KyokaiProtocol(self.app, ctx)
async def start(self, ctx: Context):
"""
Starts a Kyokai server.
"""
protocol = self.get_protocol(ctx)
self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)
logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))
|
Add 3 second delay to application submission | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import api from 'api'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
static propTypes = {
status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired,
applicationId: PropTypes.number.isRequired,
callback: PropTypes.func
}
state = {
loading: false
}
handleSubmit = () => {
const { status, applicationId, callback } = this.props
this.setState({ loading: true })
if (status !== 'complete') return null
// NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation
setTimeout(() => {
api
.post(`v1/new_club_applications/${applicationId}/submit`)
.then(json => {
callback(json)
})
.catch(e => {
alert(e.statusText)
})
.finally(_ => {
this.setState({ loading: false })
})
}, 3000)
}
render() {
const { status } = this.props
const { loading } = this.state
return (
<LargeButton
onClick={this.handleSubmit}
bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'}
disabled={status !== 'complete' || loading}
w={1}
mt={2}
mb={4}
f={3}
children={
status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'
}
/>
)
}
}
export default SubmitButton
| import React, { Component } from 'react'
import PropTypes from 'prop-types'
import api from 'api'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
static propTypes = {
status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired,
applicationId: PropTypes.number.isRequired,
callback: PropTypes.func
}
state = {
loading: false
}
handleSubmit = () => {
const { status, applicationId, callback } = this.props
this.setState({ loading: true })
// NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation
if (status !== 'complete') return null
const startTime = Time.now
api
.post(`v1/new_club_applications/${applicationId}/submit`)
.then(json => {
callback(json)
})
.catch(e => {
alert(e.statusText)
})
.finally(_ => {
this.setState({ loading: false })
})
}
render() {
const { status } = this.props
const { loading } = this.state
return (
<LargeButton
onClick={this.handleSubmit}
bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'}
disabled={status !== 'complete' || loading}
w={1}
mt={2}
mb={4}
f={3}
children={
status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'
}
/>
)
}
}
export default SubmitButton
|
Fix bug with exists property | <?php namespace ThibaudDauce\MoloquentInheritance;
use ReflectionClass;
trait MoloquentInheritanceTrait {
public $parentClasses;
/**
* Boot the moloquent inheritance for a model.
*
* @return void
*/
public static function bootMoloquentInheritanceTrait()
{
static::addGlobalScope(new MoloquentInheritanceScope);
}
/**
* Fill the model with an array of attributes.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return $this
*
* @throws MassAssignmentException
*/
public function fill(array $attributes)
{
$this->setParentClasses();
return parent::fill($attributes);
}
public function getParentClasses() {
$reflection = new ReflectionClass($this);
$classes = [$reflection->getName()];
while ($reflection->getName() !== get_class()) {
$reflection = $reflection->getParentClass();
$classes[] = $reflection->getName();
}
return $classes;
}
public function setParentClasses() {
$this->attributes['parent_classes'] = $this->getParentClasses();
}
/**
* Create a new model instance that is existing.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = array())
{
$class = $attributes['parent_classes'][0];
$instance = new $class;
$instance = $instance->newInstance(array(), true);
$instance->setRawAttributes((array) $attributes);
return $instance;
}
}
| <?php namespace ThibaudDauce\MoloquentInheritance;
use ReflectionClass;
trait MoloquentInheritanceTrait {
public $parentClasses;
/**
* Boot the moloquent inheritance for a model.
*
* @return void
*/
public static function bootMoloquentInheritanceTrait()
{
static::addGlobalScope(new MoloquentInheritanceScope);
}
/**
* Fill the model with an array of attributes.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return $this
*
* @throws MassAssignmentException
*/
public function fill(array $attributes)
{
$this->setParentClasses();
return parent::fill($attributes);
}
public function getParentClasses() {
$reflection = new ReflectionClass($this);
$classes = [$reflection->getName()];
while ($reflection->getName() !== get_class()) {
$reflection = $reflection->getParentClass();
$classes[] = $reflection->getName();
}
return $classes;
}
public function setParentClasses() {
$this->attributes['parent_classes'] = $this->getParentClasses();
}
/**
* Create a new model instance that is existing.
*
* @override Illuminate\Database\Eloquent\Model
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = array())
{
$class = $attributes['parent_classes'][0];
if ($this instanceof $class)
return parent::newFromBuilder($attributes);
$instance = new $class;
$instance->newFromBuilder((array) $attributes);
return $instance;
}
}
|
Call the CM to mask stderr output properly | import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err_output():
current_err = sys.stderr
try:
sys.stderr = sys.stdout
yield
finally:
sys.stderr = current_err
class ArgumentTests(unittest.TestCase):
def setUp(self):
self.null_plugin = PluginModule()
def create_action_map(self):
self.action_map = dict((cls.name, cls) for cls in get_modules(kafka.tools.assigner.actions, kafka.tools.assigner.actions.ActionModule))
def test_get_arguments_none(self):
sys.argv = ['kafka-assigner']
with redirect_err_output():
self.assertRaises(SystemExit, set_up_arguments, {}, {}, [self.null_plugin])
def test_get_modules(self):
self.create_action_map()
assert 'elect' in self.action_map
assert inspect.isclass(self.action_map['elect'])
def test_get_arguments_minimum(self):
self.create_action_map()
sys.argv = ['kafka-assigner', '--zookeeper', 'zkhost1.example.com:2181', 'elect']
args = set_up_arguments(self.action_map, {}, [self.null_plugin])
assert args.action == 'elect'
| import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err_output():
current_err = sys.stderr
try:
sys.stderr = sys.stdout
yield
finally:
sys.stderr = current_err
class ArgumentTests(unittest.TestCase):
def setUp(self):
self.null_plugin = PluginModule()
def create_action_map(self):
self.action_map = dict((cls.name, cls) for cls in get_modules(kafka.tools.assigner.actions, kafka.tools.assigner.actions.ActionModule))
def test_get_arguments_none(self):
sys.argv = ['kafka-assigner']
with capture_sys_output() as (stdout, stderr):
self.assertRaises(SystemExit, set_up_arguments, {}, {}, [self.null_plugin])
def test_get_modules(self):
self.create_action_map()
assert 'elect' in self.action_map
assert inspect.isclass(self.action_map['elect'])
def test_get_arguments_minimum(self):
self.create_action_map()
sys.argv = ['kafka-assigner', '--zookeeper', 'zkhost1.example.com:2181', 'elect']
args = set_up_arguments(self.action_map, {}, [self.null_plugin])
assert args.action == 'elect'
|
Fix lv2 effect builder for travis build | import os
import json
from pluginsmanager.model.lv2.lv2_plugin import Lv2Plugin
from pluginsmanager.model.lv2.lv2_effect import Lv2Effect
class Lv2EffectBuilder(object):
"""
Generates lv2 audio plugins instance (as :class:`Lv2Effect` object).
.. note::
In the current implementation, the data plugins are persisted
in *plugins.json*.
"""
def __init__(self, plugins_json=None):
self.plugins = {}
if plugins_json is None:
plugins_json = os.path.dirname(__file__) + '/plugins.json'
with open(plugins_json) as data_file:
data = json.load(data_file)
#supported_plugins = self._supported_plugins
for plugin in data:
# if plugin['uri'] in supported_plugins:
self.plugins[plugin['uri']] = Lv2Plugin(plugin)
@property
def _supported_plugins(self):
import subprocess
return str(subprocess.check_output(['lv2ls'])).split('\\n')
@property
def all(self):
return self.plugins
def build(self, lv2_uri):
"""
Returns a new :class:`Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created
"""
return Lv2Effect(self.plugins[lv2_uri])
| import os
import json
from pluginsmanager.model.lv2.lv2_plugin import Lv2Plugin
from pluginsmanager.model.lv2.lv2_effect import Lv2Effect
class Lv2EffectBuilder(object):
"""
Generates lv2 audio plugins instance (as :class:`Lv2Effect` object).
.. note::
In the current implementation, the data plugins are persisted
in *plugins.json*.
"""
def __init__(self, plugins_json=None):
self.plugins = {}
if plugins_json is None:
plugins_json = os.path.dirname(__file__) + '/plugins.json'
with open(plugins_json) as data_file:
data = json.load(data_file)
supported_plugins = self._supported_plugins
for plugin in data:
if plugin['uri'] in supported_plugins:
self.plugins[plugin['uri']] = Lv2Plugin(plugin)
@property
def _supported_plugins(self):
import subprocess
return str(subprocess.check_output(['lv2ls'])).split('\\n')
@property
def all(self):
return self.plugins
def build(self, lv2_uri):
"""
Returns a new :class:`Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created
"""
return Lv2Effect(self.plugins[lv2_uri])
|
Fix the media manual updates unit test to account for the new ext dir page.
My previous change for the extension directory manual updates page broke
the unit tests. The existing test for the upload directory didn't take
into account that the extension directory would also now be needed. The
test was fixed and renamed to signify that it checks for media dirs now. | from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def testManualUpdatesRequired(self):
"""Testing check_updates_required with valid configuration"""
# NOTE: This is assuming the install is fine. It should be given
# that we set things like the uploaded path correctly to
# a known good directory before starting unit tests.
updates_required = checks.check_updates_required()
self.assertEqual(len(updates_required), 0)
def testManualUpdatesRequiredBadMediaDirs(self):
"""Testing check_updates_required with bad media directories"""
old_media_root = settings.MEDIA_ROOT
settings.MEDIA_ROOT = "/"
checks.reset_check_cache()
updates_required = checks.check_updates_required()
settings.MEDIA_ROOT = old_media_root
# Should complain about ext and upload directories.
self.assertEqual(len(updates_required), 2)
url, data = updates_required[0]
self.assertEqual(url, "admin/manual-updates/media-upload-dir.html")
url, data = updates_required[1]
self.assertEqual(url, "admin/manual-updates/ext-dir.html")
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "admin/manual_updates_required.html")
| from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def testManualUpdatesRequired(self):
"""Testing check_updates_required with valid configuration"""
# NOTE: This is assuming the install is fine. It should be given
# that we set things like the uploaded path correctly to
# a known good directory before starting unit tests.
updates_required = checks.check_updates_required()
self.assertEqual(len(updates_required), 0)
def testManualUpdatesRequiredBadUpload(self):
"""Testing check_updates_required with a bad upload directory"""
old_media_root = settings.MEDIA_ROOT
settings.MEDIA_ROOT = "/"
checks.reset_check_cache()
updates_required = checks.check_updates_required()
settings.MEDIA_ROOT = old_media_root
self.assertEqual(len(updates_required), 1)
url, data = updates_required[0]
self.assertEqual(url, "admin/manual-updates/media-upload-dir.html")
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "admin/manual_updates_required.html")
|
fix(redux): Clear board on new request | import * as types from '../types'
import initialState from '../initialState';
import { createReducer, mergeState } from '~/utils/redux';
export default createReducer(initialState.board, {
[types.BOARD_REQUESTED]: (state, action) =>
mergeState(state, {
isFetching: true,
didInvalidate: false,
posts: []
}),
[types.BOARD_LOADED]: (state, action) =>
mergeState(state, {
posts: action.posts,
receivedAt: action.receivedAt,
isFetching: false
}),
[types.BOARD_INVALIDATED]: (state, action) =>
mergeState(state, {
didInvalidate: true
}),
[types.BOARD_DESTROYED]: (state, action) =>
mergeState(state, {
posts: []
}),
[types.BOARD_FILTER_ADDED]: (state, action) =>
mergeState(state, {
filterWords: [
...state.filterWords,
action.payload
]
}),
[types.REMOVE_FILTER]: (state, action) =>
mergeState(state, {
filterWords: state.filterWords.filter(word => {
action.payload !== word
})
}),
[types.BOARD_CACHE_LOADED]: (state, action) =>
mergeState(state, action.payload),
[types.BOARD_SEARCHED]: (state, action) =>
mergeState(state, {
search: action.payload || null
}),
[types.BOARD_SCROLLED_TO_BOTTOM]: (state, action) =>
mergeState(state, {
limit: action.payload
}),
})
| import * as types from '../types'
import initialState from '../initialState';
import { createReducer, mergeState } from '~/utils/redux';
export default createReducer(initialState.board, {
[types.BOARD_REQUESTED]: (state, action) =>
mergeState(state, {
isFetching: true,
didInvalidate: false
}),
[types.BOARD_LOADED]: (state, action) =>
mergeState(state, {
posts: action.posts,
receivedAt: action.receivedAt,
isFetching: false
}),
[types.BOARD_INVALIDATED]: (state, action) =>
mergeState(state, {
didInvalidate: true
}),
[types.BOARD_DESTROYED]: (state, action) =>
mergeState(state, {
posts: []
}),
[types.BOARD_FILTER_ADDED]: (state, action) =>
mergeState(state, {
filterWords: [
...state.filterWords,
action.payload
]
}),
[types.REMOVE_FILTER]: (state, action) =>
mergeState(state, {
filterWords: state.filterWords.filter(word => {
action.payload !== word
})
}),
[types.BOARD_CACHE_LOADED]: (state, action) =>
mergeState(state, action.payload),
[types.BOARD_SEARCHED]: (state, action) =>
mergeState(state, {
search: action.payload || null
}),
[types.BOARD_SCROLLED_TO_BOTTOM]: (state, action) =>
mergeState(state, {
limit: action.payload
}),
})
|
Increase the unit test coverage for the binary search tree | import unittest
from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree
class BinarySearchTreeUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
bst = BinarySearchTree.create()
bst.put("one", 1)
bst.put("two", 2)
bst.put("three", 3)
bst.put("six", 6)
bst.put("ten", 10)
bst.put("ten", 10)
self.assertEqual(1, bst.get("one"))
self.assertEqual(2, bst.get("two"))
self.assertEqual(3, bst.get("three"))
self.assertTrue(bst.contains_key("one"))
self.assertTrue(bst.contains_key("two"))
self.assertEqual(5, bst.size())
self.assertFalse(bst.is_empty())
bst.delete("one")
self.assertFalse(bst.contains_key("one"))
self.assertEqual(4, bst.size())
bst.delete("ten")
self.assertFalse(bst.contains_key("ten"))
self.assertEqual(3, bst.size())
bst.delete("three")
self.assertFalse(bst.contains_key("three"))
self.assertEqual(2, bst.size())
for i in range(100):
bst.put(str(i), i)
self.assertEqual(i, bst.get(str(i)))
for i in range(100):
bst.delete(str(i))
self.assertFalse(bst.contains_key(str(i)))
if __name__ == '__main__':
unittest.main() | import unittest
from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree
class BinarySearchTreeUnitTest(unittest.TestCase):
def test_binarySearchTree(self):
bst = BinarySearchTree.create()
bst.put("one", 1)
bst.put("two", 2)
bst.put("three", 3)
bst.put("six", 6)
bst.put("ten", 10)
self.assertEqual(1, bst.get("one"))
self.assertEqual(2, bst.get("two"))
self.assertEqual(3, bst.get("three"))
self.assertTrue(bst.contains_key("one"))
self.assertTrue(bst.contains_key("two"))
self.assertEqual(5, bst.size())
self.assertFalse(bst.is_empty())
bst.delete("one")
self.assertFalse(bst.contains_key("one"))
self.assertEqual(4, bst.size())
bst.delete("ten")
self.assertFalse(bst.contains_key("ten"))
self.assertEqual(3, bst.size())
bst.delete("three")
self.assertFalse(bst.contains_key("three"))
self.assertEqual(2, bst.size())
if __name__ == '__main__':
unittest.main() |
Change version number to 0.2.x | /**
* Configuration for denkmap application
*/
Ext.define('Denkmap.util.Config', {
singleton: true,
config: {
/**
* @cfg {String} version Current version number of application
**/
version: '0.2.{BUILD_NR}',
leafletMap: {
zoom: 15,
getTileLayerUrl: function(isRetina) {
if(isRetina) {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}@2x/256/{z}/{x}/{y}.png';
} else {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}/256/{z}/{x}/{y}.png';
}
},
tileLayerAttribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> and © <a href="http://www.geolion.zh.ch/geodatenservice/show?nbid=691">Geodaten GIS-ZH</a>',
apiKey: '14f1a83f16604a708a4876a956f9dd35',
styleId: 997
}
},
/**
* @private
* initializes the configuration
*/
constructor: function(config) {
this.initConfig(config);
return this;
}
});
| /**
* Configuration for denkmap application
*/
Ext.define('Denkmap.util.Config', {
singleton: true,
config: {
/**
* @cfg {String} version Current version number of application
**/
version: '0.1.{BUILD_NR}',
leafletMap: {
zoom: 15,
getTileLayerUrl: function(isRetina) {
if(isRetina) {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}@2x/256/{z}/{x}/{y}.png';
} else {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}/256/{z}/{x}/{y}.png';
}
},
tileLayerAttribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> and © <a href="http://www.geolion.zh.ch/geodatenservice/show?nbid=691">Geodaten GIS-ZH</a>',
apiKey: '14f1a83f16604a708a4876a956f9dd35',
styleId: 997
}
},
/**
* @private
* initializes the configuration
*/
constructor: function(config) {
this.initConfig(config);
return this;
}
});
|
Change timestamps columns to protected | <?php namespace Maatwebsite\Usher\Traits;
use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt;
use Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt;
trait Timestamps
{
/**
* @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt", columnPrefix=false)
* @var CreatedAt
*/
protected $createdAt;
/**
* @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt", columnPrefix=false)
* @var UpdatedAt
*/
protected $updatedAt;
/**
* @ORM\PrePersist
*/
public function prePersist()
{
$this->setCreatedAt(
new CreatedAt
);
$this->setUpdatedAt(
new UpdatedAt
);
}
/**
* @ORM\PreUpdate
*/
public function preUpdate()
{
$this->setUpdatedAt(
new UpdatedAt
);
}
/**
* @return CreatedAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param CreatedAt $createdAt
*/
public function setCreatedAt(CreatedAt $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return UpdatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param UpdatedAt $updatedAt
*/
public function setUpdatedAt(UpdatedAt $updatedAt)
{
$this->updatedAt = $updatedAt;
}
}
| <?php namespace Maatwebsite\Usher\Traits;
use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt;
use Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt;
trait Timestamps
{
/**
* @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\CreatedAt", columnPrefix=false)
* @var CreatedAt
*/
private $createdAt;
/**
* @ORM\Embedded(class = "Maatwebsite\Usher\Domain\Shared\Embeddables\UpdatedAt", columnPrefix=false)
* @var UpdatedAt
*/
private $updatedAt;
/**
* @ORM\PrePersist
*/
public function prePersist()
{
$this->setCreatedAt(
new CreatedAt
);
$this->setUpdatedAt(
new UpdatedAt
);
}
/**
* @ORM\PreUpdate
*/
public function preUpdate()
{
$this->setUpdatedAt(
new UpdatedAt
);
}
/**
* @return CreatedAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param CreatedAt $createdAt
*/
public function setCreatedAt(CreatedAt $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return UpdatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param UpdatedAt $updatedAt
*/
public function setUpdatedAt(UpdatedAt $updatedAt)
{
$this->updatedAt = $updatedAt;
}
}
|
Allow user creation from script. | <?php
namespace solutionweb\gatekeeper\utils\commands;
/**
* Command to create a user.
*
* @author Bert Peters <[email protected]>
*/
class CreateUserCommand extends GatekeeperCommand
{
protected $commandInformation = [
"description" => "Create a new user.",
"options" => [
"noactivate" => [
"optional" => true,
"description" => "Do not activate the user by default.",
],
"username" => [
"optional" => true,
"description" => "username to create. Will prompt if not present.",
],
"email" => [
"optional" => true,
"description" => "email to use. Will prompt if not present.",
],
"password" => [
"optional" => true,
"description" => "password to use. Will prompt if not present.",
],
],
];
/**
* Create a user.
*
* @param boolean|string $noactivate
*/
public function execute($noactivate = false, $password = null, $username = null, $email = null)
{
if ($username == null) {
$username = $this->question("Username");
}
if ($email == null) {
$email = $this->question("Email");
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error("Invalid email supplied.");
return;
}
}
if ($password == null) {
$password = $this->secret("Password", null, false);
if ($password != $this->secret("Repeat", null, true)) {
$this->error("Passwords do not match.");
return;
}
}
$user = $this->gatekeeper->createUser($email, $username, $password, !$noactivate);
$this->write("User " . $user->getId() . " created.");
}
}
| <?php
namespace solutionweb\gatekeeper\utils\commands;
/**
* Command to create a user.
*
* @author Bert Peters <[email protected]>
*/
class CreateUserCommand extends GatekeeperCommand
{
protected $commandInformation = [
"description" => "Create a new user.",
"options" => [
"noactivate" => [
"optional" => true,
"description" => "Do not activate the user by default.",
],
],
];
/**
* Create a user.
*
* @param boolean|string $noactivate
*/
public function execute($noactivate = false)
{
$username = $this->question("Username");
$email = $this->question("Email");
$password = $this->secret("Password", null, false);
if ($password != $this->secret("Repeat", null, true)) {
$this->error("Passwords do not match.");
return;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error("Invalid email supplied.");
return;
}
$user = $this->gatekeeper->createUser($email, $username, $password, !$noactivate);
$this->write("User " . $user->getId() . " created.");
}
}
|
Fix NameError: name 'README' is not defined
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/tmp/pip-g43cf6a2-build/setup.py", line 9, in <module>
long_description=README,
NameError: name 'README' is not defined | #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=(
'Simple app that works similar to wagtailimages,'
'but for embedding YouTube and Vimeo videos and music from SoundCloud. '
'It's an integration of django-embed-video.'
)
author='Diogo Marques',
author_email='[email protected]',
maintainer='Diogo Marques',
maintainer_email='[email protected]',
url='https://github.com/infoportugal/wagtail-embedvideos',
packages=['wagtail_embed_videos', 'wagtail_embed_videos.views'],
package_data={'wagtail_embed_videos': ['static/wagtail_embed_videos/js/*.js']},
requires=['django(>=1.7)', 'wagtail(>=1.0)', 'django-embed-video(>=1.0)'],
install_requires=['wagtail', 'django-embed-video'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Wagtail CMS',
'License :: OSI Approved :: BSD License'],
license='New BSD',
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=README,
author='Diogo Marques',
author_email='[email protected]',
maintainer='Diogo Marques',
maintainer_email='[email protected]',
url='https://github.com/infoportugal/wagtail-embedvideos',
packages=['wagtail_embed_videos', 'wagtail_embed_videos.views'],
package_data={'wagtail_embed_videos': ['static/wagtail_embed_videos/js/*.js']},
requires=['django(>=1.7)', 'wagtail(>=1.0)', 'django-embed-video(>=1.0)'],
install_requires=['wagtail', 'django-embed-video'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Wagtail CMS',
'License :: OSI Approved :: BSD License'],
license='New BSD',
)
|
Add Default Value For Timepicker When Focus | let React = require("react")
let cx = require("classnames")
let {Focusable} = require("frig").HigherOrderComponents
let popup = React.createFactory(require("./timepicker_popup"))
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {savedNotification} = require("../util.js")
let {div, input} = React.DOM
@Focusable
export default class extends React.Component {
displayName = "Frig.friggingBootstrap.TimePicker"
static defaultProps = Object.assign(require("../default_props.js"))
_inputCx() {
return cx(
this.props.inputHtml.className,
"frigb-timepicker-input",
"form-control",
)
}
_input() {
return input(Object.assign({}, this.props.inputHtml, {
valueLink: this.props.valueLink,
className: this._inputCx(),
onFocus: () => {
return this.props.valueLink.requestChange(
this.props.valueLink.value || "12:00pm"
)
},
})
)
}
_timePopup() {
if(this.props.focused === false) return
return popup({
valueLink: this.props.valueLink,
})
}
render() {
return div({className: cx(sizeClassNames(this.props))},
div({className: formGroupCx(this.props)},
div({}, label(this.props)),
this._input(),
savedNotification({parentProps: this.props}),
errorList(this.props.errors),
),
this._timePopup(),
)
}
}
| let React = require("react")
let cx = require("classnames")
let {Focusable} = require("frig").HigherOrderComponents
let popup = React.createFactory(require("./timepicker_popup"))
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {savedNotification} = require("../util.js")
let {div, input} = React.DOM
@Focusable
export default class extends React.Component {
displayName = "Frig.friggingBootstrap.TimePicker"
static defaultProps = Object.assign(require("../default_props.js"))
_inputCx() {
return cx(
this.props.inputHtml.className,
"frigb-timepicker-input",
"form-control",
)
}
_input() {
return input(Object.assign({}, this.props.inputHtml, {
valueLink: this.props.valueLink,
className: this._inputCx(),
})
)
}
_timePopup() {
if(this.props.focused === false) return
return popup({
valueLink: this.props.valueLink,
})
}
render() {
return div({className: cx(sizeClassNames(this.props))},
div({className: formGroupCx(this.props)},
div({}, label(this.props)),
this._input(),
savedNotification({parentProps: this.props}),
errorList(this.props.errors),
),
this._timePopup(),
)
}
}
|
Add input for reject application | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateApplicationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('applications', function (Blueprint $table) {
$table->uuid('id')->unique();
$table->primary('id');
$table->uuid('userid');
$table->foreign('userid')->references('id')->on('users')->onDelete('cascade');
$table->uuid('employerid');
$table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');
$table->uuid('jobid');
$table->foreign('jobid')->references('id')->on('jobs')->onDelete('cascade');
$table->text('message');
$table->boolean('rejected')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
Schema::dropIfExists('applicants');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateApplicationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('applications', function (Blueprint $table) {
$table->uuid('id')->unique();
$table->primary('id');
$table->uuid('userid');
$table->foreign('userid')->references('id')->on('users')->onDelete('cascade');
$table->uuid('employerid');
$table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');
$table->uuid('jobid');
$table->foreign('jobid')->references('id')->on('jobs')->onDelete('cascade');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
Schema::dropIfExists('applicants');
});
}
}
|
Fix Tiny MCE menu bug | <?php
namespace PHPOrchestra\BackofficeBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class TinymceCompilerPass
*/
class TinymceCompilerPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
if ($container->hasDefinition('twig.extension.stfalcon_tinymce')) {
$param = $container->getParameter('stfalcon_tinymce.config');
$param['tinymce_jquery'] = false;
$param['include_jquery'] = false;
$param['selector'] = ".tinymce";
$param['theme'] = array(
'simple' => array(
"theme" => "modern",
"plugins" => array(
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor"
),
"toolbar1" => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
"toolbar2" => "print preview | forecolor backcolor",
"menubar" => false,
)
);
$container->setParameter('stfalcon_tinymce.config', $param);
}
}
}
| <?php
namespace PHPOrchestra\BackofficeBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class TinymceCompilerPass
*/
class TinymceCompilerPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
if ($container->hasDefinition('twig.extension.stfalcon_tinymce')) {
$param = $container->getParameter('stfalcon_tinymce.config');
$param['tinymce_jquery'] = false;
$param['include_jquery'] = false;
$param['selector'] = ".tinymce";
$param['theme'] = array(
'simple' => array(
"theme" => "modern",
"plugins" => array(
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor"
),
"toolbar1" => "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link",
"toolbar2" => "print preview | forecolor backcolor",
"menubar" => false,
"image_advtab" => true,
)
);
$container->setParameter('stfalcon_tinymce.config', $param);
}
}
}
|
Set mocha tests timeout to 5s. | 'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
},
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout: 5000
},
src: ['test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'mochaTest']
}
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'mochaTest']);
grunt.registerTask('test', ['jshint:test','mochaTest']);
};
| 'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'mochaTest']
}
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'mochaTest']);
grunt.registerTask('test', ['jshint:test','mochaTest']);
};
|
Fix bug where hasSentResponse would not be reset stalling further requests. | var express = require('express');
function createMethodWrapper(app, verb) {
var original = app[verb];
return function (route, handler) {
original.call(app, route, function (req, res, next) {
// must be places here in order that it is cleared on every request
var hasSentResponse = false;
handler(req, {
setHeader: function () {
// empty
},
send: function(statusCode, body) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
res.send(statusCode, body);
}
}, function _next(err) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
next(err);
});
});
};
}
module.exports = function createMockCouchAdapter() {
var app = express();
var deferred;
var original;
['del', 'head', 'get', 'post'].forEach(function(verb) {
var expressVerb = (verb === 'del' ? 'delete' : verb);
app[verb] = createMethodWrapper(app, expressVerb);
});
// store the put method
app.put = function (route, handler) {
deferred = handler;
};
original = app.use;
app.use = function (middleware) {
original.call(app, '/:db', middleware);
// now add the put method
createMethodWrapper(app, 'put')('/:db', deferred);
};
return app;
};
| var express = require('express');
function createMethodWrapper(app, verb) {
var original = app[verb];
return function (route, handler) {
var hasSentResponse = false;
original.call(app, route, function (req, res, next) {
handler(req, {
setHeader: function () {
// empty
},
send: function(statusCode, body) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
res.send(statusCode, body);
}
}, function _next(err) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
next(err);
});
});
};
}
module.exports = function createMockCouchAdapter() {
var app = express();
var deferred;
var original;
['del', 'head', 'get', 'post'].forEach(function(verb) {
var expressVerb = (verb === 'del' ? 'delete' : verb);
app[verb] = createMethodWrapper(app, expressVerb);
});
// store the put method
app.put = function (route, handler) {
deferred = handler;
};
original = app.use;
app.use = function (middleware) {
original.call(app, '/:db', middleware);
// now add the put method
createMethodWrapper(app, 'put')('/:db', deferred);
};
return app;
};
|
ENH: Add very basic tests for codata and constants.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@6563 d6536bca-fef9-0310-8506-e4c0a848fbcf |
import warnings
import codata
import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
def test_basic_table_parse():
c = 'speed of light in vacuum'
assert_equal(codata.value(c), constants.c)
assert_equal(codata.value(c), constants.speed_of_light)
def test_basic_lookup():
assert_equal('%d %s' % (codata.c, codata.unit('speed of light in vacuum')),
'299792458 m s^-1')
if __name__ == "__main__":
run_module_suite()
|
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
if __name__ == "__main__":
run_module_suite()
|
Handle arrays in post input | <?php
class Inputs
{
protected static $_instance = Null;
public static function instance()
{
if (!self::$_instance)
self::$_instance = new self;
return self::$_instance;
}
public function input($key, $default = Null)
{
switch (Router::instance()->method) {
case Router::POST:
$result = $this->post($key, $default);
break;
case Router::PUT:
$result = $this->put($key, $default);
break;
case Router::GET:
$result = $this->get($key, $default);
break;
default:
$result = $default;
}
return $result;
}
public function post($key, $default = Null)
{
if (isset($_POST[$key])) {
if (is_array($_POST[$key])) {
$results = Array();
foreach ($_POST[$key] as $index => $value)
$results[$index] = filter_var($value, FILTER_SANITIZE_STRING);
return $results;
} else
return filter_var($_POST[$key], FILTER_SANITIZE_STRING);
} else
return $default;
}
public function get($key, $default = Null)
{
return filter_var(Router::instance()->query($key, $default), FILTER_SANITIZE_STRING);
}
public function put($key, $default = Null)
{
parse_str(file_get_contents("php://input"), $vars);
return isset($vars[$key]) ? filter_var($vars[$key], FILTER_SANITIZE_STRING) : $default;
}
}
| <?php
class Inputs
{
protected static $_instance = Null;
public static function instance()
{
if (!self::$_instance)
self::$_instance = new self;
return self::$_instance;
}
public function input($key, $default = Null)
{
switch (Router::instance()->method) {
case Router::POST:
$result = $this->post($key, $default);
break;
case Router::PUT:
$result = $this->put($key, $default);
break;
case Router::GET:
$result = $this->get($key, $default);
break;
default:
$result = $default;
}
return $result;
}
public function post($key, $default = Null)
{
return isset($_POST[$key]) ? filter_var($_POST[$key], FILTER_SANITIZE_STRING) : $default;
}
public function get($key, $default = Null)
{
return filter_var(Router::instance()->query($key, $default), FILTER_SANITIZE_STRING);
}
public function put($key, $default = Null)
{
parse_str(file_get_contents("php://input"), $vars);
return isset($vars[$key]) ? filter_var($vars[$key], FILTER_SANITIZE_STRING) : $default;
}
}
|
Fix project name in urlconf | import watson
from cms.apps.pages.models import ContentBase
from cms.models import HtmlField, SearchMetaBase
from django.db import models
class Careers(ContentBase):
# The heading that the admin places this content under.
classifier = "apps"
# The urlconf used to power this content's views.
urlconf = "{{ project_name }}.apps.careers.urls"
standfirst = models.TextField(
blank=True,
null=True
)
per_page = models.IntegerField(
"careers per page",
default=5,
blank=True,
null=True
)
def __unicode__(self):
return self.page.title
class Career(SearchMetaBase):
page = models.ForeignKey(
Careers
)
title = models.CharField(
max_length=256,
)
slug = models.CharField(
max_length=256,
unique=True
)
location = models.CharField(
max_length=256,
blank=True,
null=True
)
summary = models.TextField(
blank=True,
null=True
)
description = HtmlField()
email_address = models.EmailField()
order = models.PositiveIntegerField(
default=0
)
class Meta:
ordering = ('order',)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return self.page.page.reverse('career', kwargs={
'slug': self.slug,
})
watson.register(Career)
| import watson
from cms.apps.pages.models import ContentBase
from cms.models import HtmlField, SearchMetaBase
from django.db import models
class Careers(ContentBase):
# The heading that the admin places this content under.
classifier = "apps"
# The urlconf used to power this content's views.
urlconf = "phixflow.apps.careers.urls"
standfirst = models.TextField(
blank=True,
null=True
)
per_page = models.IntegerField(
"careers per page",
default=5,
blank=True,
null=True
)
def __unicode__(self):
return self.page.title
class Career(SearchMetaBase):
page = models.ForeignKey(
Careers
)
title = models.CharField(
max_length=256,
)
slug = models.CharField(
max_length=256,
unique=True
)
location = models.CharField(
max_length=256,
blank=True,
null=True
)
summary = models.TextField(
blank=True,
null=True
)
description = HtmlField()
email_address = models.EmailField()
order = models.PositiveIntegerField(
default=0
)
class Meta:
ordering = ('order',)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return self.page.page.reverse('career', kwargs={
'slug': self.slug,
})
watson.register(Career)
|
Add children to debug str | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class MutableTree:
def __init__ (self, value = None):
self.child = None
self.children = [ ]
self.value = value
@property
def value (self):
return self.__value
@value.setter
def value (self, x):
self.__value = x
def __len__ (self):
return 0 if self.child is None else 1
def full_length (self):
return len(self)
def __iter__ (self):
if self:
return iter((self.child,))
else:
return iter(())
def walk (self):
return iter(self)
def __getitem__ (self, index):
if self and index == 0:
return self.child
else:
raise IndexError("tree index out of range")
def insert (self, index, node):
self.child = node
self.children.insert(index, node)
def __repr__ (self):
debug = self.__class__.__name__
if self.value is not None:
debug += " " + repr(self.value)
return "<{} {}>".format(debug, repr(self.children))
| # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class MutableTree:
def __init__ (self, value = None):
self.child = None
self.children = [ ]
self.value = value
@property
def value (self):
return self.__value
@value.setter
def value (self, x):
self.__value = x
def __len__ (self):
return 0 if self.child is None else 1
def full_length (self):
return len(self)
def __iter__ (self):
if self:
return iter((self.child,))
else:
return iter(())
def walk (self):
return iter(self)
def __getitem__ (self, index):
if self and index == 0:
return self.child
else:
raise IndexError("tree index out of range")
def insert (self, index, node):
self.child = node
self.children.insert(index, node)
def __repr__ (self):
debug = self.__class__.__name__
if self.value is not None:
debug += " " + repr(self.value)
return "<{}>".format(debug)
|
Set SymPy version req to 0.7.4.1 (required only for Theano). | #!/usr/bin/env python
from setuptools import setup, find_packages
from pydy_code_gen import __version__
setup(
name='pydy-code-gen',
version=__version__,
author='Jason K. Moore',
author_email='[email protected]',
url="https://github.com/PythonDynamics/pydy-code-gen/",
description='Code generation for multibody dynamic systems.',
long_description=open('README.rst').read(),
keywords="dynamics multibody simulation code generation",
license='UNLICENSE',
packages=find_packages(),
install_requires=['sympy>=0.7.4.1',
'numpy>=1.6.1',
],
extras_require={'doc': ['sphinx', 'numpydoc'],
'theano': ['Theano>=0.6.0'],
'cython': ['Cython>=0.15.1'],
'examples': ['scipy>=0.9', 'matplotlib>=0.99'],
},
tests_require=['nose>=1.3.0'],
test_suite='nose.collector',
scripts=['bin/benchmark_pydy_code_gen.py'],
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Physics',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
from pydy_code_gen import __version__
setup(
name='pydy-code-gen',
version=__version__,
author='Jason K. Moore',
author_email='[email protected]',
url="https://github.com/PythonDynamics/pydy-code-gen/",
description='Code generation for multibody dynamic systems.',
long_description=open('README.rst').read(),
keywords="dynamics multibody simulation code generation",
license='UNLICENSE',
packages=find_packages(),
install_requires=['sympy>=0.7.3',
'numpy>=1.6.1',
],
extras_require={'doc': ['sphinx', 'numpydoc'],
'theano': ['Theano>=0.6.0'],
'cython': ['Cython>=0.15.1'],
'examples': ['scipy>=0.9', 'matplotlib>=0.99'],
},
tests_require=['nose>=1.3.0'],
test_suite='nose.collector',
scripts=['bin/benchmark_pydy_code_gen.py'],
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Physics',
],
)
|
Make sure that the admin widget also supports Django 2 | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file associated with it.
attrs["data-value"] = ""
return super(CIImgWidget, self).render(name, value, attrs)
class CIThumbnailWidget(Input):
input_type = "text"
def render(self, name, value, attrs=None, renderer=None, **kwargs):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden"
input_field = super(CIThumbnailWidget, self).render(name, value, attrs)
return render_to_string("cropimg/cropimg_widget.html",
{
"name": name, "value": value, "attrs": attrs,
"input_field": input_field
})
class Media:
js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js",
"cropimg/js/cropimg_init.js")
css = {"all": ["cropimg/resource/cropimg.css"]}
| from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file associated with it.
attrs["data-value"] = ""
return super(CIImgWidget, self).render(name, value, attrs)
class CIThumbnailWidget(Input):
input_type = "text"
def render(self, name, value, attrs=None, renderer=None):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden"
input_field = super(CIThumbnailWidget, self).render(name, value, attrs)
return render_to_string("cropimg/cropimg_widget.html",
{
"name": name, "value": value, "attrs": attrs,
"input_field": input_field
})
class Media:
js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js",
"cropimg/js/cropimg_init.js")
css = {"all": ["cropimg/resource/cropimg.css"]}
|
mongoose(deprecation): Add a new key/pair to mongoose connect options to fix deprecation warning | "use strict";
/* eslint-disable import/no-unresolved */
/* eslint-disable no-console */
import mongoose from 'mongoose';
import chalk from 'chalk';
import bluebird from 'bluebird';
const connectDB = () => {
mongoose.Promise = bluebird;
if (process.env.NODE_ENV !== 'test') {
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { promiseLibrary: bluebird, useMongoClient: true });
//============================
// CONNECTION EVENT LISTENERS
//============================
// When successfully connected
mongoose.connection.on('connected', () => {
if (process.env.NODE_ENV === 'development') {
console.log(chalk.green('Mongoose connection open to'), chalk.blue(process.env.MONGODB_URI));
} else {
console.log(chalk.green('Mongoose connection'), chalk.blue('OPEN'));
}
});
// If the connection throws an error
mongoose.connection.on('error', err => {
console.log(chalk.red('Mongoose connection error:', err));
});
// When the connection is disconnected
mongoose.connection.on('disconnected', () => {
console.log(chalk.yellow('\nMongoose connection disconnected'));
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log(chalk.yellow('Mongoose connection disconnected through app termination'));
process.exit(0);
});
});
}
};
export default connectDB;
| "use strict";
/* eslint-disable import/no-unresolved */
/* eslint-disable no-console */
import mongoose from 'mongoose';
import chalk from 'chalk';
import bluebird from 'bluebird';
const connectDB = () => {
mongoose.Promise = bluebird;
if (process.env.NODE_ENV !== 'test') {
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { promiseLibrary: bluebird });
//============================
// CONNECTION EVENT LISTENERS
//============================
// When successfully connected
mongoose.connection.on('connected', () => {
if (process.env.NODE_ENV === 'development') {
console.log(chalk.green('Mongoose connection open to'), chalk.blue(process.env.MONGODB_URI));
} else {
console.log(chalk.green('Mongoose connection'), chalk.blue('OPEN'));
}
});
// If the connection throws an error
mongoose.connection.on('error', err => {
console.log(chalk.red('Mongoose connection error:', err));
});
// When the connection is disconnected
mongoose.connection.on('disconnected', () => {
console.log(chalk.yellow('\nMongoose connection disconnected'));
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log(chalk.yellow('Mongoose connection disconnected through app termination'));
process.exit(0);
});
});
}
};
export default connectDB;
|
Rename offlineevent to offlineevents route | from django.utils.translation import ugettext_lazy as _
from meinberlin.apps.dashboard2 import DashboardComponent
from meinberlin.apps.dashboard2 import content
from . import views
from .apps import Config
class OfflineEventsComponent(DashboardComponent):
app_label = Config.label
label = 'offlineevents'
identifier = 'offlineevents'
def get_menu_label(self, project):
return _('Offline Events')
def get_progress(self, project):
return 0, 0
def get_urls(self):
return [
(r'^offlineevents/projects/(?P<project_slug>[-\w_]+)/$',
views.OfflineEventListView.as_view(component=self),
'offlineevent-list'),
(r'^offlineevents/create/project/(?P<project_slug>[-\w_]+)/$',
views.OfflineEventCreateView.as_view(component=self),
'offlineevent-create'),
(r'^offlineevents/(?P<slug>[-\w_]+)/update/$',
views.OfflineEventUpdateView.as_view(component=self),
'offlineevent-update'),
(r'^offlineevents/(?P<slug>[-\w_]+)/delete/$',
views.OfflineEventDeleteView.as_view(component=self),
'offlineevent-delete')
]
content.register_project(OfflineEventsComponent())
| from django.utils.translation import ugettext_lazy as _
from meinberlin.apps.dashboard2 import DashboardComponent
from meinberlin.apps.dashboard2 import content
from . import views
from .apps import Config
class OfflineEventsComponent(DashboardComponent):
app_label = Config.label
label = 'offlineevents'
identifier = 'offlineevents'
def get_menu_label(self, project):
return _('Offline Events')
def get_progress(self, project):
return 0, 0
def get_urls(self):
return [
(r'^offlineevent/projects/(?P<project_slug>[-\w_]+)/$',
views.OfflineEventListView.as_view(component=self),
'offlineevent-list'),
(r'^offlineevent/create/project/(?P<project_slug>[-\w_]+)/$',
views.OfflineEventCreateView.as_view(component=self),
'offlineevent-create'),
(r'^offlineevent/(?P<slug>[-\w_]+)/update/$',
views.OfflineEventUpdateView.as_view(component=self),
'offlineevent-update'),
(r'^offlineevent/(?P<slug>[-\w_]+)/delete/$',
views.OfflineEventDeleteView.as_view(component=self),
'offlineevent-delete')
]
content.register_project(OfflineEventsComponent())
|
Use more explicit variable names. | #!/usr/bin/env python
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
log = 'bmake-' + target + '-log.txt'
with open(log, 'w+') as f:
f.write(out)
f.write(err)
assert p.returncode == 0, '%s %s' % (pkg, target)
if __name__ == '__main__':
home = os.environ['HOME']
localbase = os.path.join(home, 'usr', 'pkgsrc')
lines = sys.stdin.readlines()
pkgs = [line.rstrip('\n') for line in lines]
pkgpaths = [pkg.split(' ')[0] for pkg in pkgs]
for pkgpath in pkgpaths:
print pkgpath
os.chdir(localbase)
assert os.path.exists(os.path.join(localbase, pkgpath))
build(pkgpath)
| #!/usr/bin/env python
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
log = 'bmake-' + target + '-log.txt'
with open(log, 'w+') as f:
f.write(out)
f.write(err)
assert p.returncode == 0, '%s %s' % (pkg, target)
if __name__ == '__main__':
home = os.environ['HOME']
localbase = os.path.join(home, 'usr', 'pkgsrc')
lines = sys.stdin.readlines()
pkgs = [line.rstrip('\n') for line in lines]
pkgs = [pkg.split(' ')[0] for pkg in pkgs]
for pkg in pkgs:
print pkg
os.chdir(localbase)
assert os.path.exists(os.path.join(localbase, pkg))
build(pkg)
|
Check if total is set | import parallel from 'async/parallel';
import defaults from 'lodash-es/defaults';
import handleEtag from '../helper/etag';
import keyFactory from '../helper/key';
export default function setList(cache, options = {}) {
options = defaults({}, options, {
etag: true,
list: null,
total: ['where']
});
const write = Boolean(cache.channel());
return (request, response, next) => {
const listKey = keyFactory(request, options.list);
const totalKey = keyFactory(request, options.total);
const data = request.data();
const tasks = {
list: (callback) => cache.set(listKey, data.list, callback),
total: (callback) => callback(null, null)
};
if (response.header('x-total') === null && data.total !== null) {
tasks.total = (callback) => {
cache.set(totalKey, data.total, callback);
};
}
parallel(tasks, (error, result) => {
if (error instanceof Error === true) {
next(error);
return;
}
if (result.total !== null) {
response.header('x-total', result.total);
}
const etag =
options.etag === true &&
handleEtag(request, response, result.list, write) === true;
if (etag === true) {
return;
}
if (write === true) {
response.write(result.list);
} else {
response.end(result.list);
}
});
};
}
| import parallel from 'async/parallel';
import defaults from 'lodash-es/defaults';
import handleEtag from '../helper/etag';
import keyFactory from '../helper/key';
export default function setList(cache, options = {}) {
options = defaults({}, options, {
etag: true,
list: null,
total: ['where']
});
const write = Boolean(cache.channel());
return (request, response, next) => {
const listKey = keyFactory(request, options.list);
const totalKey = keyFactory(request, options.total);
const data = request.data();
const tasks = {
list: (callback) => cache.set(listKey, data.list, callback),
total: (callback) => callback(null, null)
};
if (response.header('x-total') === null) {
tasks.total = (callback) => {
cache.set(totalKey, data.total, callback);
};
}
parallel(tasks, (error, result) => {
if (error instanceof Error === true) {
next(error);
return;
}
if (result.total !== null) {
response.header('x-total', result.total);
}
const etag =
options.etag === true &&
handleEtag(request, response, result.list, write) === true;
if (etag === true) {
return;
}
if (write === true) {
response.write(result.list);
} else {
response.end(result.list);
}
});
};
}
|
Add ability to customize error message styles | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Form, Label, Input } from 'semantic-ui-react';
class FormInput extends Component {
componentWillReceiveProps(nextProps) {
const {
input: { value, onChange },
meta: { visited },
defaultValue
} = nextProps;
if (!value && !visited && defaultValue) onChange(defaultValue);
}
render() {
const {
input,
meta: { error, touched },
readOnly,
width,
label,
defaultValue,
required,
inline,
errorMessageStyle,
...rest
} = this.props;
const hasError = touched && Boolean(error);
if (readOnly) {
return (
<span className="read-only">
{input && input.value && input.value.toLocaleString()}
</span>
);
}
return (
<Form.Field
error={hasError}
width={width}
required={required}
inline={inline}
>
{label && <label>{label}</label>}
<Input
{...input}
{...rest}
value={input.value || ''}
error={hasError}
/>
{hasError && (
<Label className="error-message" pointing={inline ? 'left' : true} style={errorMessageStyle}>
{error}
</Label>
)}
</Form.Field>
);
}
}
export default FormInput;
| import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Form, Label, Input } from 'semantic-ui-react';
class FormInput extends Component {
componentWillReceiveProps(nextProps) {
const {
input: { value, onChange },
meta: { visited },
defaultValue
} = nextProps;
if (!value && !visited && defaultValue) onChange(defaultValue);
}
render() {
const {
input,
meta: { error, touched },
readOnly,
width,
label,
defaultValue,
required,
errorPosition,
inline,
...rest
} = this.props;
const hasError = touched && Boolean(error);
if (readOnly) {
return (
<span className="read-only">
{input && input.value && input.value.toLocaleString()}
</span>
);
}
return (
<Form.Field
error={hasError}
width={width}
required={required}
style={{ position: 'relative' }}
inline={inline}
>
{label && <label>{label}</label>}
<Input
{...input}
{...rest}
value={input.value || ''}
error={hasError}
/>
{hasError && (
<Label pointing={inline ? 'left' : true}>
{error}
</Label>
)}
</Form.Field>
);
}
}
export default FormInput;
|
Change so that users are redirected to new landing page | import React from 'react';
import Utility from '../../shared/util/Utility';
import * as Security from '../../shared/reducers/Security';
import * as Lessons from '../../shared/reducers/Lessons';
export const Reducers = [Security, Lessons];
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount() {
this.checkAuth(this.props.loggedIn);
}
componentWillReceiveProps(nextProps) {
this.checkAuth(nextProps.loggedIn);
}
checkAuth(isAuthenticated) {
if (!isAuthenticated) {
const redirectAfterLogin = this.props.location.pathname;
this.props.setPageByName('start', { redirectUrl: redirectAfterLogin });
// this.props.dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));
}
}
render() {
return (
<div>
{this.props.loggedIn
? <Component {...this.props} />
: null
}
</div>
);
}
}
AuthenticatedComponent.defaultProps = Utility.reduxEnabledDefaultProps({
}, Reducers);
AuthenticatedComponent.propTypes = Utility.reduxEnabledPropTypes({
}, Reducers);
return Utility.superConnect(this, Reducers)(AuthenticatedComponent);
}
| import React from 'react';
import Utility from '../../shared/util/Utility';
import * as Security from '../../shared/reducers/Security';
import * as Lessons from '../../shared/reducers/Lessons';
export const Reducers = [Security, Lessons];
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount() {
this.checkAuth(this.props.loggedIn);
}
componentWillReceiveProps(nextProps) {
this.checkAuth(nextProps.loggedIn);
}
checkAuth(isAuthenticated) {
if (!isAuthenticated) {
const redirectAfterLogin = this.props.location.pathname;
this.props.setPageByName('login', { redirectUrl: redirectAfterLogin });
// this.props.dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));
}
}
render() {
return (
<div>
{this.props.loggedIn
? <Component {...this.props} />
: null
}
</div>
);
}
}
AuthenticatedComponent.defaultProps = Utility.reduxEnabledDefaultProps({
}, Reducers);
AuthenticatedComponent.propTypes = Utility.reduxEnabledPropTypes({
}, Reducers);
return Utility.superConnect(this, Reducers)(AuthenticatedComponent);
}
|
Improve by using breadth search instead of depth search | <?php
class AlgorithmConnectedComponents extends Algorithm{
/**
*
* @var Graph
*/
private $graph;
/**
*
* @param Graph $graph
*/
public function __construct(Graph $graph){
$this->graph = $graph;
}
/**
* check whether this graph consists of only a single component
*
* could be improved by not checking for actual number of components but stopping when there's more than one
*
* @return boolean
* @uses AlgorithmSearchBreadthFirst::getNumberOfVertices()
*/
public function isSingle(){
$alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst());
return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices());
}
/**
* @return int number of components
* @uses Graph::getVertices()
* @uses AlgorithmSearchBreadthFirst::getVerticesIds()
*/
public function getNumberOfComponents(){
$visitedVertices = array();
$components = 0;
foreach ($this->graph->getVertices() as $vid=>$vertex){ //for each vertices
if ( ! isset( $visitedVertices[$vid] ) ){ //did I visit this vertex before?
$alg = new AlgorithmSearchBreadthFirst($vertex);
$newVertices = $alg->getVerticesIds(); //get all vertices of this component
++$components;
foreach ($newVertices as $vid){ //mark the vertices of this component as visited
$visitedVertices[$vid] = true;
}
}
}
return $components; //return number of components
}
}
| <?php
class AlgorithmConnectedComponents extends Algorithm{
/**
*
* @var Graph
*/
private $graph;
/**
*
* @param Graph $graph
*/
public function __construct(Graph $graph){
$this->graph = $graph;
}
/**
* check whether this graph consists of only a single component
*
* could be improved by not checking for actual number of components but stopping when there's more than one
*
* @return boolean
* @uses AlgorithmSearchBreadthFirst::getNumberOfVertices()
*/
public function isSingle(){
$alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst());
return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices());
}
/**
* @return int number of components
* @uses Graph::getVertices()
* @uses AlgorithmSearchDepthFirst::getVertices()
*/
public function getNumberOfComponents(){
$visitedVertices = array();
$components = 0;
foreach ($this->graph->getVertices() as $vertex){ //for each vertices
if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before?
$alg = new AlgorithmSearchDepthFirst($vertex);
$newVertices = $alg->getVertices(); //get all vertices of this component
$components++;
foreach ($newVertices as $v){ //mark the vertices of this component as visited
$visitedVertices[$v->getId()] = true;
}
}
}
return $components; //return number of components
}
}
|
Remove a redundant line from get_class | """
This module adds several functions for interactive source code inspection.
"""
from __future__ import print_function, division
import inspect
def source(object):
"""
Prints the source code of a given object.
"""
print('In file: %s' % inspect.getsourcefile(object))
print(inspect.getsource(object))
def get_class(lookup_view):
"""
Convert a string version of a class name to the object.
For example, get_class('sympy.core.Basic') will return
class Basic located in module sympy.core
"""
if isinstance(lookup_view, str):
mod_name, func_name = get_mod_func(lookup_view)
if func_name != '':
lookup_view = getattr(
__import__(mod_name, {}, {}, ['*']), func_name)
if not callable(lookup_view):
raise AttributeError(
"'%s.%s' is not a callable." % (mod_name, func_name))
return lookup_view
def get_mod_func(callback):
"""
splits the string path to a class into a string path to the module
and the name of the class. For example:
>>> from sympy.utilities.source import get_mod_func
>>> get_mod_func('sympy.core.basic.Basic')
('sympy.core.basic', 'Basic')
"""
dot = callback.rfind('.')
if dot == -1:
return callback, ''
return callback[:dot], callback[dot + 1:]
| """
This module adds several functions for interactive source code inspection.
"""
from __future__ import print_function, division
import inspect
def source(object):
"""
Prints the source code of a given object.
"""
print('In file: %s' % inspect.getsourcefile(object))
print(inspect.getsource(object))
def get_class(lookup_view):
"""
Convert a string version of a class name to the object.
For example, get_class('sympy.core.Basic') will return
class Basic located in module sympy.core
"""
if isinstance(lookup_view, str):
lookup_view = lookup_view
mod_name, func_name = get_mod_func(lookup_view)
if func_name != '':
lookup_view = getattr(
__import__(mod_name, {}, {}, ['*']), func_name)
if not callable(lookup_view):
raise AttributeError(
"'%s.%s' is not a callable." % (mod_name, func_name))
return lookup_view
def get_mod_func(callback):
"""
splits the string path to a class into a string path to the module
and the name of the class. For example:
>>> from sympy.utilities.source import get_mod_func
>>> get_mod_func('sympy.core.basic.Basic')
('sympy.core.basic', 'Basic')
"""
dot = callback.rfind('.')
if dot == -1:
return callback, ''
return callback[:dot], callback[dot + 1:]
|
Convert Non-strict to strict equality checking
Convert non-strict equality checking, using `==`, to the strict version, using `===`. | module.exports = {
link: async function(library, destinations, deployer) {
let eventArgs;
// Validate name
if (library.contract_name == null) {
eventArgs = {
type: "noLibName"
};
const message = await deployer.emitter.emit("error", eventArgs);
throw new Error(message);
}
// Validate address: don't want to use .address directly because it will throw.
let hasAddress;
typeof library.isDeployed
? (hasAddress = library.isDeployed())
: (hasAddress = library.address != null);
if (!hasAddress) {
eventArgs = {
type: "noLibAddress",
contract: library
};
const message = await deployer.emitter.emit("error", eventArgs);
throw new Error(message);
}
// Link all destinations
if (!Array.isArray(destinations)) {
destinations = [destinations];
}
for (let destination of destinations) {
// Don't link if result will have no effect.
const alreadyLinked =
destination.links[library.contract_name] === library.address;
const noLinkage =
destination.unlinked_binary.indexOf(library.contract_name) < 0;
if (alreadyLinked || noLinkage) continue;
eventArgs = {
libraryName: library.contractName,
libraryAddress: library.address,
contractName: destination.contractName,
contractAddress: destination.contractAddress
};
await deployer.emitter.emit("linking", eventArgs);
destination.link(library);
}
}
};
| module.exports = {
link: async function(library, destinations, deployer) {
let eventArgs;
// Validate name
if (library.contract_name == null) {
eventArgs = {
type: "noLibName"
};
const message = await deployer.emitter.emit("error", eventArgs);
throw new Error(message);
}
// Validate address: don't want to use .address directly because it will throw.
let hasAddress;
typeof library.isDeployed
? (hasAddress = library.isDeployed())
: (hasAddress = library.address != null);
if (!hasAddress) {
eventArgs = {
type: "noLibAddress",
contract: library
};
const message = await deployer.emitter.emit("error", eventArgs);
throw new Error(message);
}
// Link all destinations
if (!Array.isArray(destinations)) {
destinations = [destinations];
}
for (let destination of destinations) {
// Don't link if result will have no effect.
const alreadyLinked =
destination.links[library.contract_name] == library.address;
const noLinkage =
destination.unlinked_binary.indexOf(library.contract_name) < 0;
if (alreadyLinked || noLinkage) continue;
eventArgs = {
libraryName: library.contractName,
libraryAddress: library.address,
contractName: destination.contractName,
contractAddress: destination.contractAddress
};
await deployer.emitter.emit("linking", eventArgs);
destination.link(library);
}
}
};
|
Modify variables passing in in dummy app. | import Ember from 'ember';
import CommentableMixin from 'ember-osf/mixins/commentable';
import TaggableMixin from 'ember-osf/mixins/taggable-mixin';
import NodeActionsMixin from 'ember-osf/mixins/node-actions';
import KeenTrackerMixin from 'ember-osf/mixins/keen-tracker';
export default Ember.Controller.extend(CommentableMixin, TaggableMixin, NodeActionsMixin, KeenTrackerMixin, {
toast: Ember.inject.service(),
propertiesVisible: false,
isSaving: false,
licenseToggle: true,
serializedLicense: Ember.computed('model.license', function() {
let license = this.get('model.license');
return {
licenseType: license,
year: this.get('model.nodeLicense.year'),
copyrightHolders: this.get('model.nodeLicense.copyright_holders') ? this.get('model.nodeLicense.copyright_holders').join(',') : null
};
}),
actions: {
toggleEditNode() {
this.toggleProperty('propertiesVisible');
},
toggleLicense() {
this.toggleProperty('licenseToggle');
},
editLicense() {
// Would update node properly!
},
updateNode() {
this.keenTrackFrontEndEvent({
category:'button',
action: 'click',
label: 'Update Node'
}, this.get('model'));
this.set('isSaving', true);
return this._super(...arguments)
.then(() => {
this.set('isSaving', false);
this.get('toast').success('Node updated successfully');
})
.catch(() => this.set('isSaving', false));
}
}
});
| import Ember from 'ember';
import CommentableMixin from 'ember-osf/mixins/commentable';
import TaggableMixin from 'ember-osf/mixins/taggable-mixin';
import NodeActionsMixin from 'ember-osf/mixins/node-actions';
import KeenTrackerMixin from 'ember-osf/mixins/keen-tracker';
export default Ember.Controller.extend(CommentableMixin, TaggableMixin, NodeActionsMixin, KeenTrackerMixin, {
toast: Ember.inject.service(),
propertiesVisible: false,
isSaving: false,
licenseToggle: true,
serializedLicense: Ember.computed('model.license', function() {
let license = this.get('model.license');
return {
licenseType: license,
year: this.get('model.nodeLicense.year'),
copyrightHolders: this.get('model.nodeLicense.copyright_holders') ? this.get('model.nodeLicense.copyright_holders').join(',') : null
};
}),
actions: {
toggleEditNode() {
this.toggleProperty('propertiesVisible');
},
toggleLicense() {
this.toggleProperty('licenseToggle');
},
editLicense() {
// Would update node properly!
},
updateNode() {
this.keenTrackFrontEndEvent('button', 'click', 'updateNode');
this.set('isSaving', true);
return this._super(...arguments)
.then(() => {
this.set('isSaving', false);
this.get('toast').success('Node updated successfully');
})
.catch(() => this.set('isSaving', false));
}
}
});
|
fix: Use new relative import within directory
See also: PSOBAT-1197 | """Generate base64 encoded User Data."""
import base64
from .get_template import get_template
def generate_encoded_user_data(env='dev',
region='us-east-1',
app_name='',
group_name=''):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
app_name (str): Application name, e.g. coreforrest.
group_name (str): Application group nane, e.g. core.
Returns:
str: base64 encoded User Data script.
#!/bin/bash
export CLOUD_ENVIRONMENT=dev
export CLOUD_APP=coreforrest
export CLOUD_APP_GROUP=forrest
export CLOUD_STACK=forrest
export EC2_REGION=us-east-1
export CLOUD_DOMAIN=dev.example.com
printenv | grep 'CLOUD\|EC2' | awk '$0="export "$0'>> /etc/gogo/cloud_env
"""
user_data = get_template(template_file='user_data.sh.j2',
env=env,
region=region,
app_name=app_name,
group_name=group_name, )
return base64.b64encode(user_data.encode()).decode()
| """Generate base64 encoded User Data."""
import base64
from ..utils import get_template
def generate_encoded_user_data(env='dev',
region='us-east-1',
app_name='',
group_name=''):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
app_name (str): Application name, e.g. coreforrest.
group_name (str): Application group nane, e.g. core.
Returns:
str: base64 encoded User Data script.
#!/bin/bash
export CLOUD_ENVIRONMENT=dev
export CLOUD_APP=coreforrest
export CLOUD_APP_GROUP=forrest
export CLOUD_STACK=forrest
export EC2_REGION=us-east-1
export CLOUD_DOMAIN=dev.example.com
printenv | grep 'CLOUD\|EC2' | awk '$0="export "$0'>> /etc/gogo/cloud_env
"""
user_data = get_template(template_file='user_data.sh.j2',
env=env,
region=region,
app_name=app_name,
group_name=group_name, )
return base64.b64encode(user_data.encode()).decode()
|
Fix missing import in merge conflict resolution | var _ = require('lodash'),
AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
| var AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
|
Refactoring: Replace loop by dictionary comprehension | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
return {Converter.__name__: Converter.converter_configuration()
for Converter in BaseExcerptConverter.available_converters}
def __init__(self, extraction_order,
available_converters=BaseExcerptConverter.available_converters,
run_as_celery_tasks=True):
""""
:param execution_configuration example:
{
'gis': {
'formats': ['txt', 'file_gdb'],
'options': {
'coordinate_reference_system': 'wgs72',
'detail_level': 'verbatim'
}
},
'routing': { ... }
}
"""
self.extraction_order = extraction_order
self.available_converters = available_converters
self.run_as_celery_tasks = run_as_celery_tasks
def execute_converters(self):
for Converter in self.available_converters:
if Converter.__name__ in self.extraction_order.extraction_configuration:
Converter.execute(
self.extraction_order,
self.extraction_order.extraction_configuration[Converter.__name__],
self.run_as_celery_tasks
)
| from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
export_options = {}
for Converter in BaseExcerptConverter.available_converters:
export_options[Converter.__name__] = Converter.converter_configuration()
return export_options
def __init__(self, extraction_order,
available_converters=BaseExcerptConverter.available_converters,
run_as_celery_tasks=True):
""""
:param execution_configuration example:
{
'gis': {
'formats': ['txt', 'file_gdb'],
'options': {
'coordinate_reference_system': 'wgs72',
'detail_level': 'verbatim'
}
},
'routing': { ... }
}
"""
self.extraction_order = extraction_order
self.available_converters = available_converters
self.run_as_celery_tasks = run_as_celery_tasks
def execute_converters(self):
for Converter in self.available_converters:
if Converter.__name__ in self.extraction_order.extraction_configuration:
Converter.execute(
self.extraction_order,
self.extraction_order.extraction_configuration[Converter.__name__],
self.run_as_celery_tasks
)
|
Allow email and label to be null | Ext.define('SlateAdmin.model.person.progress.NoteRecipient', {
extend: 'Ext.data.Model',
groupField: 'RelationshipGroup',
fields: [
{
name: 'PersonID',
type: 'integer'
},
{
name: 'FullName',
type: 'string'
},
{
name: 'Email',
type: 'string',
allowNull: true
},
{
name: 'Label',
type: 'string',
allowNull: true
},
{
name: 'RelationshipGroup',
convert: function (v) {
return v || 'Other';
}
},
// virtual fields
{
name: 'selected',
type: 'boolean',
convert: function (v, record) {
var selected = !Ext.isEmpty(record.get('Status'));
return selected;
}
}
],
proxy: {
type: 'slaterecords',
startParam: null,
limitParam: null,
api: {
read: '/notes/progress/recipients',
update: '/notes/save',
create: '/notes/save',
destory: '/notes/save'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
rootProperty: 'data',
writeAllFields: false,
allowSingle: false
}
}
});
| Ext.define('SlateAdmin.model.person.progress.NoteRecipient', {
extend: 'Ext.data.Model',
groupField: 'RelationshipGroup',
fields: [
{
name: 'PersonID',
type: 'integer'
},
{
name: 'FullName',
type: 'string'
},
{
name: 'Email',
type: 'string'
},
{
name: 'Label',
type: 'string'
},
{
name: 'RelationshipGroup',
convert: function (v) {
return v || 'Other';
}
},
// virtual fields
{
name: 'selected',
type: 'boolean',
convert: function (v, record) {
var selected = !Ext.isEmpty(record.get('Status'));
return selected;
}
}
],
proxy: {
type: 'slaterecords',
startParam: null,
limitParam: null,
api: {
read: '/notes/progress/recipients',
update: '/notes/save',
create: '/notes/save',
destory: '/notes/save'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
rootProperty: 'data',
writeAllFields: false,
allowSingle: false
}
}
});
|
Add source links for tweets | # coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
| # coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
Fix instance variable in graph sync job | import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
self.log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
format(**arguments))
del entry
| import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
format(**arguments))
del entry
|
meta-iotqa: Remove Edison specific command from Bluetooth test
The platform isn't supported anymore and the command isn't needed with
current devices.
Signed-off-by: Simo Kuusela <[email protected]> | import time
from oeqa.oetest import oeRuntimeTest
from oeqa.utils.decorators import tag
@tag(TestType="FVT", FeatureID="IOTOS-453")
class CommBluetoothTest(oeRuntimeTest):
"""
@class CommBluetoothTest
"""
log = ""
def setUp(self):
self.target.run('connmanctl enable bluetooth')
time.sleep(8)
def tearDown(self):
self.target.run('connmanctl disable bluetooth')
def target_collect_info(self, cmd):
"""
@fn target_collect_info
@param self
@param cmd
@return
"""
(status, output) = self.target.run(cmd)
self.log = self.log + "\n\n[Debug] Command output --- %s: \n" % cmd
self.log = self.log + output
'''Bluetooth device check'''
def test_comm_btcheck(self):
'''check bluetooth device
@fn test_comm_btcheck
@param self
@return
'''
# Collect system information as log
self.target_collect_info("ifconfig")
self.target_collect_info("hciconfig")
self.target_collect_info("lsmod")
# Detect BT device status
(status, output) = self.target.run('hciconfig hci0')
##
# TESTPOINT: #1, test_comm_btcheck
#
self.assertEqual(status, 0, msg="Error messages: %s" % self.log)
| import time
from oeqa.oetest import oeRuntimeTest
from oeqa.utils.decorators import tag
@tag(TestType="FVT", FeatureID="IOTOS-453")
class CommBluetoothTest(oeRuntimeTest):
"""
@class CommBluetoothTest
"""
log = ""
def setUp(self):
self.target.run('connmanctl enable bluetooth')
time.sleep(8)
def tearDown(self):
self.target.run('connmanctl disable bluetooth')
def target_collect_info(self, cmd):
"""
@fn target_collect_info
@param self
@param cmd
@return
"""
(status, output) = self.target.run(cmd)
self.log = self.log + "\n\n[Debug] Command output --- %s: \n" % cmd
self.log = self.log + output
'''Bluetooth device check'''
def test_comm_btcheck(self):
'''check bluetooth device
@fn test_comm_btcheck
@param self
@return
'''
# un-block software rfkill lock
self.target.run('rfkill unblock all')
# This is special for edison platform
# Collect system information as log
self.target_collect_info("ifconfig")
self.target_collect_info("hciconfig")
self.target_collect_info("lsmod")
# Detect BT device status
(status, output) = self.target.run('hciconfig hci0')
##
# TESTPOINT: #1, test_comm_btcheck
#
self.assertEqual(status, 0, msg="Error messages: %s" % self.log)
|
Update German, French, Spanish, and Portugese-Brasil Translations
All pulled by changing system language on PS4 and accessing Destiny in a different language. | (function() {
"use strict";
// See https://angular-translate.github.io/docs/#/guide
angular.module('dimApp')
.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('escape');
$translateProvider
.translations('en', {
Level: "Level",
Weapons: "Weapons",
Armor: "Armor",
Equip: "Equip",
Vault: "Vault",
Vanguard: "Vanguard"
})
.translations('it', {
Level: "Livello",
Weapons: "Armi",
Armor: "Armatura",
Equip: "Equipaggia",
Vault: "Deposito"
})
.translations('de', {
Weapons: "Waffen",
Armor: "Schutz",
Equip: "Ausstatten",
Vault: "Ausrüstungstresor"
})
.translations('fr', {
Level: "Niveau",
Weapons: "Armes",
Armor: "Armure",
Equip: "Équiper",
Vault: "Coffres"
})
.translations('es', {
Level: "Nivel",
Weapons: "Armas",
Armor: "Armadura",
Equip: "Equipar",
Vault: "Bóveda",
Vanguard: "Vanguardia"
})
.translations('ja', {
})
.translations('pt-br', {
Level: "Nivel",
Weapons: "Armas",
Armor: "Armadura",
Equip: "Equipar",
Vault: "Cofres"
})
.fallbackLanguage('en');
}]);
})();
| (function() {
"use strict";
// See https://angular-translate.github.io/docs/#/guide
angular.module('dimApp')
.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('escape');
$translateProvider
.translations('en', {
Level: "Level",
Weapons: "Weapons",
Armor: "Armor",
Equip: "Equip",
Vault: "Vault",
Vanguard: "Vanguard"
})
.translations('it', {
Level: "Livello",
Weapons: "Armi",
Armor: "Armatura",
Equip: "Equipaggia",
Vault: "Deposito"
})
.translations('de', {
Equip: "Ausstatten",
Vault: "Ausrüstungstresor"
})
.translations('fr', {
})
.translations('es', {
Level: "Nivel",
Weapons: "Arma",
Armor: "Armadura",
Vault: "Bóveda",
Vanguard: "Vanguardia"
})
.translations('ja', {
})
.translations('pt-br', {
})
.fallbackLanguage('en');
}]);
})();
|
Fix incompatibility with php 5.5 in tests | <?php
namespace Eole\Sandstone\Tests\Unit\Websocket;
use Eole\Sandstone\Serializer\ServiceProvider as SerializerServiceProvider;
use Eole\Sandstone\Websocket\Routing\TopicRouter;
use Eole\Sandstone\Websocket\Application as WebsocketApplication;
use Eole\Sandstone\Application;
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
public function testLoadTopicThrowExceptionWhenImplementingTheWrongEventDispatcherInterface()
{
$app = new Application();
$websocketAppClass = new \ReflectionClass(WebsocketApplication::class);
$method = $websocketAppClass->getMethod('loadTopic');
$method->setAccessible(true);
$websocketApp = $websocketAppClass->newInstance($app);
$app->register(new SerializerServiceProvider());
$app['sandstone.websocket.router'] = function () {
$wrongTopic = new WrongTopic('my-topic');
$topicRouterMock = $this->getMockBuilder(TopicRouter::class)->disableOriginalConstructor()->getMock();
$topicRouterMock
->method('loadTopic')
->willReturn($wrongTopic)
;
return $topicRouterMock;
};
$this->setExpectedExceptionRegExp(
\LogicException::class,
'/WrongTopic seems to implements the wrong EventSubscriberInterface/'
);
$method->invokeArgs($websocketApp, ['my-topic']);
}
}
| <?php
namespace Eole\Sandstone\Tests\Unit\Websocket;
use Eole\Sandstone\Serializer\ServiceProvider as SerializerServiceProvider;
use Eole\Sandstone\Websocket\Routing\TopicRouter;
use Eole\Sandstone\Websocket\Application as WebsocketApplication;
use Eole\Sandstone\Application;
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
public function testLoadTopicThrowExceptionWhenImplementingTheWrongEventDispatcherInterface()
{
$app = new Application();
$websocketAppClass = new \ReflectionClass(WebsocketApplication::class);
$method = $websocketAppClass->getMethod('loadTopic');
$method->setAccessible(true);
$websocketApp = $websocketAppClass->newInstance($app);
$app->register(new SerializerServiceProvider());
$app['sandstone.websocket.router'] = function () {
$wrongTopic = new WrongTopic('my-topic');
$topicRouterMock = $this->createMock(TopicRouter::class);
$topicRouterMock
->method('loadTopic')
->willReturn($wrongTopic)
;
return $topicRouterMock;
};
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('WrongTopic seems to implements the wrong EventSubscriberInterface');
$method->invokeArgs($websocketApp, ['my-topic']);
}
}
|
Add an answers function for state token strategy
[rev: alex.scown] | /*
* Copyright 2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define(['underscore'], function(_) {
'use strict';
const baseParams = function(queryModel) {
return {
text: queryModel.get('queryText'),
summary: 'context'
}
};
return {
waitForIndexes: _.constant(false),
answers: _.constant(false),
queryModelAttributes: [
'stateMatchIds',
'stateDontMatchIds',
'promotionsStateMatchIds'
],
// Query for promotions only if the snapshot has a promotions state token.
// Necessary to accommodate legacy snapshots predating QMS integration (FIND-30).
promotions: function(queryModel) {
if (queryModel.get('promotionsStateMatchIds')) {
return queryModel.get('promotionsStateMatchIds').length > 0;
} else {
return false;
}
},
requestParams: function(queryModel) {
return _.extend(baseParams(queryModel), {
state_match_ids: queryModel.get('stateMatchIds'),
state_dont_match_ids: queryModel.get('stateDontMatchIds')
});
},
promotionsRequestParams: function(queryModel) {
return _.extend(baseParams(queryModel), {
state_match_ids: queryModel.get('promotionsStateMatchIds')
});
},
validateQuery: function(queryModel) {
return !_.isEmpty(queryModel.get('stateMatchIds'));
}
};
});
| /*
* Copyright 2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define(['underscore'], function(_) {
'use strict';
const baseParams = function(queryModel) {
return {
text: queryModel.get('queryText'),
summary: 'context'
}
};
return {
waitForIndexes: _.constant(false),
queryModelAttributes: [
'stateMatchIds',
'stateDontMatchIds',
'promotionsStateMatchIds'
],
// Query for promotions only if the snapshot has a promotions state token.
// Necessary to accommodate legacy snapshots predating QMS integration (FIND-30).
promotions: function(queryModel) {
if (queryModel.get('promotionsStateMatchIds')) {
return queryModel.get('promotionsStateMatchIds').length > 0;
} else {
return false;
}
},
requestParams: function(queryModel) {
return _.extend(baseParams(queryModel), {
state_match_ids: queryModel.get('stateMatchIds'),
state_dont_match_ids: queryModel.get('stateDontMatchIds')
});
},
promotionsRequestParams: function(queryModel) {
return _.extend(baseParams(queryModel), {
state_match_ids: queryModel.get('promotionsStateMatchIds')
});
},
validateQuery: function(queryModel) {
return !_.isEmpty(queryModel.get('stateMatchIds'));
}
};
});
|
Use latest build schema commit -> ref | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_internal_code_reference(instance, commit=None):
project = instance.project
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_external_code_reference(git_url, commit=None):
code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit)
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None or instance.specification is None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.ref
git_url = build.git if build and build.git else None
if git_url:
code_reference = get_external_code_reference(git_url=git_url, commit=commit)
else:
code_reference = get_internal_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
| from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_internal_code_reference(instance, commit=None):
project = instance.project
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_external_code_reference(git_url, commit=None):
code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit)
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None or instance.specification is None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.commit
git_url = build.git if build and build.git else None
if git_url:
code_reference = get_external_code_reference(git_url=git_url, commit=commit)
else:
code_reference = get_internal_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
|
Fix warning on double sampleEnd (which is not true) | package com.googlecode.jmeter.plugins.webdriver.sampler;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
public class SampleResultWithSubs extends SampleResult {
private static final Logger log = LoggingManager.getLoggerForClass();
private SampleResult subSample;
public void subSampleStart(String label) {
if (subSample != null) {
log.warn("There is already a sub-sample started, continuing using it");
return;
}
if (getStartTime() == 0) {
sampleStart();
}
subSample = new SampleResult();
subSample.setSampleLabel(label);
subSample.setDataType(SampleResult.TEXT);
subSample.setSuccessful(true);
subSample.sampleStart();
}
public void subSampleEnd(boolean success) {
if (subSample == null) {
log.warn("There is no sub-sample started, use subSampleStart() to have one");
return;
}
subSample.sampleEnd();
subSample.setSuccessful(success);
super.addSubResult(subSample);
subSample = null;
}
@Override
public void sampleEnd() {
if (subSample != null) {
subSampleEnd(true);
}
if (getEndTime() == 0) {
super.sampleEnd();
}
}
}
| package com.googlecode.jmeter.plugins.webdriver.sampler;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
public class SampleResultWithSubs extends SampleResult {
private static final Logger log = LoggingManager.getLoggerForClass();
private SampleResult subSample;
public void subSampleStart(String label) {
if (subSample != null) {
log.warn("There is already a sub-sample started, continuing using it");
return;
}
if (getStartTime() == 0) {
sampleStart();
}
subSample = new SampleResult();
subSample.setSampleLabel(label);
subSample.setDataType(SampleResult.TEXT);
subSample.setSuccessful(true);
subSample.sampleStart();
}
public void subSampleEnd(boolean success) {
if (subSample == null) {
log.warn("There is no sub-sample started, use subSampleStart() to have one");
return;
}
subSample.sampleEnd();
subSample.setSuccessful(success);
super.addSubResult(subSample);
subSample = null;
}
@Override
public void sampleEnd() {
if (subSample != null) {
subSampleEnd(true);
}
super.sampleEnd();
}
}
|
Fix error when setting JSON value to be `None`
Previously this would raise an attribute error as `None` does not
have the `coerce` attribute. | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if value is None:
return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
| from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
|
Fix loading error on API level 16 and 17 | package com.wonderkiln.camerakit;
import android.graphics.Rect;
import java.nio.ByteBuffer;
public class JpegTransformer {
private ByteBuffer mHandler;
public JpegTransformer(byte[] jpeg) {
mHandler = jniStoreJpeg(jpeg, jpeg.length);
}
public byte[] getJpeg() {
return jniCommit(mHandler);
}
public int getWidth() {
return jniGetWidth(mHandler);
}
public int getHeight() {
return jniGetHeight(mHandler);
}
public void rotate(int degrees) {
jniRotate(mHandler, degrees);
}
public void flipHorizontal() {
jniFlipHorizontal(mHandler);
}
public void flipVertical() {
jniFlipVertical(mHandler);
}
public void crop(Rect crop) {
jniCrop(mHandler, crop.left, crop.top, crop.width(), crop.height());
}
static {
System.loadLibrary("yuvOperator");
System.loadLibrary("jpegTransformer");
}
private native ByteBuffer jniStoreJpeg(byte[] jpeg, int size);
private native byte[] jniCommit(ByteBuffer handler);
private native int jniGetWidth(ByteBuffer handler);
private native int jniGetHeight(ByteBuffer handler);
private native void jniRotate(ByteBuffer handler, int degrees);
private native void jniFlipHorizontal(ByteBuffer handler);
private native void jniFlipVertical(ByteBuffer handler);
private native void jniCrop(ByteBuffer handler, int left, int top, int width, int height);
}
| package com.wonderkiln.camerakit;
import android.graphics.Rect;
import java.nio.ByteBuffer;
public class JpegTransformer {
private ByteBuffer mHandler;
public JpegTransformer(byte[] jpeg) {
mHandler = jniStoreJpeg(jpeg, jpeg.length);
}
public byte[] getJpeg() {
return jniCommit(mHandler);
}
public int getWidth() {
return jniGetWidth(mHandler);
}
public int getHeight() {
return jniGetHeight(mHandler);
}
public void rotate(int degrees) {
jniRotate(mHandler, degrees);
}
public void flipHorizontal() {
jniFlipHorizontal(mHandler);
}
public void flipVertical() {
jniFlipVertical(mHandler);
}
public void crop(Rect crop) {
jniCrop(mHandler, crop.left, crop.top, crop.width(), crop.height());
}
static {
System.loadLibrary("jpegTransformer");
}
private native ByteBuffer jniStoreJpeg(byte[] jpeg, int size);
private native byte[] jniCommit(ByteBuffer handler);
private native int jniGetWidth(ByteBuffer handler);
private native int jniGetHeight(ByteBuffer handler);
private native void jniRotate(ByteBuffer handler, int degrees);
private native void jniFlipHorizontal(ByteBuffer handler);
private native void jniFlipVertical(ByteBuffer handler);
private native void jniCrop(ByteBuffer handler, int left, int top, int width, int height);
}
|
[REF] openacademy: Add domain or and ilike | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor",domain=['|',
("instructor", "=", True),
("category_id", "ilike", "Teacher")
])
course_id = fields.Many2one('openacademy.course',
ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
| # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instructor_id = fields.Many2one('res.partner', string="Instructor")
course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
|
Make future OSS test failures easier to debug
Summary: Show test output on failure.
Reviewed By: jstrizich
Differential Revision: D6914371
fbshipit-source-id: 668feaefd80c3f0253787b89783cb615fe69bf9b | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from shell_quoting import ShellQuoted
# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
return {
'depends_on': [folly, proxygen, fbthrift],
'steps': [
builder.fb_github_project_workdir('bistro/bistro'),
builder.step('Build bistro', [
# Future: should this share some code with `cmake_install()`?
builder.run(ShellQuoted(
'PATH="$PATH:"{p}/bin '
'TEMPLATES_PATH={p}/include/thrift/templates '
'./cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
).format(p=builder.option('prefix'))),
builder.workdir('cmake/Debug'),
builder.parallel_make(),
]),
builder.step('Run bistro tests', [
builder.run(ShellQuoted('ctest --output-on-failure')),
]),
]
}
config = {
'github_project': 'facebook/bistro',
'fbcode_builder_spec': fbcode_builder_spec,
}
| #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from shell_quoting import ShellQuoted
# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
return {
'depends_on': [folly, proxygen, fbthrift],
'steps': [
builder.fb_github_project_workdir('bistro/bistro'),
builder.step('Build bistro', [
# Future: should this share some code with `cmake_install()`?
builder.run(ShellQuoted(
'PATH="$PATH:"{p}/bin '
'TEMPLATES_PATH={p}/include/thrift/templates '
'./cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
).format(p=builder.option('prefix'))),
builder.workdir('cmake/Debug'),
builder.parallel_make(),
]),
builder.step('Run bistro tests', [
builder.run(ShellQuoted('ctest')),
]),
]
}
config = {
'github_project': 'facebook/bistro',
'fbcode_builder_spec': fbcode_builder_spec,
}
|
Correct error in namespace declaration | <?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Text;
/**
* Adds support for Padding a String in Twig
*/
class PadStringExtension extends \Twig_Extension
{
/**
* Name of Extension
*
* @return string
*/
public function getName()
{
return 'PadStringExtension';
}
/**
* Available filters
*
* @return array
*/
public function getFilters()
{
return array(
'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
);
}
/**
* Pads string on right or left with given padCharacter until string
* reaches maxLength
*
* @param string $value
* @param string $padCharacter
* @param int $maxLength
* @param bool $padLeft
* @return string
* @throws \InvalidArgumentException
*/
public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
{
if ( ! is_int($maxLength) ) {
throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
}
if (function_exists('mb_strlen')) {
$padLength = $maxLength - mb_strlen($value);
} else {
$padLength = $maxLength - strlen($value);
}
if ($padLength <= 0) {
return $value;
}
$padString = str_repeat($padCharacter, $padLength);
if ($padLeft) {
return $padString . $value;
}
return $value . $padString;
}
}
| <?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;
/**
* Adds support for Padding a String in Twig
*/
class PadStringExtension extends \Twig_Extension
{
/**
* Name of Extension
*
* @return string
*/
public function getName()
{
return 'PadStringExtension';
}
/**
* Available filters
*
* @return array
*/
public function getFilters()
{
return array(
'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
);
}
/**
* Pads string on right or left with given padCharacter until string
* reaches maxLength
*
* @param string $value
* @param string $padCharacter
* @param int $maxLength
* @param bool $padLeft
* @return string
* @throws \InvalidArgumentException
*/
public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
{
if ( ! is_int($maxLength) ) {
throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
}
if (function_exists('mb_strlen')) {
$padLength = $maxLength - mb_strlen($value);
} else {
$padLength = $maxLength - strlen($value);
}
if ($padLength <= 0) {
return $value;
}
$padString = str_repeat($padCharacter, $padLength);
if ($padLeft) {
return $padString . $value;
}
return $value . $padString;
}
}
|
Add black lines to hud cross |
var ForgePlugins = ForgePlugins || {};
/**
*/
ForgePlugins.EditorHUD = function(editor)
{
this._editor = editor;
this._canvas = null;
this._options = { cross: true };
this._boot();
};
ForgePlugins.EditorHUD.prototype =
{
_boot: function()
{
this._canvas = this._editor.plugin.create.canvas();
this._canvas.maximize(true);
this._editor.plugin.container.addChild(this._canvas);
},
update: function()
{
var ctx = this._canvas.context2D;
ctx.clearRect(0, 0, this._canvas.pixelWidth, this._canvas.pixelHeight);
if(this._options.cross === true)
{
var center = { x: this._canvas.pixelWidth / 2, y: this._canvas.pixelHeight / 2 };
ctx.lineWidth = 4;
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(center.x - 11, center.y);
ctx.lineTo(center.x + 11, center.y);
ctx.moveTo(center.x, center.y - 11);
ctx.lineTo(center.x, center.y + 11);
ctx.stroke();
ctx.lineWidth = 2;
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.moveTo(center.x - 10, center.y);
ctx.lineTo(center.x + 10, center.y);
ctx.moveTo(center.x, center.y - 10);
ctx.lineTo(center.x, center.y + 10);
ctx.stroke();
}
},
destroy: function()
{
this._canvas = null;
}
};
|
var ForgePlugins = ForgePlugins || {};
/**
*/
ForgePlugins.EditorHUD = function(editor)
{
this._editor = editor;
this._canvas = null;
this._options = { cross: true };
this._boot();
};
ForgePlugins.EditorHUD.prototype =
{
_boot: function()
{
this._canvas = this._editor.plugin.create.canvas();
this._canvas.maximize(true);
this._editor.plugin.container.addChild(this._canvas);
},
update: function()
{
var ctx = this._canvas.context2D;
ctx.clearRect(0, 0, this._canvas.pixelWidth, this._canvas.pixelHeight);
if(this._options.cross === true)
{
var center = { x: this._canvas.pixelWidth / 2, y: this._canvas.pixelHeight / 2 };
ctx.lineWidth = 2;
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.moveTo(center.x - 10, center.y);
ctx.lineTo(center.x + 10, center.y);
ctx.moveTo(center.x, center.y - 10);
ctx.lineTo(center.x, center.y + 10);
ctx.stroke();
}
},
destroy: function()
{
this._canvas = null;
}
};
|
Add sort by downlaods for hex accuracy | <?php
namespace WillFarrell\AlfredPkgMan;
require_once('Cache.php');
require_once('Repo.php');
class Hex extends Repo
{
protected $id = 'hex';
protected $kind = 'components';
protected $url = 'https://hex.pm';
protected $search_url = 'https://hex.pm/api/packages?sort=downloads&search=';
public function search($query)
{
if (!$this->hasMinQueryLength($query)) {
return $this->xml();
}
$this->pkgs = $this->cache->get_query_json(
$this->id,
$query,
"{$this->search_url}{$query}"
);
foreach ($this->pkgs as $pkg) {
$url = str_replace('api/', '', $pkg->url);
$this->cache->w->result(
$pkg->url,
$this->makeArg($pkg->name, $url),
$pkg->name,
$url,
"icon-cache/{$this->id}.png"
);
// only search till max return reached
if (count($this->cache->w->results()) == $this->max_return) {
break;
}
}
$this->noResults($query, "{$this->search_url}{$query}");
return $this->xml();
}
}
// Test code, uncomment to debug this script from the command-line
// $repo = new Hex();
// echo $repo->search('test');
| <?php
namespace WillFarrell\AlfredPkgMan;
require_once('Cache.php');
require_once('Repo.php');
class Hex extends Repo
{
protected $id = 'hex';
protected $kind = 'components';
protected $url = 'https://hex.pm';
protected $search_url = 'https://hex.pm/api/packages?search=';
public function search($query)
{
if (!$this->hasMinQueryLength($query)) {
return $this->xml();
}
$this->pkgs = $this->cache->get_query_json(
$this->id,
$query,
"{$this->search_url}{$query}"
);
foreach ($this->pkgs as $pkg) {
$url = str_replace('api/', '', $pkg->url);
$this->cache->w->result(
$pkg->url,
$this->makeArg($pkg->name, $url),
$pkg->name,
$url,
"icon-cache/{$this->id}.png"
);
// only search till max return reached
if (count($this->cache->w->results()) == $this->max_return) {
break;
}
}
$this->noResults($query, "{$this->search_url}{$query}");
return $this->xml();
}
}
// Test code, uncomment to debug this script from the command-line
// $repo = new Hex();
// echo $repo->search('test');
|
Move transaction commit outside try block. | <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline;
use Doctrine\DBAL\Driver\Connection;
class TransactionAwarePipeline implements Pipeline
{
/**
* @var Pipeline
*/
private $innerPipeline;
/**
* @var Connection
*/
private $connection;
/**
* @param Pipeline $innerPipeline
* @param Connection $connection
*/
public function __construct(Pipeline $innerPipeline, Connection $connection)
{
$this->innerPipeline = $innerPipeline;
$this->connection = $connection;
}
public function process($command)
{
$this->connection->beginTransaction();
try {
$command = $this->innerPipeline->process($command);
} catch (\Exception $e) {
$this->connection->rollBack();
throw $e;
}
$this->connection->commit();
return $command;
}
}
| <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline;
use Doctrine\DBAL\Driver\Connection;
class TransactionAwarePipeline implements Pipeline
{
/**
* @var Pipeline
*/
private $innerPipeline;
/**
* @var Connection
*/
private $connection;
/**
* @param Pipeline $innerPipeline
* @param Connection $connection
*/
public function __construct(Pipeline $innerPipeline, Connection $connection)
{
$this->innerPipeline = $innerPipeline;
$this->connection = $connection;
}
public function process($command)
{
$this->connection->beginTransaction();
try {
$command = $this->innerPipeline->process($command);
$this->connection->commit();
} catch (\Exception $e) {
$this->connection->rollBack();
throw $e;
}
return $command;
}
}
|
Add static factory method for settings. |
package com.zygon.htm.core;
import com.google.common.util.concurrent.AbstractScheduledService;
import java.util.concurrent.TimeUnit;
/**
*
* @author zygon
*/
public abstract class AbstractScheduledServiceImpl extends AbstractScheduledService {
public static final class Settings {
public static Settings create(long period, TimeUnit timeUnit) {
Settings s = new Settings();
s.setPeriod(period);
s.setTimeUnit(timeUnit);
return s;
}
private long period = 0;
private TimeUnit timeUnit = TimeUnit.SECONDS;
public long getPeriod() {
return period;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public void setPeriod(long period) {
this.period = period;
}
public void setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
}
private final Scheduler scheduler;
protected AbstractScheduledServiceImpl(Settings settings) {
super();
if (settings == null) {
// defaults
settings = new Settings();
}
this.scheduler = Scheduler.newFixedRateSchedule(0, settings.getPeriod(), settings.getTimeUnit());
}
protected abstract void doRun() throws Exception;
@Override
protected final void runOneIteration() throws Exception {
try {
this.doRun();
} catch (Exception e) {
// TODO: log?
e.printStackTrace();
}
}
@Override
protected final Scheduler scheduler() {
return this.scheduler;
}
}
|
package com.zygon.htm.core;
import com.google.common.util.concurrent.AbstractScheduledService;
import java.util.concurrent.TimeUnit;
/**
*
* @author zygon
*/
public abstract class AbstractScheduledServiceImpl extends AbstractScheduledService {
public static final class Settings {
private long period = 0;
private TimeUnit timeUnit = TimeUnit.SECONDS;
public long getPeriod() {
return period;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public void setPeriod(long period) {
this.period = period;
}
public void setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
}
private final Scheduler scheduler;
protected AbstractScheduledServiceImpl(Settings settings) {
super();
if (settings == null) {
// defaults
settings = new Settings();
}
this.scheduler = Scheduler.newFixedRateSchedule(0, settings.getPeriod(), settings.getTimeUnit());
}
protected abstract void doRun() throws Exception;
@Override
protected final void runOneIteration() throws Exception {
try {
this.doRun();
} catch (Exception e) {
// TODO: log?
e.printStackTrace();
}
}
@Override
protected final Scheduler scheduler() {
return this.scheduler;
}
}
|
Add nginx rules for pretty URLs | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
from nib import Resource, Processor, after
apache_redirects = b"""
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)$ /$1/index.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)$ /$1.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)/$ /$1 [L,R]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)/$ /$1 [L,R]
"""
apache_redirects_base = b"""
RewriteEngine on
RewriteBase /
"""
nginx_rules = b"""
location / {
#root {0};
index index.html;
try_files $uri $uri.html $uri/index.html;
}
"""
@after
class PrettyURLProcessor(Processor):
def process(self, documents, resources):
for document in documents:
filename = path.basename(document.uri)
if filename == 'index.html':
document.uri = path.dirname(document.path)
elif document.extension == '.html':
document.uri = document.path
htaccess = None
for resource in resources:
if resource.path == '.htaccess':
htaccess = resource
if not htaccess:
htaccess = Resource(path='.htaccess',
content=apache_redirects_base)
resources.append(htaccess)
htaccess.content += apache_redirects
nginx = Resource(path='.nginx',
content=nginx_rules)
resources.append(nginx)
return documents, resources
| from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
from nib import Resource, Processor, after
apache_redirects = b"""
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)$ /$1/index.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)$ /$1.html [L]
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule ^(.*)/$ /$1 [L,R]
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.*)/$ /$1 [L,R]
"""
apache_redirects_base = b"""
RewriteEngine on
RewriteBase /
"""
@after
class PrettyURLProcessor(Processor):
def process(self, documents, resources):
for document in documents:
filename = path.basename(document.uri)
if filename == 'index.html':
document.uri = path.dirname(document.path)
elif document.extension == '.html':
document.uri = document.path
htaccess = None
for resource in resources:
if resource.path == '.htaccess':
htaccess = resource
if not htaccess:
htaccess = Resource(path='.htaccess',
content=apache_redirects_base)
resources.append(htaccess)
htaccess.content += apache_redirects
return documents, resources
|
feat: Add function to remove reacted to urls | from . import parser
from . import printer
from . import firebase as fb
from . import reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_cache):
return url_cache is not None
def is_reaction(index):
return index is not None
def remove_url_from(url_cache_list, index):
url_cache_list.pop(index)
def event_consumer(expecting_url, url_cache_list, slack_client,
fb_credentials, firebase):
# Read slack events
events = slack_client.rtm_read()
if is_empty(events):
return (expecting_url, url_cache)
for event in events:
print(event)
if expecting_url and event['type'] == 'message':
new_url_cache = parser.parse_url_message(event)
url_cache_list.append(new_url_cache)
if is_url(new_url_cache):
printer.ask_confirmation(new_url_cache, slack_client)
if event['type'] == 'reaction_added':
reaction = parser.parse_reaction_added(event)
index = react.is_confirmation(reaction['reaction'], url_cache_list,
reaction['to_id']):
if is_reaction(index):
react.handle(reaction['reaction'], url_cache_list[index]['url'],
fb_credentials, firebase)
remove_url_from(url_cache_list, index)
return (expecting_url, url_cache_list)
| from . import parser
from . import printer
from . import firebase as fb
from . import reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_cache):
return url_cache is not None
def is_reaction(index):
return index is not None
def event_consumer(expecting_url, url_cache_list, slack_client,
fb_credentials, firebase):
# Read slack events
events = slack_client.rtm_read()
if is_empty(events):
return (expecting_url, url_cache)
for event in events:
print(event)
if expecting_url and event['type'] == 'message':
new_url_cache = parser.parse_url_message(event)
url_cache_list.append(new_url_cache)
if is_url(new_url_cache):
printer.ask_confirmation(new_url_cache, slack_client)
if event['type'] == 'reaction_added':
reaction = parser.parse_reaction_added(event)
index = react.is_confirmation(reaction['reaction'], url_cache_list,
reaction['to_id']):
if is_reaction(index):
react.handle(reaction['reaction'], url_cache_list[index]['url'],
fb_credentials, firebase)
remove_url_from(url_cache_list)
return (expecting_url, url_cache)
|
FIX Typo in requirements call to TreeDropdownField javascript resource | <?php
namespace SilverStripe\Subsites\Forms;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\View\Requirements;
use SilverStripe\Subsites\State\SubsiteState;
/**
* Wraps around a TreedropdownField to add ability for temporary
* switching of subsite sessions.
*
* @package subsites
*/
class SubsitesTreeDropdownField extends TreeDropdownField
{
private static $allowed_actions = [
'tree'
];
protected $subsiteID = 0;
/**
* Extra HTML classes
*
* @skipUpgrade
* @var string[]
*/
protected $extraClasses = ['SubsitesTreeDropdownField'];
public function Field($properties = [])
{
$html = parent::Field($properties);
Requirements::javascript('silverstripe/subsites:javascript/SubsitesTreeDropdownField.js');
return $html;
}
public function setSubsiteID($id)
{
$this->subsiteID = $id;
}
public function getSubsiteID()
{
return $this->subsiteID;
}
public function tree(HTTPRequest $request)
{
$results = SubsiteState::singleton()->withState(function () use ($request) {
SubsiteState::singleton()->setSubsiteId($this->subsiteID);
return parent::tree($request);
});
return $results;
}
}
| <?php
namespace SilverStripe\Subsites\Forms;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\View\Requirements;
use SilverStripe\Subsites\State\SubsiteState;
/**
* Wraps around a TreedropdownField to add ability for temporary
* switching of subsite sessions.
*
* @package subsites
*/
class SubsitesTreeDropdownField extends TreeDropdownField
{
private static $allowed_actions = [
'tree'
];
protected $subsiteID = 0;
/**
* Extra HTML classes
*
* @skipUpgrade
* @var string[]
*/
protected $extraClasses = ['SubsitesTreeDropdownField'];
public function Field($properties = [])
{
$html = parent::Field($properties);
Requirements::javascript('silverstripe/subsitesjavascript/SubsitesTreeDropdownField.js');
return $html;
}
public function setSubsiteID($id)
{
$this->subsiteID = $id;
}
public function getSubsiteID()
{
return $this->subsiteID;
}
public function tree(HTTPRequest $request)
{
$results = SubsiteState::singleton()->withState(function () use ($request) {
SubsiteState::singleton()->setSubsiteId($this->subsiteID);
return parent::tree($request);
});
return $results;
}
}
|
Replace depricated array helper method | <?php
namespace SocialiteProviders\Manager;
use Illuminate\Support\Arr;
use SocialiteProviders\Manager\Contracts\ConfigInterface;
trait ConfigTrait
{
/**
* @var array
*/
protected $config;
/**
* @param \SocialiteProviders\Manager\Contracts\OAuth1\ProviderInterface|\SocialiteProviders\Manager\Contracts\OAuth2\ProviderInterface $config
*/
public function setConfig(ConfigInterface $config)
{
$config = $config->get();
$this->config = $config;
$this->clientId = $config['client_id'];
$this->clientSecret = $config['client_secret'];
$this->redirectUrl = $config['redirect'];
return $this;
}
/**
* @return array
*/
public static function additionalConfigKeys()
{
return [];
}
/**
* @param string $key
* @param mixed $default
*
* @return mixed|array
*/
protected function getConfig($key = null, $default = null)
{
// check manually if a key is given and if it exists in the config
// this has to be done to check for spoofed additional config keys so that null isn't returned
if (!empty($key) && empty($this->config[$key])) {
return $default;
}
return $key ? Arr::get($this->config, $key, $default) : $this->config;
}
}
| <?php
namespace SocialiteProviders\Manager;
use SocialiteProviders\Manager\Contracts\ConfigInterface;
trait ConfigTrait
{
/**
* @var array
*/
protected $config;
/**
* @param \SocialiteProviders\Manager\Contracts\OAuth1\ProviderInterface|\SocialiteProviders\Manager\Contracts\OAuth2\ProviderInterface $config
*/
public function setConfig(ConfigInterface $config)
{
$config = $config->get();
$this->config = $config;
$this->clientId = $config['client_id'];
$this->clientSecret = $config['client_secret'];
$this->redirectUrl = $config['redirect'];
return $this;
}
/**
* @return array
*/
public static function additionalConfigKeys()
{
return [];
}
/**
* @param string $key
* @param mixed $default
*
* @return mixed|array
*/
protected function getConfig($key = null, $default = null)
{
// check manually if a key is given and if it exists in the config
// this has to be done to check for spoofed additional config keys so that null isn't returned
if (!empty($key) && empty($this->config[$key])) {
return $default;
}
return $key ? array_get($this->config, $key, $default) : $this->config;
}
}
|
Reformat code to PEP-8 standards | #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from boundary import ApiCli
class PluginGetComponents(ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/plugins"
self.pluginName = None
def addArguments(self):
ApiCli.addArguments(self)
self.parser.add_argument('-n', '--plugin-Name', dest='pluginName', action='store', metavar='plugin_name',
required=True, help='Plugin name')
def getArguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.getArguments(self)
if self.args.pluginName is not None:
self.pluginName = self.args.pluginName
self.path = "v1/plugins/{0}/components".format(self.pluginName)
def getDescription(self):
return "Get the components of a plugin in a Boundary account"
| #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from boundary import ApiCli
class PluginGetComponents (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path="v1/plugins"
self.pluginName = None
def addArguments(self):
ApiCli.addArguments(self)
self.parser.add_argument('-n', '--plugin-Name', dest='pluginName',action='store',required=True,help='Plugin name')
def getArguments(self):
'''
Extracts the specific arguments of this CLI
'''
ApiCli.getArguments(self)
if self.args.pluginName != None:
self.pluginName = self.args.pluginName
self.path = "v1/plugins/{0}/components".format(self.pluginName)
def getDescription(self):
return "Get the components of a plugin in a Boundary account"
|
Add set status text to java file | package seedu.watodo.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.watodo.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label description;
@FXML
private Label status;
@FXML
private Label id;
@FXML
private Label startDate;
@FXML
private Label endDate;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
description.setText(task.getDescription().fullDescription);
id.setText(displayedIndex + ". ");
if (task.getStartDate() != null) {
startDate.setText("Start Task From " + task.getStartDate());
} else {
startDate.setText("");
}
if (task.getEndDate() != null) {
endDate.setText("Do Task By " + task.getEndDate());
} else {
endDate.setText("");
}
status.setText(task.getStatus().toString());
initTags(task);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
| package seedu.watodo.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.watodo.model.task.ReadOnlyTask;
public class TaskCard extends UiPart<Region> {
private static final String FXML = "TaskListCard.fxml";
@FXML
private HBox cardPane;
@FXML
private Label description;
@FXML
private Label id;
@FXML
private Label startDate;
@FXML
private Label endDate;
@FXML
private FlowPane tags;
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
description.setText(task.getDescription().fullDescription);
id.setText(displayedIndex + ". ");
if (task.getStartDate() != null) {
startDate.setText("Start Task From " + task.getStartDate());
} else {
startDate.setText("");
}
if (task.getEndDate() != null) {
endDate.setText("Do Task By " + task.getEndDate());
} else {
endDate.setText("");
}
initTags(task);
}
private void initTags(ReadOnlyTask person) {
person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
|
Add CSS class for button group items. | <?php
// check if groups are not empty
foreach ($groups as $key => $group) {
$exists = false;
foreach ($group as $action => $config) {
$subaction = is_array($config) ? $action : $config;
if (array_key_exists($subaction, $links)) {
$exists = true;
}
}
if (!$exists) {
unset($groups[$key]);
}
}
?>
<?php foreach ($groups as $key => $group) : ?>
<div class='btn-group'>
<?= $this->Html->link(
sprintf("%s %s", $key, $this->Html->tag('span', '', ['class' => 'caret'])),
'#',
['class' => 'btn btn-default dropdown-toggle', 'escape' => false, 'data-toggle' => 'dropdown', 'aria-haspopup' => true, 'aria-expanded' => false]
) ?>
<ul class="dropdown-menu pull-right">
<?php foreach ($group as $action => $config) : ?>
<?php $subaction = is_array($config) ? $action : $config; ?>
<?php if (array_key_exists($subaction, $links)): ?>
<li class="dropdown-item"><?= $this->element('action-button', ['config' => $links[$subaction]]); ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
<?php
endforeach;
| <?php
// check if groups are not empty
foreach ($groups as $key => $group) {
$exists = false;
foreach ($group as $action => $config) {
$subaction = is_array($config) ? $action : $config;
if (array_key_exists($subaction, $links)) {
$exists = true;
}
}
if (!$exists) {
unset($groups[$key]);
}
}
?>
<?php foreach ($groups as $key => $group) : ?>
<div class='btn-group'>
<?= $this->Html->link(
sprintf("%s %s", $key, $this->Html->tag('span', '', ['class' => 'caret'])),
'#',
['class' => 'btn btn-default dropdown-toggle', 'escape' => false, 'data-toggle' => 'dropdown', 'aria-haspopup' => true, 'aria-expanded' => false]
) ?>
<ul class="dropdown-menu pull-right">
<?php foreach ($group as $action => $config) : ?>
<?php $subaction = is_array($config) ? $action : $config; ?>
<?php if (array_key_exists($subaction, $links)): ?>
<li><?= $this->element('action-button', ['config' => $links[$subaction]]); ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
<?php
endforeach;
|
Fix that the logger was lost | <?php
/*
* (c) webfactory GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webfactory\ContentMapping\SourceAdapter\Propel;
use Psr\Log\LoggerInterface;
/**
* Automagically implementation of the adapter for Propel as a source system.
*
* @final by default
*/
final class GenericPropelSourceAdapter extends PropelSourceAdapter
{
/**
* @var string Name of the class of the objects provided by this source.
*/
protected $className;
/**
* @var string Name of the method to call on the peer to get the objects ordered by their id.
*/
protected $resultSetMethod;
/**
* @param string $className Name of the class of the objects provided by this source.
* @param string $resultSetMethod Name of the method to call on the peer to get the objects ordered by their id.
* @param LoggerInterface|null $logger
*/
public function __construct($className, $resultSetMethod = 'doSelectRS', LoggerInterface $logger = null)
{
$this->className = $className;
$this->resultSetMethod = $resultSetMethod;
$this->setLogger($logger);
}
/**
* @return mixed|null
*/
protected function createPeer()
{
$cls = \Classloader::load("{$this->className}Peer");
return new $cls();
}
/**
* {@inheritDoc}
*/
protected function createResultSet($peer, \Criteria $criteria)
{
return $peer->{$this->resultSetMethod}($criteria);
}
}
| <?php
/*
* (c) webfactory GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webfactory\ContentMapping\SourceAdapter\Propel;
use Psr\Log\LoggerInterface;
/**
* Automagically implementation of the adapter for Propel as a source system.
*
* @final by default
*/
final class GenericPropelSourceAdapter extends PropelSourceAdapter
{
/**
* @var string Name of the class of the objects provided by this source.
*/
protected $className;
/**
* @var string Name of the method to call on the peer to get the objects ordered by their id.
*/
protected $resultSetMethod;
/**
* @param string $className Name of the class of the objects provided by this source.
* @param string $resultSetMethod Name of the method to call on the peer to get the objects ordered by their id.
* @param LoggerInterface|null $logger
*/
public function __construct($className, $resultSetMethod = 'doSelectRS', LoggerInterface $logger = null)
{
$this->className = $className;
$this->resultSetMethod = $resultSetMethod;
$this->logger = $this->setLogger($logger);
}
/**
* @return mixed|null
*/
protected function createPeer()
{
$cls = \Classloader::load("{$this->className}Peer");
return new $cls();
}
/**
* {@inheritDoc}
*/
protected function createResultSet($peer, \Criteria $criteria)
{
return $peer->{$this->resultSetMethod}($criteria);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.