text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Return all collections when db is supplied | var comongo = require('co-mongo');
module.exports = function* mongo(host, port, db) {
var connectionStr = 'mongodb://' + (host || '127.0.0.1') + ':' + (port || 27017),
ignoredCollections = ['system.indexes'];
if (typeof db === 'string') {
connectionStr += '/' + db;
}
try {
var conn = yield comongo.connect(connectionStr),
collections = [];
if (typeof db === 'string') {
var db_collections = yield conn.collections();
collections = db_collections.reduce(function (buf, col) {
var name = col._collection.collectionName;
if (ignoredCollections.indexOf(name) === -1) {
buf.push(name);
}
return buf;
}, []);
}
yield conn.close();
return collections.length === 0 ? false : collections;
} catch (e) {
console.log('Mongodb: error connecting to '+ connectionStr, e.stack);
return false;
}
};
| var exec = require('child_process').execSync;
var iter = require('super-iter');
var comongo = require('co-mongo');
var findIndex = iter.findIndex;
module.exports = function* mongodb(host, port, db, collections) {
var connection = 'mongodb://' + (host || '127.0.0.1') + ':' + (port || 27017);
if (db && typeof db === 'string') {
connection += '/' + db;
if (collections) {
if (!Array.isArray(collections)) {
collections = [collections];
}
}
else {
collections = null;
}
}
var db = yield comongo.connect(connection);
if (Array.isArray(collections)) {
var db_collections = yield db.collections();
return collections.reduce(function(acc, name) {
var index = findIndex(db_collections, function(col) {
return col._collection.collectionName === name;
});
acc[name] = index > -1;
return acc;
}, {});
}
return !(db instanceof Error);
};
|
Remove version number from Python shebang.
On special request from someone trying to purge python2.2 from code indexed
internally at Google.
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@7071 4ff67af0-8c30-449e-8e8b-ad334ec8d88c | #!/usr/bin/python
# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import md5
"""64-bit fingerprint support for strings.
Usage:
from extern import FP
print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!')
"""
def UnsignedFingerPrint(str, encoding='utf-8'):
"""Generate a 64-bit fingerprint by taking the first half of the md5
of the string."""
hex128 = md5.new(str).hexdigest()
int64 = long(hex128[:16], 16)
return int64
def FingerPrint(str, encoding='utf-8'):
fp = UnsignedFingerPrint(str, encoding=encoding)
# interpret fingerprint as signed longs
if fp & 0x8000000000000000L:
fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1)
return fp
| #!/usr/bin/python2.2
# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import md5
"""64-bit fingerprint support for strings.
Usage:
from extern import FP
print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!')
"""
def UnsignedFingerPrint(str, encoding='utf-8'):
"""Generate a 64-bit fingerprint by taking the first half of the md5
of the string."""
hex128 = md5.new(str).hexdigest()
int64 = long(hex128[:16], 16)
return int64
def FingerPrint(str, encoding='utf-8'):
fp = UnsignedFingerPrint(str, encoding=encoding)
# interpret fingerprint as signed longs
if fp & 0x8000000000000000L:
fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1)
return fp
|
Add to doc string: time complexity | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def quick_sort(a_list):
"""Quick sort algortihm with list comprehension recursion.
Time complexity: O(n*logn).
"""
if len(a_list) <= 1:
return a_list
pivot_value = a_list[len(a_list) // 2]
left_list = [x for x in a_list if x < pivot_value]
middle_list = [x for x in a_list if x == pivot_value]
right_list = [x for x in a_list if x > pivot_value]
return quick_sort(left_list) + middle_list + quick_sort(right_list)
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('Quick sort with list comprehension: ')
print(quick_sort(a_list))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def quick_sort(a_list):
"""Quick sort algortihm with list comprehension recursion."""
if len(a_list) <= 1:
return a_list
pivot_value = a_list[len(a_list) // 2]
left_list = [x for x in a_list if x < pivot_value]
middle_list = [x for x in a_list if x == pivot_value]
right_list = [x for x in a_list if x > pivot_value]
return quick_sort(left_list) + middle_list + quick_sort(right_list)
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('Quick sort with list comprehension: ')
print(quick_sort(a_list))
if __name__ == '__main__':
main()
|
Fix typo in setting default time zone for game
Close #110 | utils = {
startsAtMomentWithOffset: function (game) {
var offset = game.location.utc_offset;
if (! Match.test(offset, UTCOffset)) {
offset = -8; // Default to California
}
// UTC offsets returned by Google Places API,
// which is the source of game.location.utc_offset,
// differ in sign from what is expected by moment.js
return moment(game.startsAt).zone(-offset);
},
displayTime: function (game) {
return utils.startsAtMomentWithOffset(game).format('ddd h:mma');
},
// Same-day-ness depends on the known timezone of the game,
// not the timezone of the system executing this function.
isToday: function (game) {
var gameWhen = utils.startsAtMomentWithOffset(game);
var now = utils.startsAtMomentWithOffset(
// clone of game that starts now
_.extend({startsAt: new Date()}, _.omit(game, 'startsAt'))
);
return gameWhen.isSame(now, 'day');
},
// Markdown->HTML
converter: new Showdown.converter()
};
| utils = {
startsAtMomentWithOffset: function (game) {
var offset = game.location.utc_offset;
if (! Match.test(offset, UTCOffset)) {
offset: -8; // Default to California
}
// UTC offsets returned by Google Places API,
// which is the source of game.location.utc_offset,
// differ in sign from what is expected by moment.js
return moment(game.startsAt).zone(-offset);
},
displayTime: function (game) {
return utils.startsAtMomentWithOffset(game).format('ddd h:mma');
},
// Same-day-ness depends on the known timezone of the game,
// not the timezone of the system executing this function.
isToday: function (game) {
var gameWhen = utils.startsAtMomentWithOffset(game);
var now = utils.startsAtMomentWithOffset(
// clone of game that starts now
_.extend({startsAt: new Date()}, _.omit(game, 'startsAt'))
);
return gameWhen.isSame(now, 'day');
},
// Markdown->HTML
converter: new Showdown.converter()
};
|
Fix get_sort_by_toggle to work with QueryDicts with multiple values | from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Library()
@register.filter
def slice(items, group_size=1):
args = [iter(items)] * group_size
return (filter(None, group)
for group in zip_longest(*args, fillvalue=None))
@register.simple_tag(takes_context=True)
def get_sort_by_url(context, field, descending=False):
request = context['request']
request_get = request.GET.dict()
if descending:
request_get['sort_by'] = '-' + field
else:
request_get['sort_by'] = field
return '%s?%s' % (request.path, urlencode(request_get))
@register.simple_tag(takes_context=True)
def get_sort_by_url_toggle(context, field):
request = context['request']
request_get = request.GET.copy()
if field == request_get.get('sort_by'):
new_sort_by = u'-%s' % field # descending sort
else:
new_sort_by = field # ascending sort
request_get['sort_by'] = new_sort_by
return '%s?%s' % (request.path, request_get.urlencode())
| from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Library()
@register.filter
def slice(items, group_size=1):
args = [iter(items)] * group_size
return (filter(None, group)
for group in zip_longest(*args, fillvalue=None))
@register.simple_tag(takes_context=True)
def get_sort_by_url(context, field, descending=False):
request = context['request']
request_get = request.GET.dict()
if descending:
request_get['sort_by'] = '-' + field
else:
request_get['sort_by'] = field
return '%s?%s' % (request.path, urlencode(request_get))
@register.simple_tag(takes_context=True)
def get_sort_by_url_toggle(context, field):
request = context['request']
request_get = request.GET.dict()
if field == request_get.get('sort_by'):
new_sort_by = '-%s' % field # descending sort
else:
new_sort_by = field # ascending sort
request_get['sort_by'] = new_sort_by
return '%s?%s' % (request.path, urlencode(request_get))
|
Handle files without a clip path | <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace Imbo\Image\Transformation;
use Imbo\Exception\TransformationException,
ImagickException;
/**
* Clip transformation
*
* @author Mats Lindh <mats@lindh.no>
* @package Image\Transformations
*/
class Clip extends Transformation {
/**
* {@inheritdoc}
*/
public function transform(array $params) {
try {
$this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_TRANSPARENT);
$this->imagick->clipImage();
$this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_OPAQUE);
} catch (ImagickException $e) {
// NoClipPathDefined - the image doesn't have a clip path, but this isn't an fatal error.
if ($e->getCode() == 410) {
return;
}
throw new TransformationException($e->getMessage(), 400, $e);
}
$this->image->hasBeenTransformed(true);
}
}
| <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace Imbo\Image\Transformation;
use Imbo\Exception\TransformationException,
ImagickException;
/**
* Clip transformation
*
* @author Mats Lindh <mats@lindh.no>
* @package Image\Transformations
*/
class Clip extends Transformation {
/**
* {@inheritdoc}
*/
public function transform(array $params) {
try {
$this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_TRANSPARENT);
$this->imagick->clipImage();
$this->imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_OPAQUE);
} catch (ImagickException $e) {
throw new TransformationException($e->getMessage(), 400, $e);
}
$this->image->hasBeenTransformed(true);
}
}
|
Set to work with all users, not testing user | <?php umask (0027);
/*The user's umask is ignored for the user running php, so we need
to set it from inside of php to make sure the group read & execute
permissions aren't lost for newly created files & directories.*/
// ============================================
// GET THE USERNAME OF THE AUTHENTICATED USER
// ============================================
if (isset($_SERVER['PHP_AUTH_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
} else if (isset($_SERVER['REMOTE_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
} else {
// if not already authenticated do it
//
echo 'Internal Error - Not Authenticated'; exit();//here
//
}
//Remove error reporting and ini set for production code
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$_SESSION["id"] = $user;
if (isset($_GET["page"])) {
$page = htmlspecialchars($_GET["page"]);
} else {
$page = "homework";
}
//This needs to be wrapped around session Ids and logins
if ($page == "upload") {
require_once("controller/upload.php");
} else if ($page == "update") {
require_once("controller/update.php");
} else if ($page == "checkrefresh") {
require_once("controller/check_refresh.php");
} else {
require_once("controller/homework.php");
}
?>
| <?php umask (0027);
/*The user's umask is ignored for the user running php, so we need
to set it from inside of php to make sure the group read & execute
permissions aren't lost for newly created files & directories.*/
// ============================================
// GET THE USERNAME OF THE AUTHENTICATED USER
// ============================================
/*
if (isset($_SERVER['PHP_AUTH_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
} else if (isset($_SERVER['REMOTE_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
} else {
// if not already authenticated do it
//
echo 'Internal Error - Not Authenticated'; exit();//here
//
}
*/
$user = "sengs";
//Remove error reporting and ini set for production code
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$_SESSION["id"] = $user;
if (isset($_GET["page"])) {
$page = htmlspecialchars($_GET["page"]);
} else {
$page = "homework";
}
//This needs to be wrapped around session Ids and logins
if ($page == "upload") {
require_once("controller/upload.php");
} else if ($page == "update") {
require_once("controller/update.php");
} else if ($page == "checkrefresh") {
require_once("controller/check_refresh.php");
} else {
require_once("controller/homework.php");
}
?>
|
Fix missing cmd name in error message | import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
| import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
Fix LocalizedFieldsAdminMixin not having a base class
This was a breaking change and broke a lot of projects. | from django.contrib.admin import ModelAdmin
from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin(ModelAdmin):
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
| from . import widgets
from .fields import LocalizedField, LocalizedCharField, LocalizedTextField, \
LocalizedFileField
FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS = {
LocalizedField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedCharField: {'widget': widgets.AdminLocalizedCharFieldWidget},
LocalizedTextField: {'widget': widgets.AdminLocalizedFieldWidget},
LocalizedFileField: {'widget': widgets.AdminLocalizedFileFieldWidget},
}
class LocalizedFieldsAdminMixin:
"""Mixin for making the fancy widgets work in Django Admin."""
class Media:
css = {
'all': (
'localized_fields/localized-fields-admin.css',
)
}
js = (
'localized_fields/localized-fields-admin.js',
)
def __init__(self, *args, **kwargs):
"""Initializes a new instance of :see:LocalizedFieldsAdminMixin."""
super().__init__(*args, **kwargs)
overrides = FORMFIELD_FOR_LOCALIZED_FIELDS_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
|
Change the color of bars in the result scene | var ResultScene = InformationScene.extend({
ctor: function (game) {
this._super(game);
return true;
},
createSceneNode: function () {
return ccs.sceneReader.createNodeWithSceneFile(res.json.resultScene);
},
getLovePanelMode: function () {
return InformationScene.BAR_LOVE_PANEL_MODE;
},
setupPlayerPanels: function () {
this._super();
var rankedPlayers = this.game.getRanking();
var maxPopularity = _.max(_.map(rankedPlayers, function (player) {
return player.getPopularity();
}, this));
_.each(rankedPlayers, function (player) {
var playerPanel = this.getPlayerPanel(player.index);
var popularityBarName = (player.getPopularity() >= 0 ? 'PositivePopularityBar' : 'NegativePopularityBar');
var popularityBar = playerPanel.getChildByName(popularityBarName);
popularityBar.loadTexture(res.image.revealedBars[player.index], ccui.Widget.LOCAL_TEXTURE);
popularityBar.setPercent(Math.abs(player.getPopularity()) / maxPopularity * 100);
}, this);
},
});
| var ResultScene = InformationScene.extend({
ctor: function (game) {
this._super(game);
return true;
},
createSceneNode: function () {
return ccs.sceneReader.createNodeWithSceneFile(res.json.resultScene);
},
getLovePanelMode: function () {
return InformationScene.BAR_LOVE_PANEL_MODE;
},
setupPlayerPanels: function () {
this._super();
var rankedPlayers = this.game.getRanking();
var maxPopularity = _.max(_.map(rankedPlayers, function (player) {
return player.getPopularity();
}, this));
_.each(rankedPlayers, function (player) {
var playerPanel = this.getPlayerPanel(player.index);
var popularityBarName = (player.getPopularity() >= 0 ? 'PositivePopularityBar' : 'NegativePopularityBar');
playerPanel.getChildByName(popularityBarName).setPercent(Math.abs(player.getPopularity()) / maxPopularity * 100);
}, this);
},
});
|
Read README.rst into long_description instead | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="django-deployer",
version="0.1.0",
description="Django deployment utility for popular PaaS providers",
long_description=open('README.rst').read(),
author="Nate Aune",
author_email="nate@appsembler.com",
url="https://github.com/natea/django-deployer",
packages=find_packages(),
install_requires=[
'fabric==1.6.0', # formerly 1.4.3
'jinja2==2.6',
'heroku',
'dotcloud',
'gondor',
'pyyaml',
'sphinx==1.1.3',
],
classifiers=(
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: GPL License",
"Programming Language :: Python",
),
entry_points={
'console_scripts' : [
'deployer-init = django_deployer.main:add_fabfile',
]
},
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="django-deployer",
version="0.1.0",
description="Django deployment utility for popular PaaS providers",
long_description=open('README.md').read(),
author="Nate Aune",
author_email="nate@appsembler.com",
url="https://github.com/natea/django-deployer",
packages=find_packages(),
install_requires=[
'fabric==1.6.0', # formerly 1.4.3
'jinja2==2.6',
'heroku',
'dotcloud',
'gondor',
'pyyaml',
'sphinx==1.1.3',
],
classifiers=(
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: GPL License",
"Programming Language :: Python",
),
entry_points={
'console_scripts' : [
'deployer-init = django_deployer.main:add_fabfile',
]
},
)
|
Add test for bspwm widget |
from collections import OrderedDict
import pytest
from barython.hooks.bspwm import BspwmHook
def test_bspwm_hook_parse_event():
bh = BspwmHook()
status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:"
"mDVI-I-0:Od:LT")
expected = OrderedDict([
('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}),
('DVI-D-0', {
'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq',
'fi'],
'focused': True, 'layout': 'T'
}),
('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'})
])
assert expected == bh.parse_event(status)["monitors"]
|
from collections import OrderedDict
import pytest
from barython.hooks.bspwm import BspwmHook
def test_bspwm_hook_parse_event():
bh = BspwmHook()
status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:"
"mDVI-I-0:Od:LT")
expected = OrderedDict([
('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}),
('DVI-D-0', {
'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq',
'fi'],
'focused': True, 'layout': 'T'
}),
('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'})
])
assert expected == bh.parse_event(status)
|
Mark requirement for python 3.6 | try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
"ar": ["arpy==1.1.1"],
}
)
| try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='cle',
description='CLE Loads Everything (at least, many binary formats!) and provides a pythonic interface to analyze what they are and what they would look like in memory.',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
install_requires=[
'pyelftools>=0.25',
'cffi',
'pyvex==8.20.1.7',
'pefile',
'sortedcontainers>=2.0',
],
extras_require={
"minidump": ["minidump==0.0.10"],
"xbe": ["pyxbe==0.0.2"],
"ar": ["arpy==1.1.1"],
}
)
|
Revert "Fix bbl up for AWS"
This reverts commit 94599faddf4921e2ad53ffe47755b4b89ebd3a41.
[#139857703]
Signed-off-by: Christian Ang <15ae83feccf4d84083a62aba1cdf46bd8ce2e33b@pivotal.io> | package ec2
import (
"errors"
goaws "github.com/aws/aws-sdk-go/aws"
awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)
type AvailabilityZoneRetriever struct {
ec2ClientProvider ec2ClientProvider
}
func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
return AvailabilityZoneRetriever{
ec2ClientProvider: ec2ClientProvider,
}
}
func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
Filters: []*awsec2.Filter{{
Name: goaws.String("region-name"),
Values: []*string{goaws.String(region)},
}},
})
if err != nil {
return []string{}, err
}
azList := []string{}
for _, az := range output.AvailabilityZones {
if az == nil {
return []string{}, errors.New("aws returned nil availability zone")
}
if az.ZoneName == nil {
return []string{}, errors.New("aws returned availability zone with nil zone name")
}
azList = append(azList, *az.ZoneName)
}
return azList, nil
}
| package ec2
import (
"errors"
goaws "github.com/aws/aws-sdk-go/aws"
awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)
type AvailabilityZoneRetriever struct {
ec2ClientProvider ec2ClientProvider
}
func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
return AvailabilityZoneRetriever{
ec2ClientProvider: ec2ClientProvider,
}
}
func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
Filters: []*awsec2.Filter{{
Name: goaws.String("region-name"),
Values: []*string{goaws.String(region)},
}},
})
if err != nil {
return []string{}, err
}
azList := []string{}
for _, az := range output.AvailabilityZones {
if az == nil {
return []string{}, errors.New("aws returned nil availability zone")
}
if az.ZoneName == nil {
return []string{}, errors.New("aws returned availability zone with nil zone name")
}
if *az.ZoneName != "us-east-1d" {
azList = append(azList, *az.ZoneName)
}
}
return azList, nil
}
|
Add modals for creating objects | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""Modals for creating new objects"""
from lib.page.modal import base
class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal):
"""Class representing a program modal visible after creating a new
program from LHN"""
class NewControlModal(base.ControlModal, base.CreateNewObjectModal):
"""Class representing a control modal visible after creating a new
control from LHN"""
class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal):
"""Class representing an org group modal visible after creating a new
org group from LHN"""
class NewRiskModal(base.RiskModal, base.CreateNewObjectModal):
"""Class representing a risk modal visible after creating a new
risk from LHN"""
class NewRequestModal(base.RequestModal, base.CreateNewObjectModal):
"""Class representing an request modal visible after creating a new
request from LHN"""
class NewIssueModal(base.IssueModal, base.CreateNewObjectModal):
"""Class representing an issue visible after creating a new
issue from LHN"""
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jernej@reciprocitylabs.com
# Maintained By: jernej@reciprocitylabs.com
"""Modals for creating new objects"""
from lib.page.modal import base
class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal):
"""Class representing a program modal visible after creating a new
program from LHN"""
class NewControlModal(base.ControlModal, base.CreateNewObjectModal):
"""Class representing a control modal visible after creating a new
control from LHN"""
class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal):
"""Class representing an org group modal visible after creating a new
org group from LHN"""
class NewRiskModal(base.RiskModal, base.CreateNewObjectModal):
"""Class representing a risk modal visible after creating a new
risk from LHN"""
|
Replace lodash each() with standard forEach() |
'use strict';
var through = require('through2');
var glob = require('glob');
module.exports = function() {
var transform = function(file, env, cb) {
// find all instances matching
var contents = file.contents.toString('utf-8');
var reg = /@import\s+\"([^\"]*\*[^\"]*)\";/;
var result;
while((result = reg.exec(contents)) !== null) {
var index = result.index;
var sub = result[0];
var globName = result[1];
var files = glob.sync(file.base + globName);
var replaceString = '';
files.forEach(function(filename){
replaceString += '@import "' + filename + '";\n';
});
contents = contents.replace(sub, replaceString);
}
file.contents = new Buffer(contents);
cb(null, file);
};
return through.obj(transform);
};
|
'use strict';
var through = require('through2');
var glob = require('glob');
var _ = require('lodash');
module.exports = function() {
var transform = function(file, env, cb) {
// find all instances matching
var contents = file.contents.toString('utf-8');
var reg = /@import\s+\"([^\"]*\*[^\"]*)\";/;
var result;
while((result = reg.exec(contents)) !== null) {
var index = result.index;
var sub = result[0];
var globName = result[1];
var files = glob.sync(file.base + globName);
var replaceString = '';
_.each(files, function(filename) {
replaceString += '@import "' + filename + '";\n';
});
contents = contents.replace(sub, replaceString);
}
file.contents = new Buffer(contents);
cb(null, file);
};
return through.obj(transform);
};
|
Update build version to 0.1.1 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='prettystring',
version='0.1.1',
description='Build ANSI color encoded strings with ease.',
long_description=readme(),
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals',
'Topic :: Text Processing :: General',
'Topic :: Utilities'
],
keywords='color colorful pretty string strings',
url='https://github.com/robolivable/prettystring',
author='Robert Oliveira',
author_email='oliveira.rlde@gmail.com',
license='MIT',
packages=['prettystring'],
install_requires=['enum34==1.1.6'])
| from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='prettystring',
version='0.1.0',
description='Build ANSI color encoded strings with ease.',
long_description=readme(),
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals',
'Topic :: Text Processing :: General',
'Topic :: Utilities'
],
keywords='color colorful pretty string strings',
url='https://github.com/robolivable/prettystring',
author='Robert Oliveira',
author_email='oliveira.rlde@gmail.com',
license='MIT',
packages=['prettystring'],
install_requires=['enum34==1.1.6'])
|
Add state to game page | import React from 'react';
import { graphql } from 'react-apollo';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import GameShow from '../components/GameShow/GameShow';
import Loader from '../components/Loader';
import fullGameQuery from '../graphql/fullGame.graphql';
const mapStateToProps = ({ game }) => (
{
...game
}
);
const withGame = graphql(fullGameQuery, {
props: ({ data }) => {
if (!data.game) return { loading: data.loading };
if (data.error) return { hasErrors: true };
return {
game: data.game,
};
},
options: (props) => ({ variables: { id: props.match.params.id } })
});
const GamePage = ({ game, loading, isDownloading, isInstalling }) => (
loading
? <Loader />
: <GameShow
game={game}
isDownloading={isDownloading}
isInstalling={isInstalling}
/>
);
GamePage.propTypes = {
loading: PropTypes.bool,
game: PropTypes.object,
isDownloading: PropTypes.bool,
isInstalling: PropTypes.bool
};
GamePage.defaultProps = {
loading: false,
game: {},
isDownloading: false,
isInstalling: false
};
const GamePageWithProps = connect(mapStateToProps, null)(GamePage);
const GamePageWithData = withGame(GamePageWithProps);
export default GamePageWithData;
| import React from 'react';
import { graphql } from 'react-apollo';
import PropTypes from 'prop-types';
import GameShow from '../components/GameShow/GameShow';
import Loader from '../components/Loader';
import fullGameQuery from '../graphql/fullGame.graphql';
const withGame = graphql(fullGameQuery, {
props: ({ data }) => {
if (!data.game) return { loading: data.loading };
if (data.error) return { hasErrors: true };
return {
game: data.game,
};
},
options: (props) => ({ variables: { id: props.match.params.id } })
});
const GamePage = ({ game, loading }) => (
loading
? <Loader />
: <GameShow game={game} />
);
GamePage.propTypes = {
loading: PropTypes.bool,
game: PropTypes.object,
};
GamePage.defaultProps = {
loading: false,
game: {}
};
const GamePageWithData = withGame(GamePage);
export default GamePageWithData;
|
Mark Page's parent field as 'blank' | from django.db import models
class Page(models.Model):
"""A Page in Dyanote."""
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='')
parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children')
body = models.TextField(blank=True, default='')
author = models.ForeignKey('auth.User', related_name='pages')
NORMAL = 0
ROOT = 1
TRASH = 2
FLAGS = (
(NORMAL, 'Normal page'),
(ROOT, 'Root page'),
(TRASH, 'Trash page'),
)
flags = models.IntegerField(choices=FLAGS, default=NORMAL)
class Meta:
ordering = ('created',)
| from django.db import models
class Page(models.Model):
"""A Page in Dyanote."""
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='')
parent = models.ForeignKey('api.Page', null=True, related_name='children')
body = models.TextField(blank=True, default='')
author = models.ForeignKey('auth.User', related_name='pages')
NORMAL = 0
ROOT = 1
TRASH = 2
FLAGS = (
(NORMAL, 'Normal page'),
(ROOT, 'Root page'),
(TRASH, 'Trash page'),
)
flags = models.IntegerField(choices=FLAGS, default=NORMAL)
class Meta:
ordering = ('created',)
|
Disable the APC cache for Ubuntu 14.04. APC is deprecated now so we need a better solution anyways. | <?php
class Cache
{
private function createCacheKey($key, $isUserValue, $userId = null) {
$CC_CONFIG = Config::getConfig();
$a = $CC_CONFIG["apiKey"][0];
if ($isUserValue) {
$cacheKey = "{$key}{$userId}{$a}";
}
else {
$cacheKey = "{$key}{$a}";
}
return $cacheKey;
}
public function store($key, $value, $isUserValue, $userId = null) {
//$cacheKey = self::createCacheKey($key, $userId);
return false; ///apc_store($cacheKey, $value);
}
public function fetch($key, $isUserValue, $userId = null) {
//$cacheKey = self::createCacheKey($key, $isUserValue, $userId);
return false; //apc_fetch($cacheKey);
}
}
| <?php
class Cache
{
private function createCacheKey($key, $isUserValue, $userId = null) {
$CC_CONFIG = Config::getConfig();
$a = $CC_CONFIG["apiKey"][0];
if ($isUserValue) {
$cacheKey = "{$key}{$userId}{$a}";
}
else {
$cacheKey = "{$key}{$a}";
}
return $cacheKey;
}
public function store($key, $value, $isUserValue, $userId = null) {
$cacheKey = self::createCacheKey($key, $userId);
return apc_store($cacheKey, $value);
}
public function fetch($key, $isUserValue, $userId = null) {
$cacheKey = self::createCacheKey($key, $isUserValue, $userId);
return apc_fetch($cacheKey);
}
} |
Support giving full dates in month-year inputs
From user testing | 'use strict';
angular.module('ddsApp').directive('ddsDateMonthYear', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.push(function(viewValue) {
var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY', 'L', 'DD/MM/YY']);
ctrl.$setValidity('ddsDateMonthYear', result.isValid());
return result;
});
ctrl.$formatters.push(function(momentInstance) {
if (! momentInstance) return;
return momentInstance.format('MMM YYYY');
});
}
};
});
| 'use strict';
angular.module('ddsApp').directive('ddsDateMonthYear', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.push(function(viewValue) {
var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY']);
ctrl.$setValidity('ddsDateMonthYear', result.isValid());
return result;
});
ctrl.$formatters.push(function(momentInstance) {
if (! momentInstance) return;
return momentInstance.format('MMM YYYY');
});
}
};
});
|
Add then callback to render search-results template | var Recipe = function(data){
this.title = data.Title;
this.stars = data.StarRating;
this.imageUrl = data.ImageURL
}
function BigOvenRecipeSearchJson(query) {
var allRecipes = [];
var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg"
var apiKey = "dvx7zJ0x53M8X5U4nOh6CMGpB3d0PEhH";
var titleKeyword = query;
var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="
+ titleKeyword
+ "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url
}).then(function(data){
for(i = 0; i < data.Results.length; i ++) {
allRecipes.push(new Recipe(data.Results[i]));
};
return allRecipes
}).then(function(recipes){
var template = $('#search-results').html();
var output = Mustache.render(template, {recipes: recipes});
$('#results').append(output);
})
};
$(document).ready(function(){
BigOvenRecipeSearchJson('cookies');
});
| var Recipe = function(data){
this.title = data.Title;
this.stars = data.StarRating;
this.imageUrl = data.ImageURL
}
function BigOvenRecipeSearchJson(query) {
var allRecipes = [];
var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg"
var apiKey = APIKEY;
var titleKeyword = query;
var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="
+ titleKeyword
+ "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url
}).then(function(data){
for(i = 0; i < data.Results.length; i ++) {
allRecipes.push(new Recipe(data.Results[i]));
};
return allRecipes
}).then(function(recipes){
// render allRecipes here
})
};
$(document).ready(function(){
var bigOvenSearch = BigOvenRecipeSearchJson('cookies');
});
|
Add missing test for `Surrogate-Control` header
Fixes #13. | var nocache = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('nocache', function () {
it('sets headers properly', function (done) {
var app = connect()
app.use(function (req, res, next) {
res.setHeader('ETag', 'abc123')
next()
})
app.use(nocache())
app.use(function (req, res) {
res.end('Hello world!')
})
request(app).get('/')
.expect('Surrogate-Control', 'no-store')
.expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
.expect('Pragma', 'no-cache')
.expect('Expires', '0')
.expect('ETag', 'abc123')
.end(done)
})
it('names its function and middleware', function () {
assert.equal(nocache.name, 'nocache')
assert.equal(nocache().name, 'nocache')
})
})
| var nocache = require('..')
var assert = require('assert')
var connect = require('connect')
var request = require('supertest')
describe('nocache', function () {
it('sets headers properly', function (done) {
var app = connect()
app.use(function (req, res, next) {
res.setHeader('ETag', 'abc123')
next()
})
app.use(nocache())
app.use(function (req, res) {
res.end('Hello world!')
})
request(app).get('/')
.expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
.expect('Pragma', 'no-cache')
.expect('Expires', '0')
.expect('ETag', 'abc123')
.end(done)
})
it('names its function and middleware', function () {
assert.equal(nocache.name, 'nocache')
assert.equal(nocache().name, 'nocache')
})
})
|
Add dependency link to daploader from pypi to overide Openshift's cache | #!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.5',
'PyYAML',
'python-social-auth',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework',
'django-gravatar2',
'markdown2',
'Markdown',
],
dependency_links = [
'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework',
'https://pypi.python.org/packages/source/d/daploader/daploader-0.0.5.tar.gz'
]
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.5',
'PyYAML',
'python-social-auth',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework',
'django-gravatar2',
'markdown2',
'Markdown',
],
dependency_links = [
'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework',
]
)
|
Replace lodash-es/wrap with arrow function | import { mapValues } from 'lodash-es';
import { isPlainObject } from 'lodash-es';
const FROM_HIGHCHARTS_PROVIDER = 'getHighcharts';
const FROM_CHART_PROVIDER = 'getChart';
const FROM_AXIS_PROVIDER = 'getAxis';
const FROM_SERIES_PROVIDER = 'getSeries';
export const PROVIDED_PROPS = [
FROM_HIGHCHARTS_PROVIDER,
FROM_CHART_PROVIDER,
FROM_AXIS_PROVIDER,
FROM_SERIES_PROVIDER
];
function cleanConfig(config) {
// omit provided props
return Object.keys(config)
.filter(key => PROVIDED_PROPS.indexOf(key) < 0)
.reduce((object, key) => {
object[key] = config[key];
return object;
}, {});
}
function deepCleanConfig (config) {
const cleanedRoot = cleanConfig(config);
return mapValues(cleanedRoot, prop => {
if (isPlainObject(prop) === false) return prop;
return deepCleanConfig(prop);
});
}
export default function removeProvidedProps (func) {
return (config, ...rest) => {
const cleanedConfig = deepCleanConfig(config);
return func(cleanedConfig, ...rest);
};
}
| import { mapValues } from 'lodash-es';
import { isPlainObject } from 'lodash-es';
import { wrap } from 'lodash-es';
const FROM_HIGHCHARTS_PROVIDER = 'getHighcharts';
const FROM_CHART_PROVIDER = 'getChart';
const FROM_AXIS_PROVIDER = 'getAxis';
const FROM_SERIES_PROVIDER = 'getSeries';
export const PROVIDED_PROPS = [
FROM_HIGHCHARTS_PROVIDER,
FROM_CHART_PROVIDER,
FROM_AXIS_PROVIDER,
FROM_SERIES_PROVIDER
];
function cleanConfig(config) {
// omit provided props
return Object.keys(config)
.filter(key => PROVIDED_PROPS.indexOf(key) < 0)
.reduce((object, key) => {
object[key] = config[key];
return object;
}, {});
}
function deepCleanConfig (config) {
const cleanedRoot = cleanConfig(config);
return mapValues(cleanedRoot, prop => {
if (isPlainObject(prop) === false) return prop;
return deepCleanConfig(prop);
});
}
export default function removeProvidedProps (func) {
return wrap(func, function (origFunc, config, ...rest) {
const cleanedConfig = deepCleanConfig(config);
return origFunc(cleanedConfig, ...rest);
});
}
|
Update release version to 0.0.5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='zorg',
version='0.0.5',
url='https://github.com/zorg/zorg',
description='Python framework for robotics and physical computing.',
long_description=read('README.rst'),
author='Zorg Group',
maintainer_email='gunthercx@gmail.com',
packages=find_packages(),
package_dir={'zorg': 'zorg'},
include_package_data=True,
license='MIT',
zip_safe=True,
platforms=['any'],
keywords=['zorg', 'robotics'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Environment :: Web Environment',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=[]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='zorg',
version='0.0.4',
url='https://github.com/zorg/zorg',
description='Python framework for robotics and physical computing.',
long_description=read('README.rst'),
author='Zorg Group',
maintainer_email='gunthercx@gmail.com',
packages=find_packages(),
package_dir={'zorg': 'zorg'},
include_package_data=True,
license='MIT',
zip_safe=True,
platforms=['any'],
keywords=['zorg', 'robotics'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Environment :: Console',
'Environment :: Web Environment',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=[]
)
|
Add updated and created to crud index | @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}</h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
<th>Created At</th>
<th>Updated At</th>
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
| @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}</h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
|
Add users route to the nav | <nav class="navigation -white -floating">
<a class="navigation__logo" href="/"><span>DoSomething.org</span></a>
<div class="navigation__menu">
@if (Auth::user())
<ul class="navigation__primary">
<li>
<a href="/campaigns">
<strong class="navigation__title">Campaign Overview</strong>
</a>
</li>
<li>
<a href="/users">
<strong class="navigation__title">User Search</strong>
</a>
</li>
</ul>
<ul class="navigation__secondary">
<li>
<a href="/logout">Log Out</a>
</li>
</ul>
@endif
</div>
</nav>
| <nav class="navigation -white -floating">
<a class="navigation__logo" href="/"><span>DoSomething.org</span></a>
<div class="navigation__menu">
@if (Auth::user())
<ul class="navigation__primary">
<li>
<a href="/campaigns">
<strong class="navigation__title">Campaign Overview</strong>
</a>
</li>
</ul>
<ul class="navigation__secondary">
<li>
<a href="/logout">Log Out</a>
</li>
</ul>
@endif
</div>
</nav>
|
Stop opening devtools on app launch | const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
const nativeImage = require('electron').nativeImage
require('./main-process/file-selection')
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
icon: nativeImage.createFromPath('assets/windows-app-icon/icon_768x768-windows.png'),
show: false,
frame: true
})
mainWindow.loadURL(`file://${__dirname}/index.html`)
// mainWindow.webContents.openDevTools() // Open the DevTools.
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', () => {
createWindow()
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
| const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
const nativeImage = require('electron').nativeImage
require('./main-process/file-selection')
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
icon: nativeImage.createFromPath('assets/windows-app-icon/icon_768x768-windows.png'),
show: false
})
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.webContents.openDevTools() // Open the DevTools.
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', () => {
createWindow()
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
|
JEK-8: Add separate eventCategory for broken links | /*
* Copyright 2014-2016 CyberVision, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.
*/
var PROCESSOR_404 = (function () {
var my = {};
my.process = function process() {
ga('send', 'event', 'User routing', 'Page not found', window.location.pathname);
var version = UTILS.replaceIfBlank( UTILS.getVersionFromURL(), UTILS.getLatestVersion());
if (UTILS.getVersionsArray().indexOf(version) === -1 ) {
version = UTILS.getLatestVersion();
}
DOM.getInstance().showMenuForVersion(version);
DOM.getInstance().showSelectedVersion(version);
};
return my;
}());
$(document).ready(function(){
PROCESSOR_404.process();
});
| /*
* Copyright 2014-2016 CyberVision, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.
*/
var PROCESSOR_404 = (function () {
var my = {};
my.process = function process() {
var version = UTILS.replaceIfBlank( UTILS.getVersionFromURL(), UTILS.getLatestVersion());
if (UTILS.getVersionsArray().indexOf(version) === -1 ) {
version = UTILS.getLatestVersion();
}
DOM.getInstance().showMenuForVersion(version);
DOM.getInstance().showSelectedVersion(version);
};
return my;
}());
$(document).ready(function(){
PROCESSOR_404.process();
});
|
Update development status to beta | #!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="rouver",
version="0.99.0",
description="A microframework",
long_description=read("README.rst"),
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/rouver",
packages=["rouver", "rouver_test"],
package_data={"rouver": ["py.typed"]},
install_requires=["dectest >= 1.0.0, < 2", "werkzeug >= 0.12.0"],
tests_require=["asserts >= 0.8.5, < 0.9"],
python_requires=">= 3.5",
license="MIT",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Internet :: WWW/HTTP :: WSGI",
],
)
| #!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="rouver",
version="0.99.0",
description="A microframework",
long_description=read("README.rst"),
author="Sebastian Rittau",
author_email="srittau@rittau.biz",
url="https://github.com/srittau/rouver",
packages=["rouver", "rouver_test"],
package_data={"rouver": ["py.typed"]},
install_requires=[
"dectest >= 1.0.0, < 2",
"werkzeug >= 0.12.0",
],
tests_require=["asserts >= 0.8.5, < 0.9"],
python_requires=">= 3.5",
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Topic :: Internet :: WWW/HTTP :: WSGI",
])
|
Add comment to new test | '''Test that models with no pretrained vectors can be deserialized correctly
after vectors are added.'''
from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.ones((3, 300), dtype='f')
keys = [u'I', u'am', u'Matt']
vectors = Vectors(data=data, keys=keys)
tagger = Tagger(Vocab())
tagger.add_label('PRP')
tagger.begin_training()
assert tagger.cfg.get('pretrained_dims', 0) == 0
tagger.vocab.vectors = vectors
with make_tempdir() as path:
tagger.to_disk(path)
tagger = Tagger(Vocab()).from_disk(path)
assert tagger.cfg.get('pretrained_dims', 0) == 0
| from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.ones((3, 300), dtype='f')
keys = [u'I', u'am', u'Matt']
vectors = Vectors(data=data, keys=keys)
tagger = Tagger(Vocab())
tagger.add_label('PRP')
tagger.begin_training()
assert tagger.cfg.get('pretrained_dims', 0) == 0
tagger.vocab.vectors = vectors
with make_tempdir() as path:
tagger.to_disk(path)
tagger = Tagger(Vocab()).from_disk(path)
assert tagger.cfg.get('pretrained_dims', 0) == 0
|
Comment out unused field "latLons". | package org.meteogroup.griblibrary.grib2.model;
import org.meteogroup.griblibrary.grib2.model.gdstemplates.GDSTemplate;
import org.meteogroup.griblibrary.util.LatLon;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
public class Grib2GDS {
private int length;
private int numberOfVerticalsCoordinateParams;
private int locationOfVerticalCoordinateParams;
private int locationListPer;
private int representationType;
private int numberOfPoints;
private double north;
private double south;
private double lat1;
private double lat2;
private double Dj;
// private LatLon[] latLons;
private int ni;
private int[] nis;
private int nj;
// GRIB2 variables
private int gridDefinitionTemplateNumber;
private GDSTemplate gdsTemplate;
}
| package org.meteogroup.griblibrary.grib2.model;
import org.meteogroup.griblibrary.grib2.model.gdstemplates.GDSTemplate;
import org.meteogroup.griblibrary.util.LatLon;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
public class Grib2GDS {
private int length;
private int numberOfVerticalsCoordinateParams;
private int locationOfVerticalCoordinateParams;
private int locationListPer;
private int representationType;
private int numberOfPoints;
private double north;
private double south;
private double lat1;
private double lat2;
private double Dj;
private LatLon[] latLons;
private int ni;
private int[] nis;
private int nj;
// GRIB2 variables
private int gridDefinitionTemplateNumber;
private GDSTemplate gdsTemplate;
}
|
[WebProfilerBundle] Fix tests about web profiler icons | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources;
use PHPUnit\Framework\TestCase;
class IconTest extends TestCase
{
/**
* @dataProvider provideIconFilePaths
*/
public function testIconFileContents($iconFilePath)
{
$this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+"[^>]*+>.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
}
public function provideIconFilePaths()
{
return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources;
use PHPUnit\Framework\TestCase;
class IconTest extends TestCase
{
/**
* @dataProvider provideIconFilePaths
*/
public function testIconFileContents($iconFilePath)
{
$this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+">.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
}
public function provideIconFilePaths()
{
return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
}
}
|
Set up tests to log in on first getting to the site | var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
disclaimer = element(by.css('div.disclaimer'));
this.Given(/^that I am at the HMDA homepage$/, function(next) {
passwordBox = element.all(by.id('txt-pwd'));
loginButton = element.all(by.css('.login-button'))
browser.get('http://dev.hmda-pilot.ec2.devis.com/#/');
//Prevents 'are you sure you want to leave?' window from popping up
browser.executeScript('window.onbeforeunload = function(){};').then(function(){
if(passwordBox.count() !== 0){
//Log in if we have not already done so
passwordBox.sendKeys('p1l0t');
loginButton.click();
}
});
next();
});
this.Then(/^I will see a disclaimer at the top$/, function (next) {
expect(disclaimer.isPresent()).to.eventually.be.true.notify(next);
});
};
| var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
disclaimer = element(by.css('div.disclaimer'));
this.Given(/^that I am at the HMDA homepage$/, function(next) {
browser.get('http://dev.hmda-pilot.ec2.devis.com/#/');
//Prevents 'are you sure you want to leave?' window from popping up
browser.executeScript('window.onbeforeunload = function(){};').then(function(){
next();
});
});
this.Then(/^I will see a disclaimer at the top$/, function (next) {
expect(disclaimer.isPresent()).to.eventually.be.true.notify(next);
});
};
|
Fix off by 1 error | <?php
include 'mysqlConfig.php';
header('Content-type: text/plain; charset=us-ascii');
header("Access-Control-Allow-Origin: *");
@mysql_select_db($dsn) or die( "Unable to select database");
$min_bw = intval($_GET["min_bw"]);
$min_bw > 0 or $_GET["min_bw"] === "0" or die("Bad minimum bandwidth");
$max_bw = intval($_GET["max_bw"]);
$max_bw !== 0 or die("Bad maximum bandwidth");
$min_bw <= $max_bw or die("min bw > max bw");
$min_ts = intval($_GET["min_ts"]);
$min_ts !== 0 or die("Bad minimum timestamp");
$max_ts = intval($_GET["max_ts"]);
$max_ts !== 0 or die("Bad maximum timestamp");
$min_ts <= $max_ts or die("min ts > max ts");
$query="select ip from bw_max where bps < " . $max_bw . " and bps > " . $min_bw . " and ts < " . $max_ts . " and ts > " . $min_ts;
$result = mysql_query($query);
$first_iter = true;
if(mysql_num_rows($result)) {
while($value = mysql_fetch_assoc($result)) {
if (! $first_iter){
echo "\n";
}
$first_iter = false;
echo $value["ip"];
}
}
mysql_close();
?>
| <?php
include 'mysqlConfig.php';
header('Content-type: text/plain; charset=us-ascii');
header("Access-Control-Allow-Origin: *");
@mysql_select_db($dsn) or die( "Unable to select database");
$min_bw = intval($_GET["min_bw"]);
$min_bw > 0 or $_GET["min_bw"] === "0" or die("Bad minimum bandwidth");
$max_bw = intval($_GET["max_bw"]);
$max_bw !== 0 or die("Bad maximum bandwidth");
$min_bw <= $max_bw or die("min bw > max bw");
$min_ts = intval($_GET["min_ts"]);
$min_ts !== 0 or die("Bad minimum timestamp");
$max_ts = intval($_GET["max_ts"]);
$max_ts !== 0 or die("Bad maximum timestamp");
$min_ts <= $max_ts or die("min ts > max ts");
$query="select ip from bw_max where bps < " . $max_bw . " and bps > " . $min_bw . " and ts < " . $max_ts . " and ts > " . $min_ts;
$result = mysql_query($query);
if(mysql_num_rows($result)) {
while($value = mysql_fetch_assoc($result)) {
echo $value["ip"] . "\n";
}
}
mysql_close();
?>
|
Add Unit tests for views | import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def test_setup(self, db_session):
patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
user = User()
consultant = User()
meeting = Meeting()
db_session.add(patient1)
db_session.commit()
def test_page_load(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
def test_kept_in_db(self):
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
assert req_pass.status_code == 200
| import pytest
from flask import url_for
from pytest_flask import fixtures
from mdt_app.models import *
@pytest.mark.usefixtures('client_class')
class TestIndex:
def test_page_load(self):
assert self.client.get(url_for('main.index')).status_code == 200
@pytest.mark.usefixtures('client_class')
class TestCaseCreate:
def setup(self):
self.patient1 = Patient(id=1, hospital_number=12345678,
first_name='test1', last_name='patient',
date_of_birth='1988-10-09', sex='F')
def test_page_load(self, db_session):
db_session.add(self.patient1)
db_session.commit()
req_pass = self.client.get(url_for('main.case_create', patient_id=1))
req_no_id = self.client.get(url_for('main.case_create', patient_id=''))
assert req_pass.status_code == 200
assert req_no_id.status_code == 404, 'no id, page not found'
|
Add croniter dependency. Sort deps. | #!/usr/bin/env python2.7
from __future__ import print_function
from distutils.core import setup
import os
version = '1.0.0b'
# Append TeamCity build number if it gives us one.
if 'TC_BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['TC_BUILD_NUMBER']
setup(name='fetch',
maintainer='Jeremy Hooke',
maintainer_email='jeremy.hooke@ga.gov.au',
version=version,
description='Automatic retrieval of ancillary and data',
packages=[
'fetch',
],
scripts=[
'bin/fetch-service'
],
requires=[
'arrow',
'croniter',
'feedparser',
'lxml',
'neocommon',
'pyyaml',
'requests',
'setproctitle',
]
)
| #!/usr/bin/env python2.7
from __future__ import print_function
from distutils.core import setup
import os
version = '1.0.0b'
# Append TeamCity build number if it gives us one.
if 'TC_BUILD_NUMBER' in os.environ and version.endswith('b'):
version += '' + os.environ['TC_BUILD_NUMBER']
setup(name='fetch',
maintainer='Jeremy Hooke',
maintainer_email='jeremy.hooke@ga.gov.au',
version=version,
description='Automatic retrieval of ancillary and data',
packages=[
'fetch',
],
scripts=[
'bin/fetch-service'
],
requires=[
'neocommon',
'requests',
'feedparser',
'lxml',
'setproctitle',
'pyyaml',
'arrow'
]
)
|
Clear the song index before re-indexing the entire database | <?php
use Elasticsearch\Client;
trait AdminSearch {
public function getSearch($index = null) {
if ($index) {
$document = $this->search($index, "track", "song-database");
View::share("index", $document["hits"]["hits"]);
}
$this->layout->content = View::make("admin.search");
}
// rebuild
public function putSearch() {
$load = DB::table("tracks")->get();
try {
$this->deleteSearch();
foreach ($load as $track) {
$this->index($track);
}
return;
} catch (Exception $e) {
return ["error" => $e->getTraceAsString(), "message" => $e->getMessage()];
}
}
// wipe
public function deleteSearch() {
$this->client->indices()->delete(["index" => "song-database"]);
}
// query
public function postSearch() {
}
}
| <?php
use Elasticsearch\Client;
trait AdminSearch {
public function getSearch($index = null) {
if ($index) {
$document = $this->search($index, "track", "song-database");
View::share("index", $document["hits"]["hits"]);
}
$this->layout->content = View::make("admin.search");
}
// rebuild
public function putSearch() {
$load = DB::table("tracks")->get();
try {
foreach ($load as $track) {
$this->index($track);
}
return;
} catch (Exception $e) {
return ["error" => $e->getTraceAsString(), "message" => $e->getMessage()];
}
}
// wipe
public function deleteSearch() {
$this->client->indices()->delete(["index" => "song-database"]);
}
// query
public function postSearch() {
}
}
|
Annotate MemberDAO DB access methods with @UnitOfWork | package me.chriskramp.library;
import com.yammer.dropwizard.hibernate.UnitOfWork;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/members")
@Produces(MediaType.APPLICATION_JSON)
public class MemberResource {
private MemberDAO memberDAO;
public MemberResource(MemberDAO memberDAO) {
this.memberDAO = memberDAO;
}
@GET
@UnitOfWork
public List<Member> getAllMembers() {
return memberDAO.getAllMembers();
}
@GET
@UnitOfWork
@Path("{id}")
public Member getMember(@PathParam("id") Long id) {
return memberDAO.findById(id);
}
@POST
@UnitOfWork
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
public Member createMember(Member member) {
return memberDAO.save(member);
}
}
| package me.chriskramp.library;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/members")
@Produces(MediaType.APPLICATION_JSON)
public class MemberResource {
private MemberDAO memberDAO;
public MemberResource(MemberDAO memberDAO) {
this.memberDAO = memberDAO;
}
@GET
public List<Member> getAllMembers() {
return memberDAO.getAllMembers();
}
@GET
@Path("{id}")
public Member getMember(@PathParam("id") Long id) {
return memberDAO.findById(id);
}
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
public Member createMember(Member member) {
return memberDAO.save(member);
}
}
|
ZON-3167: Fix test, needs to select proper header for header-module to be enabled (belongs to commit:eb1b6fa) | import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
# Select header that allows header module
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.select('id=options-template.template', 'Kolumne')
s.waitForVisible('css=.fieldname-header_layout')
s.select('id=options-template.header_layout', 'Standard')
s.type('id=options-template.header_layout', '\t')
s.pause(500)
block = 'quiz'
# copy&paste from self.create_block()
s.click('link=Struktur')
s.click('link=Header')
s.waitForElementPresent('css=#header-modules .module')
block_sel = '.block.type-{0}'.format(block)
count = s.getCssCount('css={0}'.format(block_sel))
s.dragAndDropToObject(
'css=#header-modules .module[cms\\:block_type={0}]'.format(block),
'css=#editable-header > .landing-zone', '10,10')
s.waitForCssCount('css={0}'.format(block_sel), count + 1)
| import zeit.content.article.edit.browser.testing
class HeaderModules(zeit.content.article.edit.browser.testing.EditorTestCase):
def test_can_create_module_by_drag_and_drop(self):
s = self.selenium
self.add_article()
block = 'quiz'
# copy&paste from self.create_block()
s.click('link=Struktur')
s.click('link=Header')
s.waitForElementPresent('css=#header-modules .module')
block_sel = '.block.type-{0}'.format(block)
count = s.getCssCount('css={0}'.format(block_sel))
s.dragAndDropToObject(
'css=#header-modules .module[cms\\:block_type={0}]'.format(block),
'css=#editable-header > .landing-zone', '10,10')
s.waitForCssCount('css={0}'.format(block_sel), count + 1)
|
Remove properties for HTML elements in the annotation overlay view | 'use babel';
export default class AnnotationOverlayView {
constructor({type, source, row, column, message}) {
this.element = document.createElement('div');
this.element.className = 'levels-view annotation-overlay';
this.element.style.display = 'none';
const headerDiv = document.createElement('div');
headerDiv.className = 'header';
this.element.appendChild(headerDiv);
const typeSpan = document.createElement('span');
typeSpan.className = `type badge badge-flexible badge-${type}`;
typeSpan.textContent = type;
headerDiv.appendChild(typeSpan);
const positionSpan = document.createElement('span');
positionSpan.className = 'position';
positionSpan.textContent = `at line ${row}${column ? `, column ${column}` : ''}`;
headerDiv.appendChild(positionSpan);
const sourceSpan = document.createElement('span');
sourceSpan.className = 'source';
sourceSpan.textContent = source;
headerDiv.appendChild(sourceSpan);
this.element.appendChild(document.createElement('hr'));
const messageDiv = document.createElement('div');
messageDiv.textContent = message;
this.element.appendChild(messageDiv);
}
show() {
this.element.style.display = '';
}
hide() {
this.element.style.display = 'none';
}
} | 'use babel';
export default class AnnotationOverlayView {
constructor({type, source, row, column, message}) {
this.element = document.createElement('div');
this.element.className = 'levels-view annotation-overlay';
this.element.style.display = 'none';
this.headerDiv = document.createElement('div');
this.headerDiv.className = 'header';
this.element.appendChild(this.headerDiv);
this.typeSpan = document.createElement('span');
this.typeSpan.className = `type badge badge-flexible badge-${type}`;
this.typeSpan.textContent = type;
this.headerDiv.appendChild(this.typeSpan);
this.positionSpan = document.createElement('span');
this.positionSpan.className = 'position';
this.positionSpan.textContent = `at line ${row}${column ? `, column ${column}` : ''}`;
this.headerDiv.appendChild(this.positionSpan);
this.sourceSpan = document.createElement('span');
this.sourceSpan.className = 'source';
this.sourceSpan.textContent = source;
this.headerDiv.appendChild(this.sourceSpan);
this.element.appendChild(document.createElement('hr'));
this.messageDiv = document.createElement('div');
this.messageDiv.textContent = message;
this.element.appendChild(this.messageDiv);
}
show() {
this.element.style.display = '';
}
hide() {
this.element.style.display = 'none';
}
} |
Use platform-specific path separator in log messages. | #!/usr/bin/env node
const path = require('path');
const shell = require('shelljs');
const argv = require('yargs').argv;
const clc = require('cli-color');
function packageJsonLocations(dirname) {
return shell.find(dirname)
.filter(fname => !(fname.indexOf('node_modules') > -1 || fname[0] === '.') && path.basename(fname) === 'package.json')
.map(fname => path.dirname(fname));
}
function yarn(directoryName) {
let command = 'yarn';
if (argv.cmd)
command += ' ' + argv.cmd;
if (argv.opt)
command += ' ' + argv.opt;
console.log(clc.blueBright('Current yarn path: ' + directoryName + path.sep + 'package.json...'));
shell.cd(directoryName);
let result = shell.exec(command);
return {
directoryName: directoryName,
exitCode: result.code
};
}
function filterRoot(directoryName) {
console.log('Root filtering');
return path.normalize(directoryName) === path.normalize(process.cwd());
}
if (require.main === module) {
let exitCode = packageJsonLocations(process.cwd())
.filter(argv.skipRoot ? filterRoot : filtered => filtered)
.map(yarn)
.reduce((code, result) =>result.exitCode > code ? result.exitCode : code, 0);
console.log(clc.green('End of yarns'));
process.exit(exitCode);
}
module.exports = {
yarn: yarn
};
| #!/usr/bin/env node
const path = require('path');
const shell = require('shelljs');
const argv = require('yargs').argv;
const clc = require('cli-color');
function packageJsonLocations(dirname) {
return shell.find(dirname)
.filter(fname => !(fname.indexOf('node_modules') > -1 || fname[0] === '.') && path.basename(fname) === 'package.json')
.map(fname => path.dirname(fname));
}
function yarn(directoryName) {
let command = 'yarn';
if (argv.cmd)
command += ' ' + argv.cmd;
if (argv.opt)
command += ' ' + argv.opt;
console.log(clc.blueBright('Current yarn path: ' + directoryName + '/package.json...'));
shell.cd(directoryName);
let result = shell.exec(command);
return {
directoryName: directoryName,
exitCode: result.code
};
}
function filterRoot(directoryName) {
console.log('Root filtering');
return path.normalize(directoryName) === path.normalize(process.cwd());
}
if (require.main === module) {
let exitCode = packageJsonLocations(process.cwd())
.filter(argv.skipRoot ? filterRoot : filtered => filtered)
.map(yarn)
.reduce((code, result) =>result.exitCode > code ? result.exitCode : code, 0);
console.log(clc.green('End of yarns'));
process.exit(exitCode);
}
module.exports = {
yarn: yarn
};
|
Save mul at the end to force execution. | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
data = into(da.Array, uri, blockshape=(100, 100))
omega = da.random.standard_normal(size=(100, 20), blockshape=(100, 20))
mat_h = data.dot(omega)
q, r = rcnmf. tsqr.tsqr(mat_h, blockshape=(100, 20))
print data.shape
print q.shape
mul = data.dot(q)
dot_graph(data.dask, filename='data')
dot_graph(omega.dask, filename='omega')
dot_graph(q.dask, filename='q')
dot_graph(mul.dask, filename='mul')
uri = temp_file.name + '::/mul'
into(uri, mul)
temp_file.close()
| import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
data = into(da.Array, uri, blockshape=(100, 100))
omega = da.random.standard_normal(size=(100, 20), blockshape=(100, 20))
mat_h = data.dot(omega)
q, r = rcnmf. tsqr.tsqr(mat_h, blockshape=(100, 20))
print data.shape
print q.shape
mul = data.dot(q)
dot_graph(data.dask, filename='data')
dot_graph(omega.dask, filename='omega')
dot_graph(q.dask, filename='q')
dot_graph(mul.dask, filename='mul')
temp_file.close()
|
Update Litho version for Docusaurus
Reviewed By: muraziz
Differential Revision: D27236872
fbshipit-source-id: ccab5ed8a444cbf1027070a0261c108c307642f7 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*
* @format
*/
// The versions here are used across the documentation
// To use it in normal mdx, you can import this file and use a variable e.g. {site.lithoVersion}
// To use it in codeblocks, use the component in /docs/component/versionedCodeBlock.js,
// and refer to the version as: e.g. {{site.lithoVersion}}
export const site = {
lithoVersion: '0.40.0',
lithoSnapshotVersion: '0.40.1-SNAPSHOT',
soloaderVersion: '0.9.0',
flipperVersion: '0.46.0',
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*
* @format
*/
// The versions here are used across the documentation
// To use it in normal mdx, you can import this file and use a variable e.g. {site.lithoVersion}
// To use it in codeblocks, use the component in /docs/component/versionedCodeBlock.js,
// and refer to the version as: e.g. {{site.lithoVersion}}
export const site = {
lithoVersion: '0.38.0',
lithoSnapshotVersion: '0.38.1-SNAPSHOT',
soloaderVersion: '0.9.0',
flipperVersion: '0.46.0',
};
|
Fix syntax error (return outside function).
Need to fix this for code to be parsable by prettier. | #!/usr/bin/env node
/*eslint no-console: 0*/
'use strict';
const cli = require('../lib/support/cli'),
sitespeed = require('../lib/sitespeed'),
Promise = require('bluebird');
if (process.env.NODE_ENV !== 'production') {
require('longjohn');
}
Promise.config({
warnings: true,
longStackTraces: true
});
process.exitCode = 1;
let parsed = cli.parseCommandLine();
let budgetFailing = false;
// hack for getting in the unchanged cli options
parsed.options.explicitOptions = parsed.explicitOptions;
parsed.options.urls = parsed.urls;
parsed.options.urlsMetaData = parsed.urlsMetaData;
sitespeed
.run(parsed.options)
.then(result => {
if (result.errors.length > 0) {
throw new Error('Errors while running:\n' + result.errors.join('\n'));
}
if (
parsed.options.budget &&
Object.keys(result.budgetResult.failing).length > 0
) {
process.exitCode = 1;
budgetFailing = true;
}
})
.then(() => {
if (!budgetFailing) {
process.exitCode = 0;
}
})
.catch(() => {
process.exitCode = 1;
})
.finally(() => process.exit());
| #!/usr/bin/env node
/*eslint no-console: 0*/
'use strict';
const cli = require('../lib/support/cli'),
sitespeed = require('../lib/sitespeed'),
Promise = require('bluebird');
if (process.env.NODE_ENV !== 'production') {
require('longjohn');
}
Promise.config({
warnings: true,
longStackTraces: true
});
process.exitCode = 1;
let parsed = cli.parseCommandLine();
let budgetFailing = false;
// hack for getting in the unchanged cli options
parsed.options.explicitOptions = parsed.explicitOptions;
parsed.options.urls = parsed.urls;
parsed.options.urlsMetaData = parsed.urlsMetaData;
return sitespeed.run(parsed.options)
.then((result) => {
if (result.errors.length > 0) {
throw new Error('Errors while running:\n' + result.errors.join('\n'));
}
if (parsed.options.budget && Object.keys(result.budgetResult.failing).length > 0) {
process.exitCode = 1;
budgetFailing = true;
}
})
.then(() => {
if (!budgetFailing) {
process.exitCode = 0;
}
})
.catch(() => {
process.exitCode = 1;
})
.finally(() => process.exit());
|
Add 2FA field, use localized labels in UserAdmin | from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from .forms import UserCreationForm, UserChangeForm
class UserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (
(None, {'fields': ('email', 'password', 'two_fa_enabled')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',)}),
(_('Groups'), {'fields': ('groups', 'user_permissions',)}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}),
)
list_display = ('email', )
list_filter = ('is_active', )
search_fields = ('email',)
ordering = ('email',)
| from django.contrib.auth.admin import UserAdmin
from .forms import UserCreationForm, UserChangeForm
class UserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (
(None, {'fields': ('email', 'password',)}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',)}),
('Groups', {'fields': ('groups', 'user_permissions',)}),
)
add_fieldsets = (
(None, {'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}),
)
list_display = ('email', )
list_filter = ('is_active', )
search_fields = ('email',)
ordering = ('email',)
|
Fix unicode strings in migration
Fixes #31 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ImpersonationLog',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('session_key', models.CharField(help_text='The Django session request key.', max_length=40)),
('session_started_at', models.DateTimeField(help_text='The time impersonation began.', null=True, blank=True)),
('session_ended_at', models.DateTimeField(help_text='The time impersonation ended.', null=True, blank=True)),
('impersonating', models.ForeignKey(related_name='impersonated_by', to=settings.AUTH_USER_MODEL, help_text='The user being impersonated.')),
('impersonator', models.ForeignKey(related_name='impersonations', to=settings.AUTH_USER_MODEL, help_text='The user doing the impersonating.')),
],
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ImpersonationLog',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('session_key', models.CharField(help_text=b'The Django session request key.', max_length=40)),
('session_started_at', models.DateTimeField(help_text=b'The time impersonation began.', null=True, blank=True)),
('session_ended_at', models.DateTimeField(help_text=b'The time impersonation ended.', null=True, blank=True)),
('impersonating', models.ForeignKey(related_name='impersonated_by', to=settings.AUTH_USER_MODEL, help_text=b'The user being impersonated.')),
('impersonator', models.ForeignKey(related_name='impersonations', to=settings.AUTH_USER_MODEL, help_text=b'The user doing the impersonating.')),
],
),
]
|
Use HTTPBasicAuth when connecting to the API | from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
Returns:
an authenticated slumber connection
"""
session = OAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=REQUEST_TOKEN_URL,
username=settings.API_USERNAME,
password=settings.API_PASSWORD,
auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET)
)
return slumber.API(
base_url=settings.API_URL, session=session
)
| from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
Returns:
an authenticated slumber connection
"""
session = OAuth2Session(
client=LegacyApplicationClient(
client_id=settings.API_CLIENT_ID
)
)
session.fetch_token(
token_url=REQUEST_TOKEN_URL,
username=settings.API_USERNAME,
password=settings.API_PASSWORD,
client_id=settings.API_CLIENT_ID,
client_secret=settings.API_CLIENT_SECRET
)
return slumber.API(
base_url=settings.API_URL, session=session
)
|
Put the gc_content bug back. | #!/usr/bin/env python2
def reverse(seq):
"""Return the reverse of the given sequence (i.e. 3' to
5')."""
return seq[::-1]
def complement(seq):
"""Return the complement of the given sequence (i.e. G=>C,
A=>T, etc.)"""
from string import maketrans
complements = maketrans('ACTGactg', 'TGACtgac')
return seq.translate(complements)
def reverse_complement(seq):
"""Return the reverse complement of the given sequence
(e.g. the opposite strand)."""
return reverse(complement(seq))
# This function contains a bug. Do you see it?
def gc_content(seq):
"""Return the GC content of the given sequence (e.g. the
fraction of nucleotides that are either G or C)."""
return sum(x in 'GC' for x in seq) / len(seq)
| #!/usr/bin/env python2
from __future__ import division
def reverse(seq):
"""Return the reverse of the given sequence (i.e. 3' to
5')."""
return seq[::-1]
def complement(seq):
"""Return the complement of the given sequence (i.e. G=>C,
A=>T, etc.)"""
from string import maketrans
complements = maketrans('ACTGactg', 'TGACtgac')
return seq.translate(complements)
def reverse_complement(seq):
"""Return the reverse complement of the given sequence
(e.g. the opposite strand)."""
return reverse(complement(seq))
# This function contains a bug. Do you see it?
def gc_content(seq):
"""Return the GC content of the given sequence (e.g. the
fraction of nucleotides that are either G or C)."""
return sum(x in 'GC' for x in seq) / len(seq)
|
Add test to verify that named_tempfile() overrides the `delete` parameter. | from __future__ import unicode_literals
from nose.tools import *
import os
import time
from dit.utils import cd, named_tempfile, tempdir
def test_cd():
with cd('/'):
assert_equal(os.getcwd(), '/')
def test_named_tempfile1():
name = None
with named_tempfile() as tempfile:
name = tempfile.name
assert_true(os.path.isfile(name))
tempfile.write('hello'.encode('ascii'))
tempfile.close()
assert_true(os.path.isfile(name))
assert_false(os.path.isfile(name))
def test_named_tempfile2():
name = None
# The specification of delete=True should be ignored.
with named_tempfile(delete=True) as tempfile:
name = tempfile.name
assert_true(os.path.isfile(name))
tempfile.write('hello'.encode('ascii'))
tempfile.close()
assert_true(os.path.isfile(name))
assert_false(os.path.isfile(name))
def test_tempdir():
name = None
with tempdir() as tmpdir:
assert_true(os.path.isdir(tmpdir))
assert_false(os.path.isdir(tmpdir))
| from __future__ import unicode_literals
from nose.tools import *
import os
import time
from dit.utils import cd, named_tempfile, tempdir
def test_cd():
with cd('/'):
assert_equal(os.getcwd(), '/')
def test_named_tempfile():
name = None
with named_tempfile() as tempfile:
name = tempfile.name
assert_true(os.path.isfile(name))
tempfile.write('hello'.encode('ascii'))
tempfile.close()
assert_true(os.path.isfile(name))
assert_false(os.path.isfile(name))
def test_tempdir():
name = None
with tempdir() as tmpdir:
assert_true(os.path.isdir(tmpdir))
assert_false(os.path.isdir(tmpdir))
|
TYP: Update type annotations to reference package names in full | # -*- coding: utf-8 -*-
"""
fsictools
=========
Supporting tools for FSIC-based economic models. See the individual docstrings
for dependencies additional to those of `fsic`.
"""
# Version number keeps track with the main `fsic` module
from fsic import __version__
import re
from typing import List
from fsic import BaseModel, Symbol
def symbols_to_dataframe(symbols: List[Symbol]) -> 'pandas.DataFrame':
"""Convert the list of symbols to a `pandas` DataFrame. **Requires `pandas`**."""
from pandas import DataFrame
return DataFrame([s._asdict() for s in symbols])
def model_to_dataframe(model: BaseModel) -> 'pandas.DataFrame':
"""Return the values and solution information from the model as a `pandas` DataFrame. **Requires `pandas`**."""
from pandas import DataFrame
df = DataFrame(model.values.T, index=model.span, columns=model.names)
df['status'] = model.status
df['iterations'] = model.iterations
return df
| # -*- coding: utf-8 -*-
"""
fsictools
=========
Supporting tools for FSIC-based economic models. See the individual docstrings
for dependencies additional to those of `fsic`.
"""
# Version number keeps track with the main `fsic` module
from fsic import __version__
import re
from typing import List
from fsic import BaseModel, Symbol
def symbols_to_dataframe(symbols: List[Symbol]) -> 'DataFrame':
"""Convert the list of symbols to a `pandas` DataFrame. **Requires `pandas`**."""
from pandas import DataFrame
return DataFrame([s._asdict() for s in symbols])
def model_to_dataframe(model: BaseModel) -> 'DataFrame':
"""Return the values and solution information from the model as a `pandas` DataFrame. **Requires `pandas`**."""
from pandas import DataFrame
df = DataFrame(model.values.T, index=model.span, columns=model.names)
df['status'] = model.status
df['iterations'] = model.iterations
return df
|
Add try statement to cleanup pins and invert pull/up down | import time
import urllib
import RPi.GPIO as GPIO
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
GPIO.setmode(GPIO.BCM)
# Disable "Ports already in use" warning
GPIO.setwarnings(False)
# Set the pin to be an input
GPIO.setup(LPR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Try statement to cleanup GPIO pins
try:
# Only save the image once per gate opening
captured = False
# Main loop
while True:
# Capture the image if not captured yet and switch is closed (open gate)
if not captured and GPIO.input(LPR_PIN) is True:
urllib.urlretrieve(SOURCE, FILE)
print "Gate has been opened!"
captured = True
# If there was a capture and the switch is now open (closed gate) then
# ready the loop to capture again.
if captured and GPIO.input(LPR_PIN) is False:
print "The gate has now closed!"
captured = False
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup() | import time
import urllib
import RPi.GPIO as GPIO
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
GPIO.setmode(GPIO.BCM)
# Disable "Ports already in use" warning
GPIO.setwarnings(False)
# Set the pin to be an input
GPIO.setup(LPR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# Only save the image once per gate opening
captured = False
# Main loop
while True:
# Capture the image if not captured yet and switch is closed (open gate)
if not captured and GPIO.input(LPR_PIN) is True:
urllib.urlretrieve(SOURCE, FILE)
print "Gate has been opened!"
captured = True
# If there was a capture and the switch is now open (closed gate) then
# ready the loop to capture again.
if captured and GPIO.input(LPR_PIN) is False:
print "The gate has now closed!"
captured = False
time.sleep(1)
|
Fix namespace in tick generator quick test. | function makeData() {
"use strict";
return makeRandomData(50);
}
function run(div, data, Plottable) {
"use strict";
var svg = div.append("svg").attr("height", 500);
var xScale = new Plottable.Scale.Linear().tickGenerator(Plottable.Scale.TickGenerators.intervalTickGenerator(0.2));
var yScale = new Plottable.Scale.Linear();
var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
var yAxis = new Plottable.Axis.Numeric(yScale, "left");
var titleLabel = new Plottable.Component.TitleLabel("Ticks in Increments of 0.2");
var plot = new Plottable.Plot.Line(xScale, yScale);
plot.addDataset(data);
var chart = new Plottable.Component.Table([
[null, titleLabel],
[yAxis, plot],
[null, xAxis]
]);
chart.renderTo(svg);
}
| function makeData() {
"use strict";
return makeRandomData(50);
}
function run(div, data, Plottable) {
"use strict";
var svg = div.append("svg").attr("height", 500);
var xScale = new Plottable.Scale.Linear().tickGenerator(Plottable.TickGenerators.intervalTickGenerator(0.2));
var yScale = new Plottable.Scale.Linear();
var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
var yAxis = new Plottable.Axis.Numeric(yScale, "left");
var titleLabel = new Plottable.Component.TitleLabel("Ticks in Increments of 0.2");
var plot = new Plottable.Plot.Line(xScale, yScale);
plot.addDataset(data);
var chart = new Plottable.Component.Table([
[null, titleLabel],
[yAxis, plot],
[null, xAxis]
]);
chart.renderTo(svg);
}
|
Set an id when an account registers |
var mongo = require('./mongo');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var uuid = require('uuid');
passport.use(new FacebookStrategy({
clientID: process.env.FB_APP_ID,
clientSecret: process.env.FB_APP_SECRET,
callbackURL: 'http://localhost:18000/auth/facebook/callback',
enableProof: false
}, function (accessToken, refreshToken, profile, done) {
mongo.Account.findOneAndUpdate({
facebookId: profile.id
}, {
id: uuid.v4(),
displayName: profile.displayName
}, {
upsert: true
}).exec().then(function (account) {
done(null, account);
}, function (err) {
done(err);
});
}));
module.exports = passport;
|
var mongo = require('./mongo');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
passport.use(new FacebookStrategy({
clientID: process.env.FB_APP_ID,
clientSecret: process.env.FB_APP_SECRET,
callbackURL: 'http://localhost:18000/auth/facebook/callback',
enableProof: false
}, function (accessToken, refreshToken, profile, done) {
mongo.Account.findOneAndUpdate({
facebookId: profile.id
}, {
displayName: profile.displayName
}, {
upsert: true
}).exec().then(function (account) {
done(null, account);
}, function (err) {
done(err);
});
}));
module.exports = passport;
|
Use null instead of false to remove JSX attribute | const React = require('react');
const {PropTypes} = React;
const uniqueId = require('lodash/uniqueId');
class Pagination extends React.Component {
static propTypes = {
info: PropTypes.string
};
render() {
const id = this.props.info ? uniqueId('cf-pagination-') : null;
return (
<div className="cf-pagination">
<ul className="cf-pagination__list" role="navigation" aria-describedby={id}>
{this.props.children}
</ul>
{this.props.info && (
<span id={id}>
{this.props.info}
</span>
)}
</div>
);
}
}
module.exports = Pagination;
| const React = require('react');
const {PropTypes} = React;
const uniqueId = require('lodash/uniqueId');
class Pagination extends React.Component {
static propTypes = {
info: PropTypes.string
};
render() {
const id = this.props.info ? uniqueId('cf-pagination-') : false;
return (
<div className="cf-pagination">
<ul className="cf-pagination__list" role="navigation" aria-describedby={id}>
{this.props.children}
</ul>
{this.props.info && (
<span id={id}>
{this.props.info}
</span>
)}
</div>
);
}
}
module.exports = Pagination;
|
Throw a new exception when an email was not send | <?php
use Illuminate\Support\Collection;
function collection($data)
{
$collection = new Collection($data);
return $collection;
}
function parseUrl($url)
{
return explode('/', filter_var(trim( $url , '/'), FILTER_SANITIZE_URL));
}
function sendEmail($to, $name, $subject, $template, $lead)
{
$path = __DIR__. "/../resources/templates-emails/";
ob_start();
require $path . $template . '.php' ;
$html = ob_get_clean();
//$transport = (new Swift_SendmailTransport('/usr/sbin/sendmail -bs'));
$transport = new Swift_SmtpTransport(getenv('MAIL_HOST'), getenv('MAIL_PORT'));
$transport->setUsername(getenv('MAIL_USERNAME'))
->setPassword(getenv('MAIL_PASSWORD'));
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom([getenv('MAIL_FROM') => getenv('NAME_COMPANY')])
->setTo([ $to => $name])
->setBody($html, 'text/html');
try{
$mailer->send($message);
}catch (Exception $e) {
throw new $e($e->getMessage());
}
} | <?php
use Illuminate\Support\Collection;
function collection($data)
{
$collection = new Collection($data);
return $collection;
}
function parseUrl($url)
{
return explode('/', filter_var(trim( $url , '/'), FILTER_SANITIZE_URL));
}
function sendEmail($to, $name, $subject, $template, $lead)
{
$path = __DIR__. "/../resources/templates-emails/";
ob_start();
require $path . $template . '.php' ;
$html = ob_get_clean();
//$transport = (new Swift_SendmailTransport('/usr/sbin/sendmail -bs'));
$transport = new Swift_SmtpTransport(getenv('MAIL_HOST'), getenv('MAIL_PORT'));
$transport->setUsername(getenv('MAIL_USERNAME'))
->setPassword(getenv('MAIL_PASSWORD'));
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom([getenv('MAIL_FROM') => getenv('NAME_COMPANY')])
->setTo([ $to => $name])
->setBody($html, 'text/html');
try{
$mailer->send($message);
}catch (Exception $e) {
dd($e->getMessage());
}
} |
Update webpack babel-loader to es2017 | var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
publicPath: '/dist/'
},
resolve: {
modules: ['./src', 'node_modules'],
extensions: ['.js']
},
module: {
loaders: [{
test: /\.js$/,
exclude: [/node_modules/, /assets/],
loader: 'babel-loader',
include: __dirname,
query: {
presets: [ 'es2017', 'react'],
plugins: ['transform-class-properties', 'transform-object-rest-spread']
}
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
loaders: [
'file-loader',
{
loader: 'image-webpack-loader',
query: {
progressive: true,
//optimizationLevel: 7,
//interlaced: false,
}
}
]
}]
}
}
| var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
publicPath: '/dist/'
},
resolve: {
modules: ['./src', 'node_modules'],
extensions: ['.js']
},
module: {
loaders: [{
test: /\.js$/,
exclude: [/node_modules/, /assets/],
loader: 'babel-loader',
include: __dirname,
query: {
presets: [ 'es2015', 'react'],
plugins: ['transform-class-properties', 'transform-object-rest-spread']
}
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
loaders: [
'file-loader',
{
loader: 'image-webpack-loader',
query: {
progressive: true,
//optimizationLevel: 7,
//interlaced: false,
}
}
]
}]
}
}
|
Handle empty responses from `getos`
Fixes #6, #7, #8. | 'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const stdout = res.stdout.split('\n');
return {
os: stdout[0],
name: stdout[1],
release: stdout[2],
code: stdout[3]
};
}).catch(() => {
return pify(getos).then(res => {
if (!res) {
throw new Error('Your distro couldn\'t be determined');
}
return {
os: res.dist || '',
name: res.dist && res.release ? `${res.dist} ${res.release}` : '',
release: res.release || '',
code: res.codename || ''
};
});
});
};
| 'use strict';
const execa = require('execa');
const getos = require('getos');
const pify = require('pify');
module.exports = () => {
if (process.platform !== 'linux') {
return Promise.reject(new Error('Only Linux systems are supported'));
}
return execa('lsb_release', ['-a', '--short']).then(res => {
const stdout = res.stdout.split('\n');
return {
os: stdout[0],
name: stdout[1],
release: stdout[2],
code: stdout[3]
};
}).catch(() => {
return pify(getos).then(res => {
return {
os: res.dist,
name: `${res.dist} ${res.release}`,
release: res.release,
code: res.codename
};
});
});
};
|
Handle timezones in datepicker binding by resolving the string yy-mm-dd date into the local offset date. This prevents 2013-12-31 resolving into 2013-12-30 19:00 EST (for example). | define(['knockout'], function (ko) {
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
//handle date data coming via json from Microsoft
if (typeof value === "string")
{
if (String(value).indexOf('/Date(') == 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
else
value = new Date(value);
// offset this timezone to UTC
var localOffset = value.getTimezoneOffset() * 60000;
value = new Date(value.getTime() + localOffset);
}
var current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
}); | define(['knockout'], function (ko) {
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') == 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
else
value = new Date(value);
var current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
}); |
Allow default options to be overridden | 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var lpad = require('lpad-align');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || {};
opts.stream = opts.stream || process.stderr;
opts.indent = opts.indent || 2;
if (res.headers['content-length']) {
var words = [
'fetch',
'progress'
];
var fetch = chalk.cyan(lpad('fetch', words, opts.indent));
var progress = chalk.cyan(lpad('progress', words, opts.indent));
var str = progress + ' : [:bar] :percent :etas';
var bar = new ProgressBar(str, assign({}, {
complete: '=',
incomplete: ' ',
width: 20,
total: parseInt(res.headers['content-length'], 10)
}, opts));
opts.stream.write(fetch + ' : ' + url + '\n');
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
opts.stream.write('\n');
cb();
});
}
};
};
| 'use strict';
var assign = require('object-assign');
var chalk = require('chalk');
var lpad = require('lpad-align');
var ProgressBar = require('progress');
/**
* Progress bar download plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
return function (res, url, cb) {
opts = opts || {};
opts.stream = opts.stream || process.stderr;
opts.indent = opts.indent || 2;
if (res.headers['content-length']) {
var words = [
'fetch',
'progress'
];
var fetch = chalk.cyan(lpad('fetch', words, opts.indent));
var progress = chalk.cyan(lpad('progress', words, opts.indent));
var str = progress + ' : [:bar] :percent :etas';
var bar = new ProgressBar(str, assign({
complete: '=',
incomplete: ' ',
width: 20,
total: parseInt(res.headers['content-length'], 10)
}, opts));
opts.stream.write(fetch + ' : ' + url + '\n');
res.on('data', function (data) {
bar.tick(data.length);
});
res.on('end', function () {
opts.stream.write('\n');
cb();
});
}
};
};
|
Add placeholder buttons for actions (edit, delete) | @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}</h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
<th>Created At</th>
<th>Updated At</th>
<th>Actions</th>
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
<td><button class="btn btn-info">Edit</button> <button class="btn btn-danger">Delete</button></td>
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
| @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}</h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
<th>Created At</th>
<th>Updated At</th>
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
|
Fix cache key eviction counter and log output | package com.fns.xlator.client.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class CacheService {
private final Logger log = LoggerFactory.getLogger(getClass());
private CounterService counterService;
@Autowired
public CacheService(CounterService counterService) {
this.counterService = counterService;
}
@CacheEvict("translations")
public void evictTranslation(String source, String target, String text) {
counterService.increment("services.cache.key.eviction");
log.info("Key w/ source [{}], target [{}], and text [{}] removed from cache!", source, target, text);
}
}
| package com.fns.xlator.client.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class CacheService {
private final Logger log = LoggerFactory.getLogger(getClass());
private CounterService counterService;
@Autowired
public CacheService(CounterService counterService) {
this.counterService = counterService;
}
@CacheEvict("translations")
public void evictTranslation(String source, String target, String text) {
counterService.increment("services.frengly.cacheKey.eviction");
log.info("Key w/ source [{}], target [{}], and text [{}] removed from cache!");
}
}
|
Package version bump to 0.6.0 | from setuptools import setup
setup(
name = 'flowz',
version = '0.6.0',
description = 'Async I/O - oriented dependency programming framework',
url = 'https://github.com/ethanrowe/flowz',
author = 'Ethan Rowe',
author_email = 'ethan@the-rowes.com',
license = 'MIT',
test_suite = 'nose.collector',
packages = [
'flowz',
'flowz.channels',
'flowz.examples',
'flowz.test',
'flowz.test.artifacts',
'flowz.test.channels',
'flowz.test.util',
],
tests_require = [
'mock',
'nose',
'six >= 1.9.0',
],
install_requires = [
'tornado >= 4.2',
'futures >= 3.0.5'
])
| from setuptools import setup
setup(
name = 'flowz',
version = '0.5.0',
description = 'Async I/O - oriented dependency programming framework',
url = 'https://github.com/ethanrowe/flowz',
author = 'Ethan Rowe',
author_email = 'ethan@the-rowes.com',
license = 'MIT',
test_suite = 'nose.collector',
packages = [
'flowz',
'flowz.channels',
'flowz.examples',
'flowz.test',
'flowz.test.artifacts',
'flowz.test.channels',
'flowz.test.util',
],
tests_require = [
'mock',
'nose',
'six >= 1.9.0',
],
install_requires = [
'tornado >= 4.2',
'futures >= 3.0.5'
])
|
Convert comment ID to int | <?php
class B3_Heartbeat_Comments {
public function get_last_updated() {
$comments = get_comments(
array(
'date_query' => $this->get_date_query()
)
);
return $this->filter_comments($comments);
}
private function get_date_query() {
return array(
array(
'after' => '15 minutes ago',
)
);
}
private function filter_comments( $comments ) {
$result = array();
foreach ($comments as $comment) {
array_push($result, (int)$comment->comment_ID);
}
return $result;
}
} | <?php
class B3_Heartbeat_Comments {
public function get_last_updated() {
$comments = get_comments(
array(
'date_query' => $this->get_date_query()
)
);
return $this->filter_comments($comments);
}
private function get_date_query() {
return array(
array(
'after' => '15 minutes ago',
)
);
}
private function filter_comments( $comments ) {
$result = array();
foreach ($comments as $comment) {
array_push($result, $comment->comment_ID);
}
return $result;
}
} |
Index page: title tag must contain "Identicons". | <?php
namespace Identicon\Tests;
use Silex\WebTestCase;
class IndexTest extends WebTestCase
{
public function createApplication()
{
return require __DIR__ . "/../../../src/production.php";
}
public function testLoadingIndexPage()
{
$client = $this->createClient();
$crawler = $client->request("GET", "/");
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThanOrEqual(1, $crawler->filter('html:contains("Identicon")')->count());
}
public function testHtmlTitleContainsTheName()
{
$client = $this->createClient();
$crawler = $client->request("GET", "/");
$this->assertEquals("Identicons", $crawler->filter("html > head > title")->text());
}
public function testHeaderLink()
{
$client = $this->createClient();
$crawler = $client->request("GET", "/");
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThanOrEqual(1, $crawler->filter('a.navbar-brand')->count());
$host = $client->getServerParameter("HTTP_HOST");
$this->assertEquals("http://{$host}/", $crawler->filter('a.navbar-brand ')->attr("href"));
}
} | <?php
namespace Identicon\Tests;
use Silex\WebTestCase;
class IndexTest extends WebTestCase
{
public function createApplication()
{
return require __DIR__ . "/../../../src/production.php";
}
public function testLoadingIndexPage()
{
$client = $this->createClient();
$crawler = $client->request("GET", "/");
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThanOrEqual(1, $crawler->filter('html:contains("Identicon")')->count());
}
public function testHeaderLink()
{
$client = $this->createClient();
$crawler = $client->request("GET", "/");
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertGreaterThanOrEqual(1, $crawler->filter('a.navbar-brand')->count());
$host = $client->getServerParameter("HTTP_HOST");
$this->assertEquals("http://{$host}/", $crawler->filter('a.navbar-brand ')->attr("href"));
}
} |
Modify a description of the parameters to function.
Change-Id: Ic6d9354df8ec180da91fcf88df15f2e054a9be11 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.swift.auth;
/**
* This class is used for correct hierarchy mapping of
* Keystone authentication model and java code
* THIS FILE IS MAPPED BY JACKSON TO AND FROM JSON.
* DO NOT RENAME OR MODIFY FIELDS AND THEIR ACCESSORS.
*/
public class AuthenticationWrapperV3 {
/**
* authentication response field
*/
private AuthenticationResponseV3 token;
/**
* @return authentication response
*/
public AuthenticationResponseV3 getToken() {
return token;
}
/**
* @param token sets authentication response
*/
public void setToken(AuthenticationResponseV3 token) {
this.token = token;
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.swift.auth;
/**
* This class is used for correct hierarchy mapping of
* Keystone authentication model and java code
* THIS FILE IS MAPPED BY JACKSON TO AND FROM JSON.
* DO NOT RENAME OR MODIFY FIELDS AND THEIR ACCESSORS.
*/
public class AuthenticationWrapperV3 {
/**
* authentication response field
*/
private AuthenticationResponseV3 token;
/**
* @return authentication response
*/
public AuthenticationResponseV3 getToken() {
return token;
}
/**
* @param access sets authentication response
*/
public void setToken(AuthenticationResponseV3 token) {
this.token = token;
}
}
|
Set project when doing neutron DB migrations
That way, the default configuration files/dirs from the neutron
projects are read when doing the DB migrations.
This is useful if eg. some configuration files are in
/etc/neutron/neutron.conf.d/ . Theses files will then be automatically
evaluated.
Change-Id: I4997a86c4df5fa45f7682d653a5e66b1ae184a62 | # 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 neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF(project='neutron')
CONF.command.func(config, CONF.command.name)
| # 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 neutron.db.migration.cli import * # noqa
def main():
config = alembic_config.Config(
os.path.join(os.path.dirname(__file__), 'alembic.ini'))
config.set_main_option(
'script_location',
'gbpservice.neutron.db.migration:alembic_migrations')
config.neutron_config = CONF
CONF()
CONF.command.func(config, CONF.command.name)
|
Change default to 0 instead of -1 for error checking | //The amount of pennies to be donated
var paymentAmount = 1;
var incrementDonation = function(amount){
if(paymentAmount !== 0){
paymentAmount += amount;
}
};
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var getAccessToken = function(){
$.ajax({
type: "GET",
url: "/access",
data: "",
success: function(data){
accessToken = data + "";
makePayment(paymentAmount);
}
});
};
var makePayment = function(payment){
$.ajax({
type: "POST",
url: "/pay",
data: {
amount: payment/100,
access_token: accessToken,
phone: "9084202938",
note: "Donation ID: " + makeid()
},
success: function(response){
console.log(response);
},
});
paymentAmount = 0;
};
| //The amount of pennies to be donated
var paymentAmount = 0;
var incrementDonation = function(amount){
if(paymentAmount !== -1){
paymentAmount += amount;
}
};
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var getAccessToken = function(){
$.ajax({
type: "GET",
url: "/access",
data: "",
success: function(data){
accessToken = data + "";
makePayment(paymentAmount);
}
});
};
var makePayment = function(payment){
$.ajax({
type: "POST",
url: "/pay",
data: {
amount: payment/100,
access_token: accessToken,
phone: "9084202938",
note: "Donation ID: " + makeid()
},
success: function(response){
console.log(response);
},
});
paymentAmount = -1;
};
|
Use phpcs as a library. | #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
| #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
Remove the EqualPath matcher because its unused
Co-authored-by: Eli Wrenn <0a41924cabfa000cd7baec4cd10fadeb2f8e7ed3@pivotal.io>
Co-authored-by: Reid Mitchell <15b84f3bcf1e0a1a99817cc9360cedc980d7c5b6@pivotal.io> | package helpers
import (
"fmt"
"path/filepath"
"regexp"
"runtime"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/types"
)
// SayPath is used to assert that a path is printed within streaming output.
// On Windows, it uses a case-insensitive match and escapes the path.
// On non-Windows, it evaluates the base directory of the path for symlinks.
func SayPath(format string, path string) types.GomegaMatcher {
theRealDir, err := filepath.EvalSymlinks(filepath.Dir(path))
Expect(err).ToNot(HaveOccurred())
theRealPath := filepath.Join(theRealDir, filepath.Base(path))
if runtime.GOOS == "windows" {
expected := "(?i)" + format
expected = fmt.Sprintf(expected, regexp.QuoteMeta(path))
return gbytes.Say(expected)
}
return gbytes.Say(format, theRealPath)
}
| package helpers
import (
"fmt"
"path/filepath"
"regexp"
"runtime"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/types"
)
// SayPath is used to assert that a path is printed within streaming output.
// On Windows, it uses a case-insensitive match and escapes the path.
// On non-Windows, it evaluates the base directory of the path for symlinks.
func SayPath(format string, path string) types.GomegaMatcher {
theRealDir, err := filepath.EvalSymlinks(filepath.Dir(path))
Expect(err).ToNot(HaveOccurred())
theRealPath := filepath.Join(theRealDir, filepath.Base(path))
if runtime.GOOS == "windows" {
expected := "(?i)" + format
expected = fmt.Sprintf(expected, regexp.QuoteMeta(path))
return gbytes.Say(expected)
}
return gbytes.Say(format, theRealPath)
}
func EqualPath(format string, path string) types.GomegaMatcher {
theRealDir, err := filepath.EvalSymlinks(filepath.Dir(path))
Expect(err).ToNot(HaveOccurred())
theRealPath := filepath.Join(theRealDir, filepath.Base(path))
if runtime.GOOS == "windows" {
expected := "(?i)" + format
expected = fmt.Sprintf(expected, regexp.QuoteMeta(path))
return &matchers.MatchRegexpMatcher{
Regexp: expected,
}
}
return &matchers.MatchRegexpMatcher{
Regexp: theRealPath,
}
}
|
Update with last version of pymfony | # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
| # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
Add better support for hijack | package ehttp
import (
"bufio"
"fmt"
"net"
"net/http"
"sync/atomic"
)
// ResponseWriter wraps http.ResponseWriter and holds
// a flag to know if the headers have been sent as well has
// the http code sent.
type ResponseWriter struct {
http.ResponseWriter
code *int32
}
// NewResponseWriter instantiates a new ehttp ResponseWriter.
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
code: new(int32),
}
}
// Code return the http code stored in the response writer.
func (w ResponseWriter) Code() int {
return int(atomic.LoadInt32(w.code))
}
// WriteHeader wraps underlying WriteHeader
// - flag that the headers have been sent
// - store the sent code
func (w *ResponseWriter) WriteHeader(code int) {
atomic.CompareAndSwapInt32(w.code, 0, int32(code))
w.ResponseWriter.WriteHeader(code)
}
// Write wraps the underlying Write and flag that the headers have been sent.
func (w *ResponseWriter) Write(buf []byte) (int, error) {
atomic.CompareAndSwapInt32(w.code, 0, int32(http.StatusOK))
return w.ResponseWriter.Write(buf)
}
// Hijack wraps the underlying Hijack if available.
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("not a hijacker")
}
return hijacker.Hijack()
}
| package ehttp
import (
"net/http"
"sync/atomic"
)
// ResponseWriter wraps http.ResponseWriter and holds
// a flag to know if the headers have been sent as well has
// the http code sent.
type ResponseWriter struct {
http.ResponseWriter
code *int32
}
// NewResponseWriter instantiates a new ehttp ResponseWriter.
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
code: new(int32),
}
}
// Code return the http code stored in the response writer.
func (w ResponseWriter) Code() int {
return int(atomic.LoadInt32(w.code))
}
// WriteHeader wraps underlying WriteHeader
// - flag that the headers have been sent
// - store the sent code
func (w *ResponseWriter) WriteHeader(code int) {
atomic.CompareAndSwapInt32(w.code, 0, int32(code))
w.ResponseWriter.WriteHeader(code)
}
// Write wraps the underlying Write and flag that the headers have been sent.
func (w *ResponseWriter) Write(buf []byte) (int, error) {
atomic.CompareAndSwapInt32(w.code, 0, int32(http.StatusOK))
return w.ResponseWriter.Write(buf)
}
|
Change text in flash massages | <?php
namespace hipanel\actions;
use Yii;
use yii\base\Action;
class AddToCartAction extends Action
{
public $productClass;
public function run()
{
$product = new $this->productClass;
$cart = Yii::$app->cart;
$request = Yii::$app->request;
if ($product->load($request->get())) {
if (!$cart->hasPosition($product->getId())) {
$cart->put($product);
Yii::$app->session->addFlash('success', Yii::t('app', 'Item is added to cart'));
} else {
Yii::$app->session->addFlash('warning', Yii::t('app', 'Item already exists in the cart'));
}
if ($request->isAjax) {
Yii::$app->end();
} else
return $this->controller->redirect(Yii::$app->request->referrer);
}
}
} | <?php
namespace hipanel\actions;
use Yii;
use yii\base\Action;
class AddToCartAction extends Action
{
public $productClass;
public function run()
{
$product = new $this->productClass;
$cart = Yii::$app->cart;
$request = Yii::$app->request;
if ($product->load($request->get())) {
if (!$cart->hasPosition($product->getId())) {
$cart->put($product);
Yii::$app->session->addFlash('success', Yii::t('app', 'Domain is added to cart'));
} else {
Yii::$app->session->addFlash('warning', Yii::t('app', 'Domain already exists in the cart'));
}
if ($request->isAjax) {
Yii::$app->end();
} else
return $this->controller->redirect(Yii::$app->request->referrer);
}
}
} |
Make the stream format a Line Delimited JSON | /* Demonstrate a streaming REST API, where the data is "flushed" to the client ASAP.
The stream format is a Line Delimited JSON.
The Curl Demo:
curl -i http://127.0.0.1:8080/stream
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 16 Feb 2014 00:39:19 GMT
Transfer-Encoding: chunked
{"Name":"thing #1"}
{"Name":"thing #2"}
{"Name":"thing #3"}
*/
package main
import (
"fmt"
"github.com/ant0ine/go-json-rest"
"net/http"
"time"
)
func main() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
DisableJsonIndent: true,
}
handler.SetRoutes(
rest.Route{"GET", "/stream", StreamThings},
)
http.ListenAndServe(":8080", &handler)
}
type Thing struct {
Name string
}
func StreamThings(w *rest.ResponseWriter, r *rest.Request) {
cpt := 0
for {
cpt++
w.WriteJson(
&Thing{
Name: fmt.Sprintf("thing #%d", cpt),
},
)
w.Write([]byte("\n"))
// Flush the buffer to client
w.Flush()
// wait 3 seconds
time.Sleep(time.Duration(3) * time.Second)
}
}
| /* Demonstrate a streaming REST API, where the data is "flushed" to the client ASAP.
The Curl Demo:
curl -i http://127.0.0.1:8080/stream
*/
package main
import (
"fmt"
"github.com/ant0ine/go-json-rest"
"net/http"
"time"
)
func main() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
handler.SetRoutes(
rest.Route{"GET", "/stream", StreamThings},
)
http.ListenAndServe(":8080", &handler)
}
type Thing struct {
Name string
}
func StreamThings(w *rest.ResponseWriter, r *rest.Request) {
cpt := 0
for {
cpt++
w.WriteJson(
&Thing{
Name: fmt.Sprintf("thing #%d", cpt),
},
)
// Flush the buffer to client
w.Flush()
// wait 3 seconds
time.Sleep(time.Duration(3) * time.Second)
}
}
|
Read frames from EPOC and publish them over zmq | package main
import (
"flag"
"fmt"
"github.com/anchor/picolog"
"github.com/fractalcat/emogo"
zmq "github.com/pebbe/zmq4"
"os"
)
var Logger *picolog.Logger
func readFrames(e *emogo.EmokitContext, out chan *emogo.EmokitFrame) {
for {
f, err := e.WaitGetFrame()
if err != nil {
fmt.Printf("error reading frame: %v", err)
return
}
out <- f
}
}
func main() {
listen := flag.String("listen", "tcp://*:9424", "ZMQ URI to listen on.")
flag.Parse()
Logger = picolog.NewLogger(picolog.LogDebug, "insenced", os.Stdout)
eeg, err := emogo.NewEmokitContext()
if err != nil {
Logger.Errorf("Could not initialize emokit context: %v", err)
}
sock, err := zmq.NewSocket(zmq.PUB)
if err != nil {
Logger.Fatalf("Could not create ZMQ socket: %v", err)
}
err = sock.Bind(*listen)
if err != nil {
Logger.Fatalf("Could not bind to %s: %v", listen, err)
}
frameChan := make(chan *emogo.EmokitFrame, 0)
readFrames(eeg, frameChan)
for {
f := <-frameChan
_, err := sock.SendBytes(f.Raw(), 0)
if err != nil {
fmt.Printf("Error sending raw frame: %v", err)
}
}
}
| package main
import (
"flag"
"github.com/anchor/picolog"
"github.com/fractalcat/emogo"
zmq "github.com/pebbe/zmq4"
"os"
)
var Logger *picolog.Logger
func main() {
listen := flag.String("listen", "tcp://*:9424", "ZMQ URI to listen on.")
flag.Parse()
Logger = picolog.NewLogger(picolog.LogDebug, "insenced", os.Stdout)
eeg, err := emogo.NewEmokitContext()
if err != nil {
Logger.Errorf("Could not initialize emokit context: %v", err)
}
sock, err := zmq.NewSocket(zmq.PUB)
if err != nil {
Logger.Fatalf("Could not create ZMQ socket: %v", err)
}
err = sock.Bind(*listen)
if err != nil {
Logger.Fatalf("Could not bind to %s: %v", listen, err)
}
_ = eeg
}
|
Set spectrum color pickers to rgb values instead of hex | var preset1 = function(){
infinite = false;
clearInterval(infiniteLoop)
showGravs = false;
noGravity = true;
gravity = 0;
$(".disable-gravity").prop("checked", false)
$("#background-color-picker").spectrum("set", "rgb(0,0,0)");
$("ball-max-color").spectrum("set", "rgb(255,255,255)");
$("ball-min-color").spectrum("set", "rgb(255,255,255)");
maxColor = "#ffffff"
minColor = "#ffffff"
backgroundColor = parseBackgroundColor($("#background-color-picker").spectrum("get"));
cv.ctx.fillStyle = '#000000';
cv.ctx.fillRect(0,0,cv.width,cv.height)
var x1 = (cv.width/2) - (525/2)
var y1 = (cv.height/2)
var x2 = (cv.width/2) + (525/2)
var y2 = (cv.height/2)
centersOfGravity.push(new gravityCenter(x1,y1,10));
centersOfGravity.push(new gravityCenter(x2,y2,10));
var unplaced = new UnplacedCluster(cv.width/2 + 50, cv.height/2 - 10, 5)
unplaced.execute(5, 20, 15);
var unplaced = new UnplacedCluster(cv.width/2 - 50, cv.height/2 + 10, 5)
unplaced.execute(5, 20, 15);
}
| var preset1 = function(){
infinite = false;
clearInterval(infiniteLoop)
noGravity = true;
gravity = 0;
$(".disable-gravity").prop("checked", false)
$("#background-color-picker").spectrum("set", "#000000");
$("ball-max-color").spectrum("set", "#ffffff");
$("ball-min-color").spectrum("set", "#ffffff");
maxColor = "#ffffff"
minColor = "#ffffff"
backgroundColor = parseBackgroundColor($("#background-color-picker").spectrum("get"));
cv.ctx.fillStyle = '#000000';
cv.ctx.fillRect(0,0,cv.width,cv.height)
var x1 = (cv.width/2) - (525/2)
var y1 = (cv.height/2)
var x2 = (cv.width/2) + (525/2)
var y2 = (cv.height/2)
centersOfGravity.push(new gravityCenter(x1,y1,10));
centersOfGravity.push(new gravityCenter(x2,y2,10));
var unplaced = new UnplacedCluster(cv.width/2 + 50, cv.height/2 - 10, 5)
unplaced.execute(5, 20, 15);
var unplaced = new UnplacedCluster(cv.width/2 - 50, cv.height/2 + 10, 5)
unplaced.execute(5, 20, 15);
}
|
Initialize application before error handler registration | <?php
/**
* Initialize application
*/
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
include_once $file;
}
/**
* Error handler
*/
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
);
set_exception_handler(
function ($e) {
echo '<pre>' . (string) $e . '</pre>';
}
);
register_shutdown_function(
function () {
$error = error_get_last();
$errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];
if ($error && in_array($error['type'], $errors)) {
echo '<pre>' . print_r($error, 1) . '</pre>';
}
}
);
/**
* Run application
*/
app\run();
| <?php
/**
* Error handler
*/
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
);
set_exception_handler(
function ($e) {
echo '<pre>' . (string) $e . '</pre>';
}
);
register_shutdown_function(
function () {
$error = error_get_last();
$errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];
if ($error && in_array($error['type'], $errors)) {
echo '<pre>' . print_r($error, 1) . '</pre>';
}
}
);
/**
* Init and run application
*/
foreach (glob(__DIR__ . '/../src/*.php') as $file) {
include_once $file;
}
app\run();
|
Make Station.lines into a property | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.lines = []
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
class Map(object):
pass
|
refactor: Use the BufferGeometry class instead of the Geometry. | import { BufferGeometry } from './three.js';
import { validatePropString } from './utils.js';
import { geometries } from './object-stores.js';
export default {
inject: ['vglGeometries'],
props: {
name: validatePropString,
},
computed: {
inst: () => new BufferGeometry(),
},
watch: {
inst: {
handler(inst, oldInst) {
if (oldInst) delete geometries[oldInst.uuid];
geometries[inst.uuid] = inst;
this.$set(this.vglGeometries.forSet, this.name, inst.uuid);
},
immediate: true,
},
name(name, oldName) {
if (this.vglGeometries.forGet[oldName] === this.inst.uuid) {
this.$delete(this.vglGeometries.forSet, oldName);
}
this.$set(this.vglGeometries.forSet, name, this.inst.uuid);
},
},
beforeDestroy() {
delete geometries[this.inst.uuid];
if (this.vglGeometries.forGet[this.name] === this.inst.uuid) {
this.$delete(this.vglGeometries.forSet, this.name);
}
},
render(h) {
return this.$slots.default ? h('div', this.$slots.default) : undefined;
},
};
| import { Geometry } from './three.js';
import { validatePropString } from './utils.js';
import { geometries } from './object-stores.js';
export default {
inject: ['vglGeometries'],
props: {
name: validatePropString,
},
computed: {
inst: () => new Geometry(),
},
watch: {
inst: {
handler(inst, oldInst) {
if (oldInst) delete geometries[oldInst.uuid];
geometries[inst.uuid] = inst;
this.$set(this.vglGeometries.forSet, this.name, inst.uuid);
},
immediate: true,
},
name(name, oldName) {
if (this.vglGeometries.forGet[oldName] === this.inst.uuid) this.$delete(this.vglGeometries.forSet, oldName);
this.$set(this.vglGeometries.forSet, name, this.inst.uuid);
},
},
beforeDestroy() {
delete geometries[this.inst.uuid];
if (this.vglGeometries.forGet[this.name] === this.inst.uuid) this.$delete(this.vglGeometries.forSet, this.name);
},
render(h) {
return this.$slots.default ? h('div', this.$slots.default) : undefined;
}
};
|
Add media to url, for development only | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name="listings"
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^accounts/register/$', views.register, name='register'),
url(r'^accounts/register/complete/$', views.RegistrationCompleteView.as_view(), name='registration_complete'),
url(r'^accounts/profile/$', login_required(views.ProfileView.as_view()), name='profile'),
url(r'^accounts/profile/preference$', login_required(views.PreferenceView.as_view()), name='preference'),
url(r'^listing/new/$', login_required(views.ListingCreate.as_view()), name='new'),
url(r'^listing/(?P<listing_id>\d+)/$', views.ListingDetail.as_view(), name='detail'),
url(r'^listing/(?P<listing_id>\d+)/edit/$', login_required(views.ListingEdit.as_view()), name='edit'),
url(r'^listing/(?P<listing_id>\d+)/toggle/$', login_required(views.listing_status_toggle), name='toggle'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
admin.site.site_header = 'Housing Admin'
| from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views
from . import views
app_name="listings"
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^accounts/register/$', views.register, name='register'),
url(r'^accounts/register/complete/$', views.RegistrationCompleteView.as_view(), name='registration_complete'),
url(r'^accounts/profile/$', login_required(views.ProfileView.as_view()), name='profile'),
url(r'^listing/new/$', login_required(views.ListingCreate.as_view()), name='new'),
url(r'^listing/(?P<listing_id>\d+)/$', views.ListingDetail.as_view(), name='detail'),
url(r'^listing/(?P<listing_id>\d+)/edit/$', login_required(views.ListingEdit.as_view()), name='edit'),
url(r'^listing/(?P<listing_id>\d+)/toggle/$', login_required(views.listing_status_toggle), name='toggle'),
]
|
Remove policy caveat from Differential
Summary: Policies are now fully supported in Differential.
Test Plan: Grepped for other caveats, looks like I've already removed htem all.
Reviewers: chad, btrahan
Reviewed By: chad
CC: aran
Differential Revision: https://secure.phabricator.com/D8095 | <?php
final class DifferentialEditPolicyFieldSpecification
extends DifferentialFieldSpecification {
private $value;
public function shouldAppearOnEdit() {
return true;
}
protected function didSetRevision() {
$this->value = $this->getRevision()->getEditPolicy();
}
public function setValueFromRequest(AphrontRequest $request) {
$this->value = $request->getStr('editPolicy');
return $this;
}
public function renderEditControl() {
$viewer = $this->getUser();
$revision = $this->getRevision();
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($revision)
->execute();
return id(new AphrontFormPolicyControl())
->setUser($viewer)
->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
->setPolicyObject($revision)
->setPolicies($policies)
->setName('editPolicy');
}
public function willWriteRevision(DifferentialRevisionEditor $editor) {
$this->getRevision()->setEditPolicy($this->value);
}
}
| <?php
final class DifferentialEditPolicyFieldSpecification
extends DifferentialFieldSpecification {
private $value;
public function shouldAppearOnEdit() {
return true;
}
protected function didSetRevision() {
$this->value = $this->getRevision()->getEditPolicy();
}
public function setValueFromRequest(AphrontRequest $request) {
$this->value = $request->getStr('editPolicy');
return $this;
}
public function renderEditControl() {
$viewer = $this->getUser();
$revision = $this->getRevision();
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($revision)
->execute();
return id(new AphrontFormPolicyControl())
->setUser($viewer)
->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
->setPolicyObject($revision)
->setPolicies($policies)
->setName('editPolicy')
->setCaption(
pht(
'NOTE: These policy features are not yet fully supported.'));
}
public function willWriteRevision(DifferentialRevisionEditor $editor) {
$this->getRevision()->setEditPolicy($this->value);
}
}
|
Bring back echo to ensure stability | <?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
$i = 0;
foreach (glob($dir . '/*') as $file) {
if (!is_dir($file)) {
$i++;
}
}
echo $i;
}
// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
$feed = fopen($url, 'r');
$data = stream_get_contents($feed);
fclose($feed);
echo $data;
}
// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
echo $array[array_rand($array)];
}
// `undot`
//
// Removes dots from string.
function undot($string) {
echo str_replace('.', '', $string);
} | <?php
/*
* Layout functions
*/
// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
return true;
}
}
// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
$i = 0;
foreach (glob($dir . '/*') as $file) {
if (!is_dir($file)) {
$i++;
}
}
echo $i;
}
// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
$feed = fopen($url, 'r');
$data = stream_get_contents($feed);
fclose($feed);
echo $data;
}
// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
echo $array[array_rand($array)];
}
// `undot`
//
// Removes dots from string.
function undot($string) {
$string = str_replace('.', '', $string);
} |
Simplify how query string is passed to search | import * as Backbone from 'backbone';
import Items from '../collections/items';
import SearchBoxView from '../views/searchBox-view';
import SearchResultsView from '../views/searchResults-view';
import AppView from '../views/app-view';
import Events from '../helpers/backbone-events';
import DocumentSet from '../helpers/search';
class AppRouter extends Backbone.Router {
get routes() {
return {
'': 'loadDefault',
'search/(?q=*queryString)': 'search'
};
}
initialize() {
this.listenTo(Events, 'router:go', this.go);
}
go(route) {
this.navigate(route, {trigger: true});
}
loadDefault() {
new AppView();
}
search(queryString) {
DocumentSet.search(q).then(function(result) {
let currentDocuments = new DocumentSet(result).documents;
let docCollection = new Items(currentDocuments);
new SearchResultsView({collection: docCollection}).render();
});
queryString = queryString || '';
}
}
export default AppRouter;
| import * as Backbone from 'backbone';
import Items from '../collections/items';
import SearchBoxView from '../views/searchBox-view';
import SearchResultsView from '../views/searchResults-view';
import AppView from '../views/app-view';
import Events from '../helpers/backbone-events';
import DocumentSet from '../helpers/search';
class AppRouter extends Backbone.Router {
get routes() {
return {
'': 'loadDefault',
'search/(?q=*queryString)': 'search'
};
}
initialize() {
this.listenTo(Events, 'router:go', this.go);
}
go(route) {
this.navigate(route, {trigger: true});
}
loadDefault() {
new AppView();
}
let q = queryString.substring(2);
search(queryString) {
DocumentSet.search(q).then(function(result) {
let currentDocuments = new DocumentSet(result).documents;
let docCollection = new Items(currentDocuments);
new SearchResultsView({collection: docCollection}).render();
});
}
}
export default AppRouter;
|
Set package version to 0.2.0 | from avalanche import benchmarks
from avalanche import evaluation
from avalanche import logging
from avalanche import models
from avalanche import training
__version__ = "0.2.0"
_dataset_add = None
def _avdataset_radd(self, other, *args, **kwargs):
from avalanche.benchmarks.utils import AvalancheDataset
global _dataset_add
if isinstance(other, AvalancheDataset):
return NotImplemented
return _dataset_add(self, other, *args, **kwargs)
def _avalanche_monkey_patches():
from torch.utils.data.dataset import Dataset
global _dataset_add
_dataset_add = Dataset.__add__
Dataset.__add__ = _avdataset_radd
_avalanche_monkey_patches()
| from avalanche import benchmarks
from avalanche import evaluation
from avalanche import logging
from avalanche import models
from avalanche import training
__version__ = "0.1.0a0"
_dataset_add = None
def _avdataset_radd(self, other, *args, **kwargs):
from avalanche.benchmarks.utils import AvalancheDataset
global _dataset_add
if isinstance(other, AvalancheDataset):
return NotImplemented
return _dataset_add(self, other, *args, **kwargs)
def _avalanche_monkey_patches():
from torch.utils.data.dataset import Dataset
global _dataset_add
_dataset_add = Dataset.__add__
Dataset.__add__ = _avdataset_radd
_avalanche_monkey_patches()
|
Fix showing deleted user in forum
Apparently assigning default instance variable using function requires using constructor and stuff. Reverting it for now. | <?php
/**
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Models;
class DeletedUser extends User
{
public $user_avatar = null;
public $username = '[deleted user]';
}
| <?php
/**
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License version 3
* as published by the Free Software Foundation.
*
* osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with osu!web. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Models;
class DeletedUser extends User
{
public $user_avatar = null;
public $username = trans('users.deleted');
}
|
Validate that the input file ends with .jiradoc | # ------------------------------------------------------------
# __main__.py
#
# The main program
# ------------------------------------------------------------
import argparse
import os
import pkg_resources
import sys
from jiradoc.parser.parser import parser as jiradoc_parser
def main(args=None):
parser = argparse.ArgumentParser(description='A tool that parses a JIRAdoc formatted file and returns a list of '
'story objects')
test_file = pkg_resources.resource_filename(__name__, 'data/test.jiradoc')
parser.add_argument('-f', dest='file', default=test_file,
help='A .jiradoc file containing sub-tasks to JIRA stories')
args = parser.parse_args()
filename, ext = os.path.splitext(args.file)
if ext != '.jiradoc':
print 'Invalid file extension: ' + ext
print 'The only valid extension is .jiradoc'
sys.exit(1)
with open(args.file) as f:
content = f.read()
stories = jiradoc_parser.parse(content)
for story in stories:
print story
if __name__ == "__main__":
main()
| # ------------------------------------------------------------
# __main__.py
#
# The main program which expects a jiradoc formatted file to
# be passed in as a cmdline option. It reads the file and
# parses its content to Story objects.
# ------------------------------------------------------------
import argparse
import pkg_resources
from jiradoc.parser.parser import parser
def main(args=None):
argparser = argparse.ArgumentParser(description='The JIRAdoc parser')
test_file = pkg_resources.resource_filename(__name__, 'data/test.jiradoc')
argparser.add_argument('-f', dest='file', default=test_file, help='The jiradoc formatted file')
args = argparser.parse_args()
with open(args.file) as f:
content = f.read()
stories = parser.parse(content)
for story in stories:
print story
if __name__ == "__main__":
main()
|
Add a load balanced client example | package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory (rantav@gmail.com)
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
// A load balanced version would look like this:
// CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
| package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory (rantav@gmail.com)
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
|
Revert "change from string to int"
This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252. | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not parser:
return cards
else:
return parser(cards)
def once_parser(cards):
'''parser for ONCE [2] issue mode'''
return [next(i for i in cards if i.type == "CardIssue")]
def multi_parser(cards):
'''parser for MULTI [4] issue mode'''
return cards
def mono_parser(cards):
'''parser for MONO [8] issue mode'''
return [i for i in cards if i.type == "CardIssue"
and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1]
def unflushable_parser(cards):
'''parser for UNFLUSHABLE [16] issue mode'''
return [i for i in cards if i.type == "CardIssue"]
parsers = {
'NONE': none_parser,
'CUSTOM': none_parser,
'ONCE': once_parser,
'MULTI': multi_parser,
'MONO': mono_parser,
'UNFLUSHABLE': unflushable_parser
}
| '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not parser:
return cards
else:
return parser(cards)
def once_parser(cards):
'''parser for ONCE [2] issue mode'''
return [next(i for i in cards if i.type == "CardIssue")]
def multi_parser(cards):
'''parser for MULTI [4] issue mode'''
return cards
def mono_parser(cards):
'''parser for MONO [8] issue mode'''
return [i for i in cards if i.type == "CardIssue"
and exponent_to_amount(i.amount[0], i.number_of_decimals) == 1]
def unflushable_parser(cards):
'''parser for UNFLUSHABLE [16] issue mode'''
return [i for i in cards if i.type == "CardIssue"]
parsers = {
0: none_parser,
1: custom_parser,
2: once_parser,
4: multi_parser,
8: mono_parser,
16: unflushable_parser
}
|
Use just one call system | const shell = require('shelljs');
const path = require('path');
shell.echo(`
🕓 The setup process can take few minutes.
🔸 Administration Panel
📦 Installing packages...
`);
const pwd = shell.pwd();
const silent = process.env.npm_config_debug !== 'true';
const isDevelopmentMode = path.resolve(pwd.stdout).indexOf('strapi-admin') !== -1;
const appPath = isDevelopmentMode ? path.resolve(process.env.PWD, '..') : path.resolve(pwd.stdout, '..');
// We just install the admin's dependencies here
// Remove package-lock.json.
shell.rm('-rf', path.resolve(appPath, 'package-lock.json'));
shell.rm('-rf', path.resolve(appPath, 'admin', 'package-lock.json'));
// Install the project dependencies.
shell.exec(`cd "${appPath}" && npm install --ignore-scripts`, {
silent
});
// Install the administration dependencies.
shell.exec(`cd "${path.resolve(appPath, 'admin')}" && npm install`, {
silent
});
if (isDevelopmentMode) {
shell.exec(`cd "${path.resolve(appPath, 'admin')}" && npm link strapi-helper-plugin && npm link strapi-utils`, {
silent
});
} else {
shell.exec(`cd "${path.resolve(appPath, 'admin', 'node_modules', 'strapi-helper-plugin')}" && npm install`, {
silent
});
}
shell.echo('Packaged installed successfully');
| const shell = require('shelljs');
const path = require('path');
shell.echo('');
shell.echo('🕓 The setup process can take few minutes.');
shell.echo('');
shell.echo('🔸 Administration Panel');
shell.echo('📦 Installing packages...');
const pwd = shell.pwd();
const silent = process.env.npm_config_debug !== 'true';
const isDevelopmentMode = path.resolve(pwd.stdout).indexOf('strapi-admin') !== -1;
const appPath = isDevelopmentMode ? path.resolve(process.env.PWD, '..') : path.resolve(pwd.stdout, '..');
// We just install the admin's dependencies here
// Remove package-lock.json.
shell.rm('-rf', path.resolve(appPath, 'package-lock.json'));
shell.rm('-rf', path.resolve(appPath, 'admin', 'package-lock.json'));
// Install the project dependencies.
shell.exec(`cd "${appPath}" && npm install --ignore-scripts`, {
silent
});
// Install the administration dependencies.
shell.exec(`cd "${path.resolve(appPath, 'admin')}" && npm install`, {
silent
});
if (isDevelopmentMode) {
shell.exec(`cd "${path.resolve(appPath, 'admin')}" && npm link strapi-helper-plugin && npm link strapi-utils`, {
silent
});
} else {
shell.exec(`cd "${path.resolve(appPath, 'admin', 'node_modules', 'strapi-helper-plugin')}" && npm install`, {
silent
});
}
shell.echo('Packaged installed successfully');
|
Add warning for missing pandoc | try:
from setuptools import setup
except ImportError:
from disutils.core import setup
try:
from pypandoc import convert
long_description = convert('README.md', 'rst')
except:
"""
Don't fail if pandoc or pypandoc are not installed.
However, it is better to publish the package with
a formatted README.
"""
print("""
Warning: Missing pandoc, which is used to format \
the README. Install pypandoc and pandoc before publishing \
a new version.""")
long_description = open('README.md').read()
from chargehound.version import VERSION
setup(
name='chargehound',
version=VERSION,
author='Chargehound',
author_email='support@chargehound.com',
packages=['chargehound'],
description='Chargehound Python Bindings',
long_description=long_description,
url='https://www.chargehound.com',
license='MIT',
test_suite='test.all',
install_requires=[
'requests'
],
)
| try:
from setuptools import setup
except ImportError:
from disutils.core import setup
try:
from pypandoc import convert
long_description = convert('README.md', 'rst')
except:
"""
Don't fail if pandoc or pypandoc are not installed.
However, it is better to publish the package with
a formatted README.
"""
long_description = open('README.md').read()
from chargehound.version import VERSION
setup(
name='chargehound',
version=VERSION,
author='Chargehound',
author_email='support@chargehound.com',
packages=['chargehound'],
description='Chargehound Python Bindings',
long_description=long_description,
url='https://www.chargehound.com',
license='MIT',
test_suite='test.all',
install_requires=[
'requests'
],
)
|
Include hash on file name | // Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import {join, relative, sep} from 'path'
import {getProjectDir} from '../../../paths'
const PROJECT_DIR = getProjectDir()
function fileName(file) {
const RELATIVE = relative(PROJECT_DIR, file)
let nodes = RELATIVE.split(sep)
if (nodes[0] === 'src')
nodes.shift()
return `${nodes.join(sep)}?[sha512:hash:base64:8]`
}
export default function () {
return {
exclude: /\.(css|jsx?|mjs)$/,
use: [{
loader: 'file-loader',
options: {
name: fileName,
},
}],
}
}
| // Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import {join, relative, sep} from 'path'
import {getProjectDir} from '../../../paths'
const PROJECT_DIR = getProjectDir()
function fileName(file) {
const RELATIVE = relative(PROJECT_DIR, file)
let nodes = RELATIVE.split(sep)
if (nodes[0] === 'src')
nodes.shift()
return nodes.join(sep)
}
export default function () {
return {
exclude: /\.(css|jsx?|mjs)$/,
use: [{
loader: 'file-loader',
options: {
name: fileName,
},
}],
}
}
|
Add spec file in yo write | const fountain = require('fountain-generator');
module.exports = fountain.Base.extend({
prompting() {
this.fountainPrompting();
},
configuring() {
this.mergeJson('package.json', {
dependencies: {
'axios': '^0.9.1',
'es6-promise': '^3.1.2'
}
});
if (this.props.js === 'typescript') {
this.env.addToTsd = `"axios": "github:DefinitelyTyped/DefinitelyTyped/axios/axios.d.ts#bcd5761826eb567876c197ccc6a87c4d05731054",`;
}
},
writing: {
src() {
[
'src/index.js',
'src/index.css',
'src/app/footer.js',
'src/app/footer.spec.js',
'src/app/header.js',
'src/app/main.js',
'src/app/title.js',
'src/app/techs/tech.js',
'src/app/techs/techs.js'
].map(file => this.copyTemplate(file, file));
},
techs() {
this.prepareTechJson();
}
}
});
| const fountain = require('fountain-generator');
module.exports = fountain.Base.extend({
prompting() {
this.fountainPrompting();
},
configuring() {
this.mergeJson('package.json', {
dependencies: {
'axios': '^0.9.1',
'es6-promise': '^3.1.2'
}
});
if (this.props.js === 'typescript') {
this.env.addToTsd = `"axios": "github:DefinitelyTyped/DefinitelyTyped/axios/axios.d.ts#bcd5761826eb567876c197ccc6a87c4d05731054",`;
}
},
writing: {
src() {
[
'src/index.js',
'src/index.css',
'src/app/footer.js',
'src/app/header.js',
'src/app/main.js',
'src/app/title.js',
'src/app/techs/tech.js',
'src/app/techs/techs.js'
].map(file => this.copyTemplate(file, file));
},
techs() {
this.prepareTechJson();
}
}
});
|
Remove weird text shadow under links | import Typography from 'typography';
import theme from 'typography-theme-ocean-beach';
theme.googleFonts.push(
{
name: 'M+PLUS+1p',
styles: ['400'],
},
{
name: 'Noto+Sans+JP',
styles: ['400'],
}
);
theme.headerFontFamily = ['Roboto Slab', 'M PLUS 1p', 'sans-serif'];
theme.bodyFontFamily = ['Roboto', 'Noto Sans JP', 'sans-serif'];
theme.overrideThemeStyles = () => ({
a: {
'text-decoration': 'underline',
'text-decoration-thickness': '0.1em',
'background-image': 'none',
color: '#222',
'text-shadow': 'none',
},
'a:hover': {
'text-decoration': 'none',
},
blockquote: {
'border-left-width': '0.5rem',
'border-left-color': 'inherit',
'margin-left': '-1.5rem',
},
'p code': {
'font-size': '1rem',
'line-height': '1.5',
},
'li code': {
'font-size': '1rem',
'line-height': '1.5',
},
pre: {
'margin-left': '-1.3125em',
'margin-right': '-1.3125em',
'line-height': '1.5',
},
});
const typography = new Typography(theme);
export default typography;
| import Typography from 'typography';
import theme from 'typography-theme-ocean-beach';
theme.googleFonts.push(
{
name: 'M+PLUS+1p',
styles: ['400'],
},
{
name: 'Noto+Sans+JP',
styles: ['400'],
}
);
theme.headerFontFamily = ['Roboto Slab', 'M PLUS 1p', 'sans-serif'];
theme.bodyFontFamily = ['Roboto', 'Noto Sans JP', 'sans-serif'];
theme.overrideThemeStyles = () => ({
a: {
'text-decoration': 'underline',
'text-decoration-thickness': '0.1em',
'background-image': 'none',
color: '#222',
},
'a:hover': {
'text-decoration': 'none',
},
blockquote: {
'border-left-width': '0.5rem',
'border-left-color': 'inherit',
'margin-left': '-1.5rem',
},
'p code': {
'font-size': '1rem',
'line-height': '1.5',
},
'li code': {
'font-size': '1rem',
'line-height': '1.5',
},
pre: {
'margin-left': '-1.3125em',
'margin-right': '-1.3125em',
'line-height': '1.5',
},
});
const typography = new Typography(theme);
export default typography;
|
Fix router test server helper to listen for new lifted log line | var request = require('request');
var fs = require('fs');
var spawn = require('child_process').spawn;
module.exports = {
// Write routes object to router file
writeRoutes: function(routes) {
fs.writeFileSync('config/routes.js', 'module.exports.routes = ' + JSON.stringify(routes));
},
// Starts sails server, makes request, returns response, kills sails server
testRoute: function(method, options, callback) {
// Prefix url with domain:port
if (typeof options === 'string') {
options = 'http://localhost:1337/' + options;
} else {
options.url = 'http://localhost:1337/' + options.url;
}
// Start the sails server process
var sailsprocess = spawn('../bin/sails.js', ['lift']);
sailsprocess.stderr.on('data',function(data) {
// Change buffer to string
var dataString = data + '';
// Make request once server has sucessfully started
if (dataString.match(/Sails \S+ lifted/)) {
request[method](options, function(err, response) {
if (err) callback(err);
// Kill server process and return response
sailsprocess.kill();
callback(null, response);
});
}
});
}
};
| var request = require('request');
var fs = require('fs');
var spawn = require('child_process').spawn;
module.exports = {
// Write routes object to router file
writeRoutes: function(routes) {
fs.writeFileSync('config/routes.js', 'module.exports.routes = ' + JSON.stringify(routes));
},
// Starts sails server, makes request, returns response, kills sails server
testRoute: function(method, options, callback) {
// Prefix url with domain:port
if (typeof options === 'string') {
options = 'http://localhost:1337/' + options;
} else {
options.url = 'http://localhost:1337/' + options.url;
}
// Start the sails server process
var sailsprocess = spawn('../bin/sails.js', ['lift']);
sailsprocess.stderr.on('data',function(data) {
// Change buffer to string
var dataString = data + '';
// Make request once server has sucessfully started
if (dataString.indexOf('http://localhost:1337') !== -1) {
request[method](options, function(err, response) {
if (err) callback(err);
// Kill server process and return response
sailsprocess.kill();
callback(null, response);
});
}
});
}
};
|
Remove unused org member in factory | import factory
from bluebottle.organizations.models import OrganizationContact, Organization
from .geo import CountryFactory
from .accounts import BlueBottleUserFactory
class OrganizationFactory(factory.DjangoModelFactory):
class Meta(object):
model = Organization
name = factory.Sequence(lambda n: 'Organization_{0}'.format(n))
slug = factory.Sequence(lambda n: 'organization_{0}'.format(n))
address_line1 = "'s Gravenhekje 1a"
address_line2 = '1011 TG'
city = 'Amsterdam'
state = 'North Holland'
country = factory.SubFactory(CountryFactory, name='Netherlands')
postal_code = '1011TG'
# Contact
phone_number = '(+31) 20 715 8980'
website = 'http://onepercentclub.com'
email = 'info@onepercentclub.com'
class OrganizationContactFactory(factory.DjangoModelFactory):
class Meta(object):
model = OrganizationContact
name = factory.Sequence(lambda n: 'Contact_{0}'.format(n))
phone = factory.Sequence(lambda n: '555-{0}'.format(n))
email = factory.Sequence(lambda n: '{0}@example.com'.format(n))
owner = factory.SubFactory(BlueBottleUserFactory)
organization = factory.SubFactory(OrganizationFactory)
| import factory
from bluebottle.organizations.models import OrganizationContact, Organization, OrganizationMember
from .geo import CountryFactory
from .accounts import BlueBottleUserFactory
class OrganizationFactory(factory.DjangoModelFactory):
class Meta(object):
model = Organization
name = factory.Sequence(lambda n: 'Organization_{0}'.format(n))
slug = factory.Sequence(lambda n: 'organization_{0}'.format(n))
address_line1 = "'s Gravenhekje 1a"
address_line2 = '1011 TG'
city = 'Amsterdam'
state = 'North Holland'
country = factory.SubFactory(CountryFactory, name='Netherlands')
postal_code = '1011TG'
# Contact
phone_number = '(+31) 20 715 8980'
website = 'http://onepercentclub.com'
email = 'info@onepercentclub.com'
class OrganizationContactFactory(factory.DjangoModelFactory):
class Meta(object):
model = OrganizationContact
name = factory.Sequence(lambda n: 'Contact_{0}'.format(n))
phone = factory.Sequence(lambda n: '555-{0}'.format(n))
email = factory.Sequence(lambda n: '{0}@example.com'.format(n))
owner = factory.SubFactory(BlueBottleUserFactory)
organization = factory.SubFactory(OrganizationFactory)
class OrganizationMemberFactory(factory.DjangoModelFactory):
class Meta(object):
model = OrganizationMember
user = factory.SubFactory(BlueBottleUserFactory)
function = 'owner'
organization = factory.SubFactory(OrganizationFactory)
|
Create test that fails when actual cleanup caused | # coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
yield "Oh snap."
for _ in range(10001):
yield "I erase lemmas."
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "It's sentence produced by that bug."
anchor = None
remember = None
for i, d in enumerate(nlp.pipe(string_generator())):
if i == 9999:
anchor = d
elif 10001 == i:
remember = d
elif i == 10002:
del anchor
gc.collect()
# We should run cleanup more than one time to actually cleanup data.
# In first run — clean up only mark strings as «not hitted».
if i == 20000 or i == 30000:
gc.collect()
for t in d:
str(t.lemma_)
assert remember.text == 'Oh snap.'
| # coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
yield "Oh snap."
for _ in range(10001):
yield "I erase lemmas."
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "It's sentence produced by that bug."
anchor = None
remember = None
for i, d in enumerate(nlp.pipe(string_generator())):
if i == 9999:
anchor = d
elif 10001 == i:
remember = d
elif i == 10002:
del anchor
gc.collect()
for t in d:
str(t.lemma_)
assert remember.text == 'Oh snap.'
|
Add to download links ng-csv | var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3030',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3030
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
| var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3051',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3051
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
|
Fix demos to use readTokenXxx() | /*
* Copyright 2015 Ivan Pribela
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.svetovid.demo;
import org.svetovid.Svetovid;
public class HelloWorld {
public static void main(String[] args) {
// Ask for a name
String name = Svetovid.in.readLine("Please enter your name:");
// Greet the user
Svetovid.out.println("Hello " + name + "!");
}
}
| /*
* Copyright 2015 Ivan Pribela
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.svetovid.demo;
import org.svetovid.Svetovid;
public class HelloWorld {
public static void main(String[] args) {
// Ask for a name
String name = Svetovid.in.readString("Please enter your name:");
// Greet the user
Svetovid.out.println("Hello " + name + "!");
}
}
|
Adjust stack level returned to account for it being calculated one level deeper than it is being used.
Also, make the stack level calculator private until there is a need to make it public. | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import warnings
# This function is from https://github.com/python/cpython/issues/67998
# (https://bugs.python.org/file39550/deprecated_module_stacklevel.diff) and
# calculates the appropriate stacklevel for deprecations to target the
# deprecation for the caller, no matter how many internal stack frames we have
# added in the process. For example, with the deprecation warning in the
# __init__ below, the appropriate stacklevel will change depending on how deep
# the inheritance hierarchy is.
def _external_stacklevel(internal):
"""Find the first frame that doesn't any of the given internal strings
The depth will be 1 at minimum in order to start checking at the caller of
the function that called this utility method.
"""
# Get the level of my caller's caller
level = 2
frame = sys._getframe(level)
while frame and any(s in frame.f_code.co_filename for s in internal):
level +=1
frame = frame.f_back
# the returned value will be used one level up from here, so subtract one
return level-1
def deprecation(message, internal=None):
"""Generate a deprecation warning targeting the first frame outside the ipywidgets library.
internal is a list of strings, which if they appear in filenames in the
frames, the frames will also be considered internal. This can be useful if we know that ipywidgets
is calling out to, for example, traitlets internally.
"""
if internal is None:
internal = []
warnings.warn(message, DeprecationWarning, stacklevel=_external_stacklevel(internal+['ipywidgets/widgets/']))
| # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import warnings
# This function is from https://github.com/python/cpython/issues/67998
# (https://bugs.python.org/file39550/deprecated_module_stacklevel.diff) and
# calculates the appropriate stacklevel for deprecations to target the
# deprecation for the caller, no matter how many internal stack frames we have
# added in the process. For example, with the deprecation warning in the
# __init__ below, the appropriate stacklevel will change depending on how deep
# the inheritance hierarchy is.
def external_stacklevel(internal):
"""Find the first frame that doesn't any of the given internal strings
The depth will be 2 at minimum in order to start checking at the caller of
the function that called this utility method.
"""
level = 2
frame = sys._getframe(level)
while frame and any(s in frame.f_code.co_filename for s in internal):
level +=1
frame = frame.f_back
return level
def deprecation(message, internal=None):
"""Generate a deprecation warning targeting the first external frame
internal is a list of strings, which if they appear in filenames in the
frames, the frames will also be considered internal.
"""
if internal is None:
internal = []
warnings.warn(message, DeprecationWarning, stacklevel=external_stacklevel(internal+['ipywidgets/widgets/']))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.