text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix parsing of taskWarrior's output
I don't know for older versions, but the latest stable release already
have '[' and ']' when doing an export. This lead to raising an exception
because it makes a nested list and you try to access it using a string
rather than an integer | # -*- coding: utf-8 -*-
"""
Display currently active (started) taskwarrior tasks.
Configuration parameters:
- cache_timeout : how often we refresh this module in seconds (5s default)
Requires
- task
@author James Smith http://jazmit.github.io/
@license BSD
"""
# import your useful libs here
from time import time
from subprocess import check_output
import json
import shlex
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 5
def taskWarrior(self, i3s_output_list, i3s_config):
command = 'task start.before:tomorrow status:pending export'
taskwarrior_output = check_output(shlex.split(command))
tasks_json = json.loads(taskwarrior_output.decode('utf-8'))
def describeTask(taskObj):
return str(taskObj['id']) + ' ' + taskObj['description']
result = ', '.join(map(describeTask, tasks_json))
response = {
'cached_until': time() + self.cache_timeout,
'full_text': result
}
return response
if __name__ == "__main__":
"""
Test this module by calling it directly.
"""
from time import sleep
x = Py3status()
config = {
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
'color_good': '#00FF00'
}
while True:
print(x.taskWarrior([], config))
sleep(1)
| # -*- coding: utf-8 -*-
"""
Display currently active (started) taskwarrior tasks.
Configuration parameters:
- cache_timeout : how often we refresh this module in seconds (5s default)
Requires
- task
@author James Smith http://jazmit.github.io/
@license BSD
"""
# import your useful libs here
from time import time
from subprocess import check_output
import json
import shlex
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 5
def taskWarrior(self, i3s_output_list, i3s_config):
command = 'task start.before:tomorrow status:pending export'
taskwarrior_output = check_output(shlex.split(command))
tasks_json = json.loads('[' + taskwarrior_output.decode('utf-8') + ']')
def describeTask(taskObj):
return str(taskObj['id']) + ' ' + taskObj['description']
result = ', '.join(map(describeTask, tasks_json))
response = {
'cached_until': time() + self.cache_timeout,
'full_text': result
}
return response
if __name__ == "__main__":
"""
Test this module by calling it directly.
"""
from time import sleep
x = Py3status()
config = {
'color_bad': '#FF0000',
'color_degraded': '#FFFF00',
'color_good': '#00FF00'
}
while True:
print(x.taskWarrior([], config))
sleep(1)
|
Modify url for mentor search get request | app.controller('SearchController', ['$http', function($http) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
// .config(function($mdThemingProvider) {
// $mdThemingProvider.theme('docs-dark', 'default')
// .primaryPalette('yellow')
// .dark();
//
// });
self.test = function() {
console.log(self.newSearch);
};
self.getMentors = function() {
console.log(self.newSearch);
var newSearchString = JSON.stringify(self.newSearch);
return $http({
method: 'GET',
url: '/mentor-search/search',
headers: {
newSearchString: newSearchString
}
})
.then(function (response) {
self.mentors = response.data;
console.log("Mentors list:", self.mentors);
}),
function(err){
console.log("Error with search get request ", err);
};
}
}]);
/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/
| app.controller('SearchController', ['$http', function($http) {
console.log('SearchController running');
var self = this;
self.mentors = [];
self.newSearch = {
first_name: null,
last_name: null,
email: null,
company: null,
job_title: null,
zip: null,
race: null,
sex: null,
orientation: null,
birthday: null,
school: null,
degree: null,
major: null,
language: null
};
// .config(function($mdThemingProvider) {
// $mdThemingProvider.theme('docs-dark', 'default')
// .primaryPalette('yellow')
// .dark();
//
// });
self.test = function() {
console.log(self.newSearch);
};
self.getMentors = function() {
console.log(self.newSearch);
var newSearchString = JSON.stringify(self.newSearch);
return $http({
method: 'GET',
url: '/mentor-search',
headers: {
newSearchString: newSearchString
}
})
.then(function (response) {
self.mentors = response.data;
console.log("Mentors list:", self.mentors);
}),
function(err){
console.log("Error with search get request ", err);
};
}
}]);
/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/
|
Include district in updated e-mail. | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = values.participants.map(p => <li key={p.id}>{p.name}</li>);
return renderEmail(
<Email title={`${values.event.customQuestions.emailSubjectTag} Booking Updated`}>
<Item>
<p>Hi {values.emailUser.userName},</p>
<p>{values.userName} has updated their booking {values.district ? `for ${values.district}` : ''} to {values.event.name}. They have
booked {values.participants.length} {values.participants.length === 1 ? 'person' : 'people'}:</p>
<p>
<ul>{participantsList}</ul>
</p>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `${values.event.customQuestions.emailSubjectTag} Booking Updated`;
} | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = values.participants.map(p => <li key={p.id}>{p.name}</li>);
return renderEmail(
<Email title={`${values.event.customQuestions.emailSubjectTag} Booking Updated`}>
<Item>
<p>Hi {values.emailUser.userName},</p>
<p>{values.userName} has updated booking to {values.event.name}. They have
booked {values.participants.length} {values.participants.length === 1 ? 'person' : 'people'}:</p>
<p>
<ul>{participantsList}</ul>
</p>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `${values.event.customQuestions.emailSubjectTag} Booking Updated`;
} |
Upgrade pyflakes from 0.7.3 to 0.8 | from setuptools import setup
setup(
name='tangled',
version='0.1a8.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=[
'tangled',
'tangled.scripts',
'tangled.tests',
'tangled.tests.dummy_package',
],
extras_require={
'dev': (
'coverage>=3.7.1',
'nose>=1.3.1',
'pep8>=1.4.6',
'pyflakes>=0.8',
'Sphinx>=1.2.2',
'sphinx_rtd_theme>=0.1.5',
)
},
entry_points="""
[console_scripts]
tangled = tangled.__main__:main
[tangled.scripts]
release = tangled.scripts:ReleaseCommand
scaffold = tangled.scripts:ScaffoldCommand
python = tangled.scripts:ShellCommand
test = tangled.scripts:TestCommand
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled',
version='0.1a8.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled/tags',
author='Wyatt Baldwin',
author_email='[email protected]',
packages=[
'tangled',
'tangled.scripts',
'tangled.tests',
'tangled.tests.dummy_package',
],
extras_require={
'dev': (
'coverage>=3.7.1',
'nose>=1.3.1',
'pep8>=1.4.6',
'pyflakes>=0.7.3',
'Sphinx>=1.2.2',
'sphinx_rtd_theme>=0.1.5',
)
},
entry_points="""
[console_scripts]
tangled = tangled.__main__:main
[tangled.scripts]
release = tangled.scripts:ReleaseCommand
scaffold = tangled.scripts:ScaffoldCommand
python = tangled.scripts:ShellCommand
test = tangled.scripts:TestCommand
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite. | from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
| from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
Switch triggerUnti lfunction (deprecated) to trigger function | <?php
namespace Detail\Apigility\Rest\Resource;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;
use Detail\Apigility\Exception;
class Resource extends BaseResource
{
public function patchMultiple($ids, $data)
{
if (!is_array($ids)) {
throw new Exception\InvalidArgumentException(
sprintf(
'Data provided to %s must be an array of identifiers; received "%s"',
__FUNCTION__,
gettype($data)
)
);
}
if (is_array($data)) {
$data = (object) $data;
}
if (!is_object($data)) {
throw new Exception\InvalidArgumentException(
sprintf(
'Data provided to create must be either an array or object; received "%s"',
gettype($data)
)
);
}
$events = $this->getEventManager();
$event = $this->prepareEvent(__FUNCTION__, array('ids' => $ids, 'data' => $data));
$results = $events->trigger(
$event,
function ($result) {
return ($result instanceof ApiProblem || $result instanceof ApiProblemResponse);
}
);
$last = $results->last();
if (!is_array($last) && !is_object($last)) {
return $data;
}
return $last;
}
}
| <?php
namespace Detail\Apigility\Rest\Resource;
use ZF\ApiProblem\ApiProblem;
use ZF\ApiProblem\ApiProblemResponse;
use ZF\Rest\Resource as BaseResource;
use Detail\Apigility\Exception;
class Resource extends BaseResource
{
public function patchMultiple($ids, $data)
{
if (!is_array($ids)) {
throw new Exception\InvalidArgumentException(
sprintf(
'Data provided to %s must be an array of identifiers; received "%s"',
__FUNCTION__,
gettype($data)
)
);
}
if (is_array($data)) {
$data = (object) $data;
}
if (!is_object($data)) {
throw new Exception\InvalidArgumentException(
sprintf(
'Data provided to create must be either an array or object; received "%s"',
gettype($data)
)
);
}
$events = $this->getEventManager();
$event = $this->prepareEvent(__FUNCTION__, array('ids' => $ids, 'data' => $data));
$results = $events->triggerUntil(
$event,
function ($result) {
return ($result instanceof ApiProblem || $result instanceof ApiProblemResponse);
}
);
$last = $results->last();
if (!is_array($last) && !is_object($last)) {
return $data;
}
return $last;
}
}
|
Fix core logging when no message on channel | from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
"""
def __init__(self, channel_layer, callback=None):
self.channel_layer = channel_layer
self.callback = callback
def run(self):
"""
Tries to continually dispatch messages to consumers.
"""
channels = self.channel_layer.registry.all_channel_names()
while True:
channel, content = self.channel_layer.receive_many(channels, block=True)
# If no message, stall a little to avoid busy-looping then continue
if channel is None:
time.sleep(0.01)
continue
# Create message wrapper
logger.debug("Worker got message on %s: repl %s", channel, content.get("reply_channel", "none"))
message = Message(
content=content,
channel_name=channel,
channel_layer=self.channel_layer,
)
# Handle the message
consumer = self.channel_layer.registry.consumer_for_channel(channel)
if self.callback:
self.callback(channel, message)
try:
consumer(message)
except:
logger.exception("Error processing message with consumer %s:", name_that_thing(consumer))
| from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
"""
def __init__(self, channel_layer, callback=None):
self.channel_layer = channel_layer
self.callback = callback
def run(self):
"""
Tries to continually dispatch messages to consumers.
"""
channels = self.channel_layer.registry.all_channel_names()
while True:
channel, content = self.channel_layer.receive_many(channels, block=True)
logger.debug("Worker got message on %s: repl %s", channel, content.get("reply_channel", "none"))
# If no message, stall a little to avoid busy-looping then continue
if channel is None:
time.sleep(0.01)
continue
# Create message wrapper
message = Message(
content=content,
channel_name=channel,
channel_layer=self.channel_layer,
)
# Handle the message
consumer = self.channel_layer.registry.consumer_for_channel(channel)
if self.callback:
self.callback(channel, message)
try:
consumer(message)
except:
logger.exception("Error processing message with consumer %s:", name_that_thing(consumer))
|
Support variables with - and _ symbols | import * as postcss from 'postcss';
import * as _ from 'underscore';
export default postcss.plugin('postcss-themeize', (options = {}) => {
const themesOptions = options.themes || {};
const themesConfig = _.reduce(themesOptions, (memo, config, theme) => {
_.each(config, (value, rule) => {
memo[rule] = [...(memo[rule] || []), { theme, value }];
});
return memo;
}, {});
return root => {
root.walkRules(rule => {
const themes = {};
rule.walkDecls(decl => {
const matches = decl.value.match(/@([a-zA-Z0-9\-_]+)\s*?/);
const match = matches && matches[1];
if (match && themesConfig[match]) {
const config = themesConfig[match];
config.forEach(({ theme, value }) => {
const clonedDecl = decl.clone({
value: decl.value.replace(`@${match}`, value)
});
const decls = themes[theme] || [];
themes[theme] = [...decls, clonedDecl];
});
}
if (match) {
decl.remove();
}
});
if (_.isEmpty(themes)) {
return;
}
_.each(themes, (decls, theme) => {
const themeRule = rule.cloneAfter({
selector: `.${theme} ${rule.selector}`
});
themeRule.removeAll().append(decls);
});
});
};
});
| import * as postcss from 'postcss';
import * as _ from 'underscore';
export default postcss.plugin('postcss-themeize', (options = {}) => {
const themesOptions = options.themes || {};
const themesConfig = _.reduce(themesOptions, (memo, config, theme) => {
_.each(config, (value, rule) => {
memo[rule] = [...(memo[rule] || []), { theme, value }];
});
return memo;
}, {});
return root => {
root.walkRules(rule => {
const themes = {};
rule.walkDecls(decl => {
const matches = decl.value.match(/@([a-zA-Z0-9]+)\s*?/);
const match = matches && matches[1];
if (match && themesConfig[match]) {
const config = themesConfig[match];
config.forEach(({ theme, value }) => {
const clonedDecl = decl.clone({
value: decl.value.replace(`@${match}`, value)
});
const decls = themes[theme] || [];
themes[theme] = [...decls, clonedDecl];
});
}
if (match) {
decl.remove();
}
});
if (_.isEmpty(themes)) {
return;
}
_.each(themes, (decls, theme) => {
const themeRule = rule.cloneAfter({
selector: `.${theme} ${rule.selector}`
});
themeRule.removeAll().append(decls);
});
});
};
});
|
Add sound level to influx | # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class DustNode(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("dust-node-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
return
influx_data = {
"measurement": "dustnode",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"room_humidity": data["data"]["room_humidity"],
"room_temperature": round(data["data"]["room_temperature"], 1),
"barometer_temperature": round(data["data"]["barometer_temperature"], 1),
"barometer_pressure": round(data["data"]["barometer_reading"], 1),
"dust_density": round(data["data"]["dust_density"], 5),
"sound_level": data["data"]["sound_level"],
}
}
self.insert_into_influx([influx_data])
def main():
item = DustNode()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
| # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class DustNode(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("dust-node-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
return
influx_data = {
"measurement": "dustnode",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"room_humidity": data["data"]["room_humidity"],
"room_temperature": round(data["data"]["room_temperature"], 1),
"barometer_temperature": round(data["data"]["barometer_temperature"], 1),
"barometer_pressure": round(data["data"]["barometer_reading"], 1),
"dust_density": round(data["data"]["dust_density"], 5)
}
}
self.insert_into_influx([influx_data])
def main():
item = DustNode()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
Allow spaces in template variables | JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_ \.]+)\s*}}/g);
var l = matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
// Pre-compute the search/replace functions
// This drastically speeds up template execution
var replacements = [];
var get_replacement = function(i) {
var p = matches[i].replace(/[{}]+/g,'').trim().split('.');
var n = p.length;
var func;
if(n > 1) {
var cur;
func = function(vars) {
cur = vars;
for(i=0; i<n; i++) {
cur = cur[p[i]];
if(!cur) break;
}
return cur;
};
}
else {
p = p[0];
func = function(vars) {
return vars[p];
};
}
replacements.push({
s: matches[i],
r: func
});
};
for(var i=0; i<l; i++) {
get_replacement(i);
}
// The compiled function
return function(vars) {
var ret = template+"";
var r;
for(i=0; i<l; i++) {
r = replacements[i];
ret = ret.replace(r.s, r.r(vars));
}
return ret;
};
}
};
};
| JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_\.]+)\s*}}/g);
var l = matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
// Pre-compute the search/replace functions
// This drastically speeds up template execution
var replacements = [];
var get_replacement = function(i) {
var p = matches[i].replace(/[{}\s]+/g,'').split('.');
var n = p.length;
var func;
if(n > 1) {
var cur;
func = function(vars) {
cur = vars;
for(i=0; i<n; i++) {
cur = cur[p[i]];
if(!cur) break;
}
return cur;
};
}
else {
p = p[0];
func = function(vars) {
return vars[p];
};
}
replacements.push({
s: matches[i],
r: func
});
};
for(var i=0; i<l; i++) {
get_replacement(i);
}
// The compiled function
return function(vars) {
var ret = template+"";
var r;
for(i=0; i<l; i++) {
r = replacements[i];
ret = ret.replace(r.s, r.r(vars));
}
return ret;
};
}
};
};
|
Modify function that calculate the expected signature | import logging
import hashlib
import hmac
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
for app in apps:
if app.connector.name.lower() == 'facebook':
return app
return None
def _valid_request(app_secret, req_signature, payload):
exp_signature = 'sha1=' + hmac.new(app_secret, msg=unicode(payload), digestmod=hashlib.sha1).hexdigest()
return exp_signature == req_signature
@csrf_exempt
def fb_real_time_updates(request):
fb_app = _get_facebook_app()
if fb_app:
if request.method == 'GET':
challenge = request.GET.get('hub.challenge')
token = request.GET.get('hub.verify_token')
if fb_app.token_real_time_updates == token:
logger.info('Token received!')
return HttpResponse(challenge)
elif request.method == 'POST':
logger.info(request.body)
req_signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if _valid_request(fb_app.app_secret,req_signature,request.body):
req_json = json.loads(request.body)
logger.info(req_json)
return HttpResponse()
else:
logger.info('The received signature does not correspond to the expected one!')
return HttpResponseForbidden()
| import logging
import hashlib
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
for app in apps:
if app.connector.name.lower() == 'facebook':
return app
return None
@csrf_exempt
def fb_real_time_updates(request):
fb_app = _get_facebook_app()
if fb_app:
if request.method == 'GET':
challenge = request.GET.get('hub.challenge')
token = request.GET.get('hub.verify_token')
if fb_app.token_real_time_updates == token:
logger.info('Token received!')
return HttpResponse(challenge)
elif request.method == 'POST':
logger.info(request.body)
req_signature = request.META.get('HTTP_X_HUB_SIGNATURE')
logger.info(req_signature)
exp_signature = 'sha1=' + hashlib.sha1('sha1='+unicode(request.body)+fb_app.app_secret).hexdigest()
logger.info(exp_signature)
req_json = json.loads(request.body)
if req_signature == exp_signature:
logger.info(req_json)
return HttpResponse()
else:
logger.info('The received signature does not correspond to the expected one!')
return HttpResponseForbidden()
|
Raise an error when a symbol cannot be found | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self, key):
if key in self.binds:
return self.binds[key]
elif self.parent:
return self.parent.get(key)
else:
raise ValueError("Invalid symbol " + key)
def set(self, key, value):
if key in self.binds:
self.binds[key] = value
elif self.parent:
self.parent.set(key,value)
else:
self.binds[key] = value
def __repr__( self):
ret = "\n%s:\n" % self.level
keys = self.binds.keys()
for key in keys:
ret = ret + " %5s: %s\n" % (key, self.binds[key])
return ret
| class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self, key):
if key in self.binds:
return self.binds[key]
elif self.parent:
return self.parent.get(key)
else:
return None
def set(self, key, value):
if key in self.binds:
self.binds[key] = value
elif self.parent:
self.parent.set(key,value)
else:
self.binds[key] = value
def __repr__( self):
ret = "\n%s:\n" % self.level
keys = self.binds.keys()
for key in keys:
ret = ret + " %5s: %s\n" % (key, self.binds[key])
return ret
|
Add ref for file upload dropZone | import { h, Component } from 'preact';
import Dropzone from 'react-dropzone';
import style from './style';
export default class FileUpload extends Component {
constructor(props) {
super(props);
this.dropzoneRef = null;
this.state = {
isFileSelected: false,
file: false,
};
this.handleFileDrop = this.handleFileDrop.bind(this);
}
handleFileDrop(acceptedFiles, rejectedFiles) {
this.setState({
...this.state,
isFileSelected: true,
file: acceptedFiles[0],
});
this.props.confirmChooseFile(this.state.file);
}
render(props, state) {
return (
<div class={`${style['file-upload']} container`}>
<div class="offset-by-three one column">
<Dropzone
onDrop={this.handleFileDrop}
multiple={false}
class={style['file']}
className={style['file']}
accept=".stl"
ref={(node) => { this.dropzoneRef = node; }}
>
<div class={style['file__text']}>Přidejte model ve formátu STL přetáhnutím souboru nebo kliknutím</div>
</Dropzone>
</div>
{/*<div class={`one column offset-by-two ${style['button']}`}>*/}
{/*<button class="button-primary disabled" disabled={!state.isFileSelected} onClick={this.handleAnalyzeButtonClick} type="button">Go to details</button>*/}
{/*</div>*/}
</div>
);
}
}
| import { h, Component } from 'preact';
import Dropzone from 'react-dropzone';
import style from './style';
export default class FileUpload extends Component {
constructor(props) {
super(props);
this.state = {
isFileSelected: false,
file: false,
};
this.handleFileDrop = this.handleFileDrop.bind(this);
}
handleFileDrop(acceptedFiles, rejectedFiles) {
this.setState({
...this.state,
isFileSelected: true,
file: acceptedFiles[0],
});
this.props.confirmChooseFile(this.state.file);
}
render(props, state) {
return (
<div class={`${style['file-upload']} container`}>
<div class="offset-by-three one column">
<Dropzone
onDrop={this.handleFileDrop}
multiple={false}
class={style['file']}
className={style['file']}
accept=".stl"
>
<div class={style['file__text']}>Přidejte model ve formátu STL přetáhnutím souboru nebo kliknutím</div>
</Dropzone>
</div>
{/*<div class={`one column offset-by-two ${style['button']}`}>*/}
{/*<button class="button-primary disabled" disabled={!state.isFileSelected} onClick={this.handleAnalyzeButtonClick} type="button">Go to details</button>*/}
{/*</div>*/}
</div>
);
}
}
|
Throw an appropriate AuthenticateException when a chat-api authentication error code is encountered. | <?php
namespace MessageBird\Common;
use MessageBird\Exceptions;
/**
* Class ResponseError
*
* @package MessageBird\Common
*/
class ResponseError
{
const SUCCESS = 1;
const REQUEST_NOT_ALLOWED = 2;
const MISSING_PARAMS = 9;
const INVALID_PARAMS = 10;
const NOT_FOUND = 20;
const NOT_ENOUGH_CREDIT = 25;
const CHAT_API_AUTH_ERROR = 1001;
public $errors = array ();
/**
* Load the error data into an array.
* Throw an exception when important errors are found.
*
* @param $body
*
* @throws Exceptions\BalanceException
* @throws Exceptions\AuthenticateException
*/
public function __construct($body)
{
if (!empty($body->errors)) {
foreach ($body->errors AS $error) {
if ($error->code === self::NOT_ENOUGH_CREDIT) {
throw new Exceptions\BalanceException;
} elseif ($error->code === self::REQUEST_NOT_ALLOWED) {
throw new Exceptions\AuthenticateException;
} elseif ($error->code === self::CHAT_API_AUTH_ERROR) {
throw new Exceptions\AuthenticateException;
}
$this->errors[] = $error;
}
}
}
/**
* Get the error string to show in the Exception message.
*
* @return string
*/
public function getErrorString()
{
$errorString = array ();
foreach ($this->errors AS $error) {
$errorString[] = $error->description;
}
return implode(', ', $errorString);
}
}
| <?php
namespace MessageBird\Common;
use MessageBird\Exceptions;
/**
* Class ResponseError
*
* @package MessageBird\Common
*/
class ResponseError
{
const SUCCESS = 1;
const REQUEST_NOT_ALLOWED = 2;
const MISSING_PARAMS = 9;
const INVALID_PARAMS = 10;
const NOT_FOUND = 20;
const NOT_ENOUGH_CREDIT = 25;
public $errors = array ();
/**
* Load the error data into an array.
* Throw an exception when important errors are found.
*
* @param $body
*
* @throws Exceptions\BalanceException
* @throws Exceptions\AuthenticateException
*/
public function __construct($body)
{
if (!empty($body->errors)) {
foreach ($body->errors AS $error) {
if ($error->code === self::NOT_ENOUGH_CREDIT) {
throw new Exceptions\BalanceException;
} elseif ($error->code === self::REQUEST_NOT_ALLOWED) {
throw new Exceptions\AuthenticateException;
}
$this->errors[] = $error;
}
}
}
/**
* Get the error string to show in the Exception message.
*
* @return string
*/
public function getErrorString()
{
$errorString = array ();
foreach ($this->errors AS $error) {
$errorString[] = $error->description;
}
return implode(', ', $errorString);
}
}
|
[CFG] Rename 'format' route to 'accept' | <?php
return [
'name_prefix' => 'aura.demo.',
'routes' => [
'home' => [
'path' => '/',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'hello' => [
'path' => '/hello',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'logo' => [
'path' => '/logo',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'logo',
],
],
'accept' => [
'path' => '/accept{:format:(\..+)?}',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'accept'
],
],
],
];
| <?php
return [
'name_prefix' => 'aura.demo.',
'routes' => [
'home' => [
'path' => '/',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'hello' => [
'path' => '/hello',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'index',
],
],
'logo' => [
'path' => '/logo',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'logo',
],
],
'format' => [
'path' => '/accept{:format:(\..+)?}',
'values' => [
'controller' => 'aura.demo.hello',
'action' => 'accept'
],
],
],
];
|
Fix bind of the switches and increase perf with the DOM | function RenderClass(element) {
var _private = this;
_private.el = null;
this.update = function (data) {
if (_private.el === null) { return; }
for (var container of data) {
var isChecked = (container.state === 'Up')
var newLine = document.getElementById('template').cloneNode(true);
var lineIfExist = document.getElementById('container-' + container.name)
newLine.innerHTML = newLine.innerHTML
.replace(/{{name}}/g, container.name)
.replace(/{{path}}/g, container.path)
.replace(/{{ischecked}}/g, isChecked ? 'checked' : '')
if (lineIfExist && lineIfExist.querySelector('input').checked !== isChecked) {
lineIfExist.querySelector('input').checked = !lineIfExist.querySelector('input').checked
} else if (!lineIfExist) {
_private.el.insertAdjacentHTML('beforeend', newLine.innerHTML)
_private.bindSwitch('container-' + container.name)
}
}
}
_private.bindSwitch = function (container_id) {
var container = document.getElementById(container_id)
var label = container.querySelector('.state-switch')
var input = container.querySelector('input')
label.onclick = function () {
var name = this.getAttribute('for').replace(/state-/, '')
ipc.send('switch-state', {
name: name,
value: !input.checked
})
return false
}
}
_private.init = function (el) {
_private.el = el;
}
_private.init(element);
} | function RenderClass(element) {
var _private = this;
_private.el = null;
this.update = function (data) {
if (_private.el === null) { return; }
for (var container of data) {
newLine = document.getElementById('template').cloneNode(true);
newLine.innerHTML = newLine.innerHTML
.replace(/{{name}}/g, container.name)
.replace(/{{path}}/g, container.path)
.replace(/{{ischecked}}/g, container.state === 'Up' ? 'checked' : '')
if (document.getElementById('container-' + container.name)) {
var toDelete = document.getElementById('container-' + container.name)
toDelete.insertAdjacentHTML('afterend', newLine.innerHTML)
toDelete.parentElement.removeChild(toDelete)
} else {
_private.el.insertAdjacentHTML('afterend', newLine.innerHTML)
}
_private.bindSwitchs()
}
}
_private.bindSwitchs = function () {
var switchs = _private.el.querySelectorAll('#content .switch')
for (var state_switch of switchs) {
var label = state_switch.querySelector('.state-switch')
var input = state_switch.querySelector('input')
label.onclick = function () {
var name = label.getAttribute('for').replace(/state-/, '')
ipc.send('switch-state', {
name: name,
value: !input.checked
})
return false
}
}
}
_private.init = function (el) {
_private.el = el;
}
_private.init(element);
} |
Fix issue when a private match is found multiple times | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Processor functions
"""
def conflict_prefer_longer(matches):
"""
Remove shorter matches if they conflicts with longer ones
:param matches:
:type matches: rebulk.match.Matches
:param context:
:type context:
:return:
:rtype: list[rebulk.match.Match]
"""
to_remove_matches = set()
for match in filter(lambda match: not match.private, matches):
conflicting_matches = set()
for i in range(*match.span):
conflicting_matches.update(matches.starting(i))
conflicting_matches.update(matches.ending(i))
if conflicting_matches:
# keep the match only if it's the longest
for conflicting_match in filter(lambda match: not match.private, conflicting_matches):
if len(conflicting_match) < len(match):
to_remove_matches.add(conflicting_match)
for match in list(to_remove_matches):
matches.remove(match)
return matches
def remove_private(matches):
"""
Removes private matches.
:param matches:
:type matches:
:return:
:rtype:
"""
for match in list(matches):
if match.private:
matches.remove(match)
return matches
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Processor functions
"""
def conflict_prefer_longer(matches):
"""
Remove shorter matches if they conflicts with longer ones
:param matches:
:type matches: rebulk.match.Matches
:param context:
:type context:
:return:
:rtype: list[rebulk.match.Match]
"""
to_remove_matches = set()
for match in filter(lambda match: not match.private, matches):
conflicting_matches = set()
for i in range(*match.span):
conflicting_matches.update(matches.starting(i))
conflicting_matches.update(matches.ending(i))
if conflicting_matches:
# keep the match only if it's the longest
for conflicting_match in filter(lambda match: not match.private, conflicting_matches):
if len(conflicting_match) < len(match):
to_remove_matches.add(conflicting_match)
for match in list(to_remove_matches):
matches.remove(match)
return matches
def remove_private(matches):
"""
Removes private matches.
:param matches:
:type matches:
:return:
:rtype:
"""
to_remove_matches = set()
for match in matches:
if match.private:
to_remove_matches.add(match)
for match in list(to_remove_matches):
matches.remove(match)
return matches
|
Update repo URL for Jazzband ownership transfer | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-ical',
version='1.5',
description="iCal feeds for Django based on Django's syndication feed "
"framework.",
long_description=(open('README.rst').read() + '\n' +
open('CHANGES.rst').read()),
author='Ian Lewis',
author_email='[email protected]',
license='MIT License',
url='https://github.com/jazzband/django-ical',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Framework :: Django :: 1.10',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[
'Django>=1.8',
'icalendar>=4.0',
],
tests_require=[
'django-recurrence',
],
packages=find_packages(),
test_suite='tests.main',
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-ical',
version='1.5',
description="iCal feeds for Django based on Django's syndication feed "
"framework.",
long_description=(open('README.rst').read() + '\n' +
open('CHANGES.rst').read()),
author='Ian Lewis',
author_email='[email protected]',
license='MIT License',
url='https://github.com/Pinkerton/django-ical',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Framework :: Django :: 1.10',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[
'Django>=1.8',
'icalendar>=4.0',
],
tests_require=[
'django-recurrence',
],
packages=find_packages(),
test_suite='tests.main',
)
|
[FrameworkBundle][5.4] Remove fileLinkFormat property from DebugHandlersListener | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;
return static function (ContainerConfigurator $container) {
$container->parameters()->set('debug.error_handler.throw_at', -1);
$container->services()
->set('debug.debug_handlers_listener', DebugHandlersListener::class)
->args([
null, // Exception handler
service('monolog.logger.php')->nullOnInvalid(),
null, // Log levels map for enabled error levels
param('debug.error_handler.throw_at'),
param('kernel.debug'),
param('kernel.debug'),
service('monolog.logger.deprecation')->nullOnInvalid(),
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'php'])
->set('debug.file_link_formatter', FileLinkFormatter::class)
->args([param('debug.file_link_format')])
->alias(FileLinkFormatter::class, 'debug.file_link_formatter')
;
};
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;
return static function (ContainerConfigurator $container) {
$container->parameters()->set('debug.error_handler.throw_at', -1);
$container->services()
->set('debug.debug_handlers_listener', DebugHandlersListener::class)
->args([
null, // Exception handler
service('monolog.logger.php')->nullOnInvalid(),
null, // Log levels map for enabled error levels
param('debug.error_handler.throw_at'),
param('kernel.debug'),
service('debug.file_link_formatter'),
param('kernel.debug'),
service('monolog.logger.deprecation')->nullOnInvalid(),
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'php'])
->set('debug.file_link_formatter', FileLinkFormatter::class)
->args([param('debug.file_link_format')])
->alias(FileLinkFormatter::class, 'debug.file_link_formatter')
;
};
|
Change KAFKA_BROKER parameter, added a send producer | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer, KafkaProducer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.producer = KafkaProducer(bootstrap_servers=KAFKA_BROKER)
self.consumer = KafkaConsumer(group_id='tmdb',
bootstrap_servers=KAFKA_BROKER)
self.consumer.subscribe(pattern='omdb')
def run(self):
'''
Collects a message from the topic 'tmdb'. This message is a json containing all the
information collected from the apis further up the stream. We get the imdb_id from
this data and pass it to the tmdb api. We append the information from the tmdb_api
to the msg we collected, and then pass it to the next topic.
'''
for message in self.consumer:
# message value and key are raw bytes -- decode if necessary!
# e.g., for unicode: `message.value.decode('utf-8')
msg_data = json.loads(message.value)
imdb_id = msg_data['imdb_id']
tmdb_data = GetTMDB.get_info(imdb_id)
msg_data.extend(tmdb_data)
self.producer.send('tmdb', json.dumps(msg_data)) | import json
from get_tmdb import GetTMDB
from kafka import KafkaConsumer
try:
from GLOBALS import KAFKA_BROKER, TMDB_API
except ImportError:
print('Get it somewhere else')
class CollectTMDB(object):
def __init__(self, ):
self.tmdb = GetTMDB(TMDB_API)
self.consumer = KafkaConsumer(group_id='tmdb',
bootstrap_servers=['{}:9092'.format(KAFKA_BROKER)])
self.consumer.subscribe(pattern='tmdb')
def run(self):
'''
Collects a message from the topic 'tmdb'. This message is a json containing all the
information collected from the apis further up the stream. We get the imdb_id from
this data and pass it to the tmdb api. We append the information from the tmdb_api
to the msg we collected, and then pass it to the next topic.
'''
for message in self.consumer:
# message value and key are raw bytes -- decode if necessary!
# e.g., for unicode: `message.value.decode('utf-8')
msg_data = json.loads(message.value)
imdb_id = msg_data['imdb_id']
tmdb_data = GetTMDB.get_info(imdb_id)
msg_data.extend(tmdb_data) |
Make it work for node <= 5 | 'use strict';
var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
return callback();
}
var mainModule = null;
if (request.descriptionFilePath.endsWith('bower.json')) {
var source = request.descriptionFileData;
var modules = typeof source['main'] == 'string'
? [source['main']]
: source['main'];
mainModule = modules.find(module => { return module.endsWith('.js') });
}
if (! mainModule) {
return callback();
}
var obj = Object.assign({}, request, {
path: path.resolve(request.path, mainModule)
});
return resolver.doResolve('undescribed-raw-file', obj, 'using path: ' + mainModule, callback);
});
}
}
| var path = require('path');
module.exports = class BowerResolvePlugin {
constructor(options) {
this.options = options;
}
apply(resolver) {
resolver.plugin('existing-directory', function (request, callback) {
if (request.path !== request.descriptionFileRoot) {
return callback();
}
var mainModule = null;
if (request.descriptionFilePath.endsWith('bower.json')) {
var source = request.descriptionFileData;
var modules = typeof source['main'] == 'string'
? [source['main']]
: source['main'];
mainModule = modules.find(module => { return module.endsWith('.js') });
}
if (! mainModule) {
return callback();
}
var obj = Object.assign({}, request, {
path: path.resolve(request.path, mainModule)
});
return resolver.doResolve('undescribed-raw-file', obj, 'using path: ' + mainModule, callback);
});
}
} |
Use PHP5.3 safe syntax in rename_keys | <?php
/**
* @package Garp\Functional
* @author Harmen Janssen <[email protected]>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Rename keys in an array.
*
* @param mixed $transformMap
* @param mixed $collection
* @return array
*/
function rename_keys($transformMap, array $collection = null) {
if (!is_callable($transformMap) && !is_array($transformMap)) {
throw new \InvalidArgumentException(
'rename_keys expects argument 1 to be an array or a function'
);
}
$transformer = function ($collection) use ($transformMap) {
return reduce(
function ($acc, $cur) use ($transformMap, $collection) {
$prop = is_callable($transformMap)
? $transformMap($cur)
: prop($cur, $transformMap);
return prop_set(
$prop ?: $cur,
$collection[$cur],
$acc
);
},
array(),
keys($collection)
);
};
return func_num_args() < 2 ? $transformer : $transformer($collection);
}
| <?php
/**
* @package Garp\Functional
* @author Harmen Janssen <[email protected]>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
namespace Garp\Functional;
/**
* Rename keys in an array.
*
* @param mixed $transformMap
* @param mixed $collection
* @return array
*/
function rename_keys($transformMap, array $collection = null) {
if (!is_callable($transformMap) && !is_array($transformMap)) {
throw new \InvalidArgumentException(
'rename_keys expects argument 1 to be an array or a function'
);
}
$transformer = function ($collection) use ($transformMap) {
return reduce(
function ($acc, $cur) use ($transformMap, $collection) {
$prop = is_callable($transformMap)
? $transformMap($cur)
: prop($cur, $transformMap);
return prop_set(
$prop ?: $cur,
$collection[$cur],
$acc
);
},
[],
keys($collection)
);
};
return func_num_args() < 2 ? $transformer : $transformer($collection);
}
|
Update test results using new return type | """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
'12.345678',
)
self.assertEqual(
degree_decimal_str_transform('123456'),
'0.123456',
)
| """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
12.345678,
)
self.assertEqual(
degree_decimal_str_transform('123456'),
0.123456,
)
|
Replace api key with env vars | module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CHOCOLATE_FREE_CF_SPACE,
accessToken: process.env.CHOCOLATE_FREE_CF_TOKEN
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: 'UA-89281107-1',
},
},
{
resolve: 'gatsby-plugin-sitemap'
},
{
resolve: 'gatsby-plugin-manifest',
options: {
'name': 'Chocolate-free',
'short_name': 'ChocoFree',
'start_url': '/',
'background_color': '#e8e8e8',
'icons': [
{
'src': '/android-chrome-192x192.png',
'sizes': '192x192',
'type': 'image/png'
},
{
'src': '/android-chrome-512x512.png',
'sizes': '512x512',
'type': 'image/png'
}
],
'theme_color': '#e8e8e8',
'display': 'standalone'
}
},
'gatsby-plugin-offline',
'gatsby-transformer-remark',
'gatsby-plugin-sass'
],
}
| module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: '0w6gaytm0wfv',
accessToken: 'c9414fe612e8c31f402182354c5263f9c6b1f0c611ae5597585cb78692dc2493',
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: 'UA-89281107-1',
},
},
{
resolve: 'gatsby-plugin-sitemap'
},
{
resolve: 'gatsby-plugin-manifest',
options: {
'name': 'Chocolate-free',
'short_name': 'ChocoFree',
'start_url': '/',
'background_color': '#e8e8e8',
'icons': [
{
'src': '/android-chrome-192x192.png',
'sizes': '192x192',
'type': 'image/png'
},
{
'src': '/android-chrome-512x512.png',
'sizes': '512x512',
'type': 'image/png'
}
],
'theme_color': '#e8e8e8',
'display': 'standalone'
}
},
'gatsby-plugin-offline',
'gatsby-transformer-remark',
'gatsby-plugin-sass'
],
}
|
Add a representation of GraphView object | from octopus.dispatcher.model import TaskNode, FolderNode, TaskGroup
from octopus.dispatcher import rules
import logging
logger = logging.getLogger("dispatcher")
class RuleError(rules.RuleError):
'''Base class for GraphViewBuilder related exceptions.'''
pass
class TaskNodeHasNoChildrenError(RuleError):
'''Raised when a GraphViewBuilder is requested to add a child node
to a FolderNode.
'''
class GraphViewBuilder(object):
def __init__(self, dispatchTree, root):
self.dispatchTree = dispatchTree
self.root = root
def apply(self, task):
id = None
name = task.name
parent = task.parent.nodes['graph_rule'] if task.parent else self.root
user = task.user
priority = task.priority
dispatchKey = task.dispatchKey
maxRN = task.maxRN
if isinstance(task, TaskGroup):
strategy = task.strategy
node = FolderNode(id, name, parent, user, priority, dispatchKey, maxRN,
strategy, taskGroup=task)
else:
node = TaskNode(None, name, parent, user, priority, dispatchKey, maxRN, task)
task.nodes['graph_rule'] = node
return [node]
def processDependencies(self, dependencies):
for task, taskdeps in dependencies.items():
node = task.nodes['graph_rule']
for deptask, statuslist in taskdeps.items():
depnode = deptask.nodes['graph_rule']
node.addDependency(depnode, statuslist)
def __repr__(self):
return "GraphViewBuilder( root=%r, dispatchTree=%r )" % (self.root, self.dispatchTree ) | from octopus.dispatcher.model import TaskNode, FolderNode, TaskGroup
from octopus.dispatcher import rules
import logging
logger = logging.getLogger("dispatcher")
class RuleError(rules.RuleError):
'''Base class for GraphViewBuilder related exceptions.'''
pass
class TaskNodeHasNoChildrenError(RuleError):
'''Raised when a GraphViewBuilder is requested to add a child node
to a FolderNode.
'''
class GraphViewBuilder(object):
def __init__(self, dispatchTree, root):
self.dispatchTree = dispatchTree
self.root = root
def apply(self, task):
id = None
name = task.name
parent = task.parent.nodes['graph_rule'] if task.parent else self.root
user = task.user
priority = task.priority
dispatchKey = task.dispatchKey
maxRN = task.maxRN
if isinstance(task, TaskGroup):
strategy = task.strategy
node = FolderNode(id, name, parent, user, priority, dispatchKey, maxRN,
strategy, taskGroup=task)
else:
node = TaskNode(None, name, parent, user, priority, dispatchKey, maxRN, task)
task.nodes['graph_rule'] = node
return [node]
def processDependencies(self, dependencies):
for task, taskdeps in dependencies.items():
node = task.nodes['graph_rule']
for deptask, statuslist in taskdeps.items():
depnode = deptask.nodes['graph_rule']
node.addDependency(depnode, statuslist)
|
Update the function header declaration
So that it looks not that horrible. | function c_a(a, b) {
"use strict";
var c, d, obj;
obj = {
"difference": [],
"same_elements": []
};
function trim(a) {
var i = a.length;
while (i >= 0) {
if (a[i] === "_*deleted*_") {
a.splice(i, 1);
}
i -= 1;
}
return a;
}
function process_it(k, l) {
var same = [];
l.forEach(function (v, i) {
k.forEach(function (vv, ii) {
if (v === vv) {
same.push(vv);
l.splice(i, 1, "_*deleted*_");
k.splice(ii, 1, "_*deleted*_");
}
});
});
return {
"difference": trim(l.concat(k)),
"same_elements": same
};
}
if (a instanceof Array && b instanceof Array) {
c = a.slice();
d = b.slice();
if (c.length >= d.length) {
obj = process_it(c, d);
} else {
obj = process_it(d, c);
}
}
return obj;
};
| var c_a = function (a, b) {
"use strict";
var c, d, obj;
obj = {
"difference": [],
"same_elements": []
};
function trim(a) {
var i = a.length;
while (i >= 0) {
if (a[i] === "_*deleted*_") {
a.splice(i, 1);
}
i -= 1;
}
return a;
}
function process_it(k, l) {
var same = [];
l.forEach(function (v, i) {
k.forEach(function (vv, ii) {
if (v === vv) {
same.push(vv);
l.splice(i, 1, "_*deleted*_");
k.splice(ii, 1, "_*deleted*_");
}
});
});
return {
"difference": trim(l.concat(k)),
"same_elements": same
};
}
if (a instanceof Array && b instanceof Array) {
c = a.slice();
d = b.slice();
if (c.length >= d.length) {
obj = process_it(c, d);
} else {
obj = process_it(d, c);
}
}
return obj;
};
|
Fix URL trailing slash bug in teams endpoint | """Defines the URL routes for the Team API."""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
TeamsListView,
TeamsDetailView,
TopicDetailView,
TopicListView,
MembershipListView,
MembershipDetailView
)
TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)'
USERNAME_PATTERN = r'(?P<username>[\w.+-]+)'
TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id')
urlpatterns = patterns(
'',
url(
r'^v0/teams/$',
TeamsListView.as_view(),
name="teams_list"
),
url(
r'^v0/teams/' + TEAM_ID_PATTERN + '$',
TeamsDetailView.as_view(),
name="teams_detail"
),
url(
r'^v0/topics/$',
TopicListView.as_view(),
name="topics_list"
),
url(
r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$',
TopicDetailView.as_view(),
name="topics_detail"
),
url(
r'^v0/team_membership$',
MembershipListView.as_view(),
name="team_membership_list"
),
url(
r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$',
MembershipDetailView.as_view(),
name="team_membership_detail"
)
)
| """Defines the URL routes for the Team API."""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
TeamsListView,
TeamsDetailView,
TopicDetailView,
TopicListView,
MembershipListView,
MembershipDetailView
)
TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)'
USERNAME_PATTERN = r'(?P<username>[\w.+-]+)'
TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id')
urlpatterns = patterns(
'',
url(
r'^v0/teams$',
TeamsListView.as_view(),
name="teams_list"
),
url(
r'^v0/teams/' + TEAM_ID_PATTERN + '$',
TeamsDetailView.as_view(),
name="teams_detail"
),
url(
r'^v0/topics/$',
TopicListView.as_view(),
name="topics_list"
),
url(
r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$',
TopicDetailView.as_view(),
name="topics_detail"
),
url(
r'^v0/team_membership$',
MembershipListView.as_view(),
name="team_membership_list"
),
url(
r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$',
MembershipDetailView.as_view(),
name="team_membership_detail"
)
)
|
Fix get gpg key from database | from glob import glob
import os
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = create_gpg(gpg_bin, path, passphrase)
return Database(path, gpg)
@classmethod
def from_path(cls, path, gpg_bin="gpg"):
gpg = load_gpg(binary=gpg_bin, database_path=path)
return Database(path, gpg)
@property
def gpg_key(self):
return self.gpg.list_keys(secret=True)[0]["fingerprint"]
def add(self, credential):
encrypted_password = self.gpg.encrypt(
credential.password,
self.gpg_key
)
credential.password = str(encrypted_password)
credential.save(database_path=self.path)
def credential(self, name):
credential_path = os.path.join(self.path, name)
credential = Credential.from_path(credential_path)
return credential
@property
def credentials(self):
return [self.credential(os.path.basename(c))
for c in glob(self.path + "/**")]
| from glob import glob
import os
from .credential import Credential
from .crypt import create_gpg, load_gpg
class Database(object):
def __init__(self, path, gpg):
self.path = path
self.gpg = gpg
@classmethod
def create(cls, path, passphrase, gpg_bin="gpg"):
gpg = create_gpg(gpg_bin, path, passphrase)
return Database(path, gpg)
@classmethod
def from_path(cls, path, gpg_bin="gpg"):
gpg = load_gpg(binary=gpg_bin, database_path=path)
return Database(path, gpg)
@property
def gpg_key(self, secret=False):
return self.gpg.list_keys(secret=secret)[0]
def add(self, credential):
encrypted_password = self.gpg.encrypt(
credential.password,
self.gpg_key
)
credential.password = str(encrypted_password)
credential.save(database_path=self.path)
def credential(self, name):
credential_path = os.path.join(self.path, name)
credential = Credential.from_path(credential_path)
return credential
@property
def credentials(self):
return [self.credential(os.path.basename(c))
for c in glob(self.path + "/**")]
|
Load box2d library in JNI | package org.cocos2dx.breakout;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.os.Bundle;
import android.widget.EditText;
public class BreakoutCocos2Dx extends Cocos2dxActivity{
private Cocos2dxGLSurfaceView mGLView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// get the packageName,it's used to set the resource path
String packageName = getApplication().getPackageName();
super.setPackageName(packageName);
setContentView(R.layout.game_demo);
mGLView = (Cocos2dxGLSurfaceView) findViewById(R.id.game_gl_surfaceview);
mGLView.setTextField((EditText)findViewById(R.id.textField));
// Get the size of the mGLView after the layout happens
mGLView.post(new Runnable() {
@Override
public void run() {
Cocos2dxActivity.screenHeight = mGLView.getHeight();
Cocos2dxActivity.screenWidth = mGLView.getWidth();
}
});
}
@Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
static {
System.loadLibrary("box2d");
System.loadLibrary("cocos2d");
System.loadLibrary("cocosdenshion");
System.loadLibrary("game");
}
}
| package org.cocos2dx.breakout;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.os.Bundle;
import android.widget.EditText;
public class BreakoutCocos2Dx extends Cocos2dxActivity{
private Cocos2dxGLSurfaceView mGLView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// get the packageName,it's used to set the resource path
String packageName = getApplication().getPackageName();
super.setPackageName(packageName);
setContentView(R.layout.game_demo);
mGLView = (Cocos2dxGLSurfaceView) findViewById(R.id.game_gl_surfaceview);
mGLView.setTextField((EditText)findViewById(R.id.textField));
// Get the size of the mGLView after the layout happens
mGLView.post(new Runnable() {
@Override
public void run() {
Cocos2dxActivity.screenHeight = mGLView.getHeight();
Cocos2dxActivity.screenWidth = mGLView.getWidth();
}
});
}
@Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
static {
System.loadLibrary("cocos2d");
System.loadLibrary("cocosdenshion");
System.loadLibrary("game");
}
}
|
Fix error when no content-length is sent. | export default class FileLoader {
// This returns ArrayBuffer
static load (url, on_progress = () => {
}) {
return new Promise((resolve, reject) => {
fetch(url).then(async (response) => {
// Handle HTTP error
if (response.status === 404) {
reject('NOT_FOUND')
} else if (response.status !== 200) {
reject('HTTP_ERROR')
}
// For length calculation
const length = +response.headers.get('Content-Length')
const chunks = []
let received = 0
// Read incoming chunk
const reader = response.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
chunks.push(value)
received += value.length
// Progress event handler
on_progress(received / length)
}
// Loaded, reassemble file
const file = new Uint8Array(received)
let offset = 0
for (let chunk of chunks) {
file.set(chunk, offset)
offset += chunk.length
}
// Resolve promise to the file content array buffer
resolve(file.buffer)
}).catch(() => {
reject('NETWORK_ERROR')
})
})
}
// Utility to decode ArrayBuffer to text
static decode (buffer) {
const decoder = new TextDecoder('utf8')
return decoder.decode(buffer)
}
}
| export default class FileLoader {
// This returns ArrayBuffer
static load (url, on_progress = () => {
}) {
return new Promise((resolve, reject) => {
fetch(url).then(async (response) => {
// Handle HTTP error
if (response.status === 404) {
reject('NOT_FOUND')
} else if (response.status !== 200) {
reject('HTTP_ERROR')
}
// For length calculation
const length = +response.headers.get('Content-Length')
const chunks = []
let received = 0
// Read incoming chunk
const reader = response.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
chunks.push(value)
received += value.length
// Progress event handler
on_progress(received / length)
}
// Loaded, reassemble file
const file = new Uint8Array(length)
let offset = 0
for (let chunk of chunks) {
file.set(chunk, offset)
offset += chunk.length
}
// Resolve promise to the file content array buffer
resolve(file.buffer)
}).catch(() => {
reject('NETWORK_ERROR')
})
})
}
// Utility to decode ArrayBuffer to text
static decode (buffer) {
const decoder = new TextDecoder('utf8')
return decoder.decode(buffer)
}
}
|
Add prefixes for Android >= 4.0 | const options = require('./options');
const autoprefixer = require('autoprefixer');
module.exports = {
resolve: {
modules: [
options.paths.root,
options.paths.resolve('node_modules')
],
alias: {
src: 'src',
directives: 'src/directives',
helpers: 'src/helpers',
mixins: 'src/mixins',
styles: 'src/styles',
vue$: 'vue/dist/vue.common.js'
},
extensions: ['.js', '.json', '.vue', '.scss']
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// configured in the script specific webpack configs
},
postcss: [
autoprefixer({
browsers: ['last 2 versions', 'ie > 9', 'Firefox ESR', 'android >= 4.0']
})
]
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
// Stats is used to customize Webpack's console output
// https://webpack.js.org/configuration/stats/
stats: {
hash: false,
colors: true,
chunks: false,
version: false,
children: false,
timings: true
}
};
| const options = require('./options');
const autoprefixer = require('autoprefixer');
module.exports = {
resolve: {
modules: [
options.paths.root,
options.paths.resolve('node_modules')
],
alias: {
src: 'src',
directives: 'src/directives',
helpers: 'src/helpers',
mixins: 'src/mixins',
styles: 'src/styles',
vue$: 'vue/dist/vue.common.js'
},
extensions: ['.js', '.json', '.vue', '.scss']
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// configured in the script specific webpack configs
},
postcss: [
autoprefixer({
browsers: ['last 2 versions', 'ie > 9', 'Firefox ESR']
})
]
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
// Stats is used to customize Webpack's console output
// https://webpack.js.org/configuration/stats/
stats: {
hash: false,
colors: true,
chunks: false,
version: false,
children: false,
timings: true
}
};
|
Make sure we're sorting results | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
| import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = list(listMetrics(self.rootdir))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = list(listMetrics(self.rootdir + '/'))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
|
Use application sourceLanguage in default migrate | <?php
use yii\db\Migration;
use lav45\translate\LocaleHelperTrait;
class m151220_112320_lang extends Migration
{
use LocaleHelperTrait;
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%lang}}', [
'id' => $this->string(2)->notNull(),
'locale' => $this->string(8)->notNull(),
'name' => $this->string(32)->notNull(),
'status' => $this->smallInteger(),
'PRIMARY KEY (id)',
], $tableOptions);
$this->createIndex('lang_name_idx', 'lang', 'name', true);
$this->createIndex('lang_status_idx', 'lang', 'status');
$source_language = Yii::$app->sourceLanguage;
$source_language_id = $this->getPrimaryLanguage($source_language);
$this->insert('{{%lang}}', [
'id' => strtolower($source_language_id),
'locale' => $source_language,
'name' => strtoupper($source_language_id),
'status' => 10,
]);
}
public function safeDown()
{
$this->dropTable('{{%lang}}');
}
}
| <?php
use yii\db\Migration;
class m151220_112320_lang extends Migration
{
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%lang}}', [
'id' => $this->string(2)->notNull(),
'locale' => $this->string(8)->notNull(),
'name' => $this->string(32)->notNull(),
'status' => $this->smallInteger(),
'PRIMARY KEY (id)',
], $tableOptions);
$this->createIndex('lang_name_idx', 'lang', 'name', true);
$this->createIndex('lang_status_idx', 'lang', 'status');
$this->insert('lang', [
'id' => 'en',
'locale' => 'en-US',
'name' => 'ENG',
'status' => 10,
]);
}
public function safeDown()
{
$this->dropTable('lang');
}
}
|
Make the party set JS generator output keys in a predictable order
This makes it easier to check with "git diff" if there have been any
changes. | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_root = realpath(join(dirname(__file__), '..', '..', '..'))
output_filename = join(
repo_root,
'elections',
settings.ELECTION_APP,
'static',
'js',
'post-to-party-set.js',
)
with open(output_filename, 'w') as f:
f.write('var postIDToPartySet = ')
mapping = {
post['id']: AREA_POST_DATA.post_id_to_party_set(post['id'])
for election, election_data in settings.ELECTIONS_CURRENT
for post in get_all_posts(election_data['for_post_role'])
}
unknown_post_ids = [
k for k, v in mapping.items()
if v is None
]
f.write(json.dumps(mapping, sort_keys=True))
f.write(';\n')
if unknown_post_ids:
print "Warning: no party set could be found for these post IDs:"
print unknown_post_ids
| import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_root = realpath(join(dirname(__file__), '..', '..', '..'))
output_filename = join(
repo_root,
'elections',
settings.ELECTION_APP,
'static',
'js',
'post-to-party-set.js',
)
with open(output_filename, 'w') as f:
f.write('var postIDToPartySet = ')
mapping = {
post['id']: AREA_POST_DATA.post_id_to_party_set(post['id'])
for election, election_data in settings.ELECTIONS_CURRENT
for post in get_all_posts(election_data['for_post_role'])
}
unknown_post_ids = [
k for k, v in mapping.items()
if v is None
]
f.write(json.dumps(mapping))
f.write(';\n')
if unknown_post_ids:
print "Warning: no party set could be found for these post IDs:"
print unknown_post_ids
|
Change to form handling now persists realtionship between associations | <?php
namespace Test\TestTwoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;
use Test\TestStoreBundle\Entity\User;
use Test\TestStoreBundle\Entity\Address;
use Test\TestStoreBundle\Entity\Personal;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$all = new All();
$all->getUser()->add(new User());
$all->getAddress()->add(new Address());
$all->getPersonal()->add(new Personal());
// Create Form
$form = $this->createForm(new AllType(), $all);
$form->handleRequest($request);
if ($form->isValid()) {
$all->getUser()->first()->setPersonal($all->getPersonal()->first());
$all->getUser()->first()->setAddress($all->getAddress()->first());
$all->getAddress()->first()->setUser($all->getUser()->first());
$all->getPersonal()->first()->setUser($all->getUser()->first());
// Persist submitted info to Database
$em = $this->getDoctrine()->getManager();
$em->persist($all->getUser()->first());
$em->persist($all->getAddress()->first());
$em->persist($all->getPersonal()->first());
$em->flush();
return new Response('Well done, it worked!');
}
return $this->render('TestTestTwoBundle:Default:index.html.twig', array('form' => $form->createView()));
}
}
| <?php
namespace Test\TestTwoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;
use Test\TestStoreBundle\Entity\User;
use Test\TestStoreBundle\Entity\Address;
use Test\TestStoreBundle\Entity\Personal;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$all = new All();
$all->getUser()->add(new User());
$all->getAddress()->add(new Address());
$all->getPersonal()->add(new Personal());
// Create Form
$form = $this->createForm(new AllType(), $all);
$form->handleRequest($request);
if ($form->isValid()) {
// Persist submitted info to Database
$em = $this->getDoctrine()->getManager();
$em->persist($all->getUser()->first());
$em->persist($all->getAddress()->first());
$em->persist($all->getPersonal()->first());
$em->flush();
return new Response('Well done, it worked!');
}
return $this->render('TestTestTwoBundle:Default:index.html.twig', array('form' => $form->createView()));
}
}
|
Fix after parameter for reddit api | 'use strict';
angular.module('repicbro.services')
.factory('PostsManager', function ($rootScope, Posts) {
var posts = [],
current = null,
index = 0,
latest = '',
updating = false;
var broadcastCurrentUpdate = function (current) {
$rootScope.$broadcast('PostsManager.CurrentUpdate', current);
};
var next = function () {
console.log('next');
checkSize();
current = posts[++index];
broadcastCurrentUpdate(current);
};
var prev = function () {
console.log('prev');
current = posts[--index];
broadcastCurrentUpdate(current);
};
var checkSize = function () {
if (posts.length - index < 50 && !updating) {
getPosts();
}
};
var getPosts = function () {
console.log('Get posts');
updating = true;
Posts.get('funny', latest, function (data) {
angular.forEach(data.data.children, function (p) {
posts.push(p.data);
});
current = posts[index];
latest = posts.slice(-1)[0].name;
broadcastCurrentUpdate(current);
updating = false;
});
};
getPosts();
return {
posts: posts,
current: current,
next: next,
prev: prev
};
});
| 'use strict';
angular.module('repicbro.services')
.factory('PostsManager', function ($rootScope, Posts) {
var posts = [],
current = null,
index = 0,
latest = '',
updating = false;
var broadcastCurrentUpdate = function (current) {
$rootScope.$broadcast('PostsManager.CurrentUpdate', current);
};
var next = function () {
console.log('next');
checkSize();
current = posts[++index];
broadcastCurrentUpdate(current);
};
var prev = function () {
console.log('prev');
current = posts[--index];
broadcastCurrentUpdate(current);
};
var checkSize = function () {
if (posts.length - index < 50 && !updating) {
getPosts();
}
};
var getPosts = function () {
console.log('Get posts');
updating = true;
Posts.get('funny', latest, function (data) {
latest = data.data.name;
angular.forEach(data.data.children, function (p) {
posts.push(p.data);
});
current = posts[index];
broadcastCurrentUpdate(current);
updating = false;
});
};
getPosts();
return {
posts: posts,
current: current,
next: next,
prev: prev
};
});
|
Move extension requirement logic into PHPUnit phpDoc annotation | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Db\Adapter\Driver\Pgsql;
use Zend\Db\Adapter\Driver\Pgsql\Connection;
use Zend\Db\Adapter\Exception as AdapterException;
class ConnectionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Connection
*/
protected $connection = null;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->connection = new Connection();
}
/**
* Test getResource method if it tries to connect to the database.
*
* @covers Zend\Db\Adapter\Driver\Pgsql\Connection::getResource
* @requires extension pgsql
*/
public function testResource()
{
try {
$resource = $this->connection->getResource();
// connected with empty string
$this->assertTrue(is_resource($resource));
} catch (AdapterException\RuntimeException $exc) {
// If it throws an exception it has failed to connect
$this->setExpectedException('Zend\Db\Adapter\Exception\RuntimeException');
throw $exc;
}
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Db\Adapter\Driver\Pgsql;
use Zend\Db\Adapter\Driver\Pgsql\Connection;
use Zend\Db\Adapter\Exception as AdapterException;
class ConnectionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Connection
*/
protected $connection = null;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->connection = new Connection();
}
/**
* Test getResource method if it tries to connect to the database.
*
* @covers Zend\Db\Adapter\Driver\Pgsql\Connection::getResource
*/
public function testResource()
{
if (extension_loaded('pgsql')) {
try {
$resource = $this->connection->getResource();
// connected with empty string
$this->assertTrue(is_resource($resource));
} catch (AdapterException\RuntimeException $exc) {
// If it throws an exception it has failed to connect
$this->setExpectedException('Zend\Db\Adapter\Exception\RuntimeException');
throw $exc;
}
} else {
$this->markTestSkipped('pgsql extension not loaded');
}
}
}
|
Fix for spaces in user queries | <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = 10)
{
// The API will throw a 400 response if you include properly encoded spaces,
// but underscores work as a substitute.
$query = str_replace(' ', '_', $query);
$offset = 0;
while (true) {
$response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);
if ($response->total_record_count == 0) {
break;
}
foreach ($response->user as $data) {
// Contacts without a primary identifier will have the primary_id
// field populated with something weird like "no primary id (123456789023)".
// We ignore those.
// See: https://github.com/scriptotek/php-alma-client/issues/6
if (strpos($data->primary_id, 'no primary id') === 0) {
continue;
}
$user = User::fromResponse($this->client, $data);
if ($full) {
$user->fetch();
}
yield $user;
$offset++;
}
if ($offset >= $response->total_record_count) {
break;
}
}
}
}
| <?php
namespace Scriptotek\Alma\Users;
use Scriptotek\Alma\ResourceList;
class Users extends ResourceList
{
protected $resourceName = User::class;
/**
* Iterates over all users matching the given query.
* Handles continuation.
*/
public function search($query, $full = false, $batchSize = 10)
{
$offset = 0;
while (true) {
$response = $this->client->getJSON('/users', ['q' => $query, 'limit' => $batchSize, 'offset' => $offset]);
if ($response->total_record_count == 0) {
break;
}
foreach ($response->user as $data) {
if (strpos($data->primary_id, 'no primary id') === 0) {
continue;
}
$user = User::fromResponse($this->client, $data);
if ($full) {
$user->fetch();
}
yield $user;
$offset++;
}
if ($offset >= $response->total_record_count) {
break;
}
}
}
}
|
Add views in Pynuts init | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with database data
.. seealso::
`Flask Application <http://flask.pocoo.org/docs/api/>`_
"""
def __init__(self, import_name, config=None, reflect=False,
*args, **kwargs):
super(Pynuts, self).__init__(import_name, *args, **kwargs)
self.config.update(config or {})
self.db = SQLAlchemy(self)
self.documents = {}
self.views = {}
if reflect:
self.db.metadata.reflect(bind=self.db.get_engine(self))
class Document(document.Document):
"""Document base class of the application."""
_pynuts = self
self.Document = Document
class ModelView(view.ModelView):
"""Model view base class of the application."""
_pynuts = self
self.ModelView = ModelView
def render_rest(self, document_type, part='index.rst.jinja2',
**kwargs):
return self.documents[document_type].generate_rest(part, **kwargs)
| """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with database data
.. seealso::
`Flask Application <http://flask.pocoo.org/docs/api/>`_
"""
def __init__(self, import_name, config=None, reflect=False,
*args, **kwargs):
super(Pynuts, self).__init__(import_name, *args, **kwargs)
self.config.update(config or {})
self.db = SQLAlchemy(self)
self.documents = {}
if reflect:
self.db.metadata.reflect(bind=self.db.get_engine(self))
class Document(document.Document):
"""Document base class of the application."""
_pynuts = self
self.Document = Document
class ModelView(view.ModelView):
"""Model view base class of the application."""
_pynuts = self
self.ModelView = ModelView
def render_rest(self, document_type, part='index.rst.jinja2',
**kwargs):
return self.documents[document_type].generate_rest(part, **kwargs)
|
Deploy Travis CI build 720 to GitHub | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "<placeholder>"
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'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',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
| #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "<file not found>"
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'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',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
|
Make form update existing instance if uid matches | from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
if 'instance' not in kwargs or kwargs['instance'] is None:
# Note: currently assumes instance is always passed as a kwarg
# - need to check but this is probably bad
try:
kwargs['instance'] = VendOutlet.objects.get(uid=uid)
except VendOutlet.DoesNotExist:
pass
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
| from django import forms
from django_vend.core.forms import VendDateTimeField
from .models import VendOutlet
class VendOutletForm(forms.ModelForm):
deleted_at = VendDateTimeField(required=False)
def __init__(self, data=None, *args, **kwargs):
if data:
uid = data.pop('id', None)
if uid is not None:
data['uid'] = uid
tax_inc = data.pop('display_prices', None)
if tax_inc is not None:
if tax_inc == 'inclusive':
data['display_prices_tax_inclusive'] = True
elif tax_inc == 'exclusive':
data['display_prices_tax_inclusive'] = False
deleted_at = data.get('deleted_at')
if deleted_at is not None and deleted_at == 'null':
data['deleted_at'] = None
super(VendOutletForm, self).__init__(data, *args, **kwargs)
class Meta:
model = VendOutlet
fields = ['uid', 'name', 'time_zone', 'currency', 'currency_symbol',
'display_prices_tax_inclusive', 'deleted_at']
|
Revert "Revert "Make migration SQLite compatible""
This reverts commit b16016994f20945a8a2bbb63b9cb920d856ab66f. | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
|
Make the clusters member final | package me.prettyprint.cassandra.service;
import java.util.HashMap;
import java.util.Map;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
public class ClusterFactory {
private static final Map<String, Cluster> clusters = new HashMap<String, Cluster>();
public static Cluster get(String clusterName) {
return clusters.get(clusterName);
}
/**
*
* @param clusterName The cluster name. This is an identifying string for the cluster, e.g.
* "production" or "test" etc. Clusters will be created on demand per each unique clusterName key.
* @param hostIp host:ip format string
* @return
*/
public static Cluster getOrCreate(String clusterName, String hostIp) {
/*
I would like to move off of string literals for hosts, perhaps
providing them for convinience, and used specific types
*/
return getOrCreate(clusterName, new CassandraHostConfigurator(hostIp));
}
public static Cluster getOrCreate(String clusterName,
CassandraHostConfigurator cassandraHostConfigurator) {
Cluster c = clusters.get(clusterName);
if (c == null) {
synchronized (clusters) {
c = clusters.get(clusterName);
if (c == null) {
c = create(clusterName, cassandraHostConfigurator);
clusters.put(clusterName, c);
}
}
}
return c;
}
public static Cluster create(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) {
return new ClusterImpl(clusterName, cassandraHostConfigurator);
}
}
| package me.prettyprint.cassandra.service;
import java.util.HashMap;
import java.util.Map;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
public class ClusterFactory {
private static Map<String, Cluster> clusters = new HashMap<String, Cluster>();
public static Cluster get(String clusterName) {
return clusters.get(clusterName);
}
/**
*
* @param clusterName The cluster name. This is an identifying string for the cluster, e.g.
* "production" or "test" etc. Clusters will be created on demand per each unique clusterName key.
* @param hostIp host:ip format string
* @return
*/
public static Cluster getOrCreate(String clusterName, String hostIp) {
/*
I would like to move off of string literals for hosts, perhaps
providing them for convinience, and used specific types
*/
return getOrCreate(clusterName, new CassandraHostConfigurator(hostIp));
}
public static Cluster getOrCreate(String clusterName,
CassandraHostConfigurator cassandraHostConfigurator) {
Cluster c = clusters.get(clusterName);
if (c == null) {
synchronized (clusters) {
c = clusters.get(clusterName);
if (c == null) {
c = create(clusterName, cassandraHostConfigurator);
clusters.put(clusterName, c);
}
}
}
return c;
}
public static Cluster create(String clusterName, CassandraHostConfigurator cassandraHostConfigurator) {
return new ClusterImpl(clusterName, cassandraHostConfigurator);
}
}
|
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file. | """
Spamhaus XBL list handler.
Maintainer: Sauli Pahlman <[email protected]>
"""
import idiokit
from abusehelper.core import cymruwhois, bot, events
class SpamhausXblBot(bot.PollingBot):
xbl_filepath = bot.Param("Filename of Spamhaus XBL file")
@idiokit.stream
def poll(self):
skip_chars = ["#", ":", "$"]
self.log.info("Opening %s" % self.xbl_filepath)
try:
with open(self.xbl_filepath, "r") as f:
for line in f:
line = line.strip()
if line and line[0] in skip_chars:
continue
event = events.Event()
event.add("ip", line)
event.add("description url", "http://www.spamhaus.org/query/bl?ip=" + line)
yield idiokit.send(event)
except IOError, ioe:
self.log.error("Could not open %s: %s" % (self.xbl_filepath, ioe))
if __name__ == "__main__":
SpamhausXblBot.from_command_line().execute()
| """
Spamhaus XBL list handler.
Maintainer: Sauli Pahlman <[email protected]>
"""
import idiokit
from abusehelper.core import cymruwhois, bot, events
class SpamhausXblBot(bot.PollingBot):
xbl_filepath = bot.Param("Filename of Spamhaus XBL file")
@idiokit.stream
def poll(self):
skip_chars = ["#", ":", "$"]
self.log.info("Opening %s" % self.xbl_filepath)
entries = []
try:
with open(self.xbl_filepath, "r") as f:
for line in f:
line = line.strip()
if line and line[0] in skip_chars:
continue
entries.append(line)
self.log.info("Read %d entries" % len(entries))
except IOError, ioe:
self.log.error("Could not open %s: %s" % (self.xbl_filepath, ioe))
for entry in entries:
event = events.Event()
event.add("ip", entry)
event.add("description url", "http://www.spamhaus.org/query/bl?ip=" + entry)
yield idiokit.send(event)
if __name__ == "__main__":
SpamhausXblBot.from_command_line().execute()
|
Use git diff instead of git diff-index | import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec('git diff', {cwd: dependencyPath});
if (!diff.trim()) { continue; }
process.stdout.write(`Committing 'vinsonchuong/${dependencyName}'\n`);
process.stdout.write(diff + '\n');
await exec(
`git config user.email '[email protected]'`,
{cwd: dependencyPath}
);
await exec(
`git config user.name 'Vinson Chuong'`,
{cwd: dependencyPath}
);
await exec(
[
'git commit',
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
| import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
process.stdout.write(diff + '\n');
process.stdout.write(`Committing 'vinsonchuong/${dependencyName}'\n`);
await exec(
`git config user.email '[email protected]'`,
{cwd: dependencyPath}
);
await exec(
`git config user.name 'Vinson Chuong'`,
{cwd: dependencyPath}
);
await exec(
[
'git commit',
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
|
Print rancher-compose command to help debug/confirmation | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Set Required fields for rancher-compose to work
# Should raise an error if they are not declared
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
try:
rancher_compose_command = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", "-d", "--force-upgrade",
]
if services:
rancher_compose_command.append(services)
print(' '.join(rancher_compose_command)
subprocess.check_call(rancher_compose_command)
finally:
# Unset environmental variables, no point in them hanging about
del os.environ['RANCHER_URL']
del os.environ['RANCHER_ACCESS_KEY']
del os.environ['RANCHER_SECRET_KEY']
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Set Required fields for rancher-compose to work
# Should raise an error if they are not declared
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
try:
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", "-d",
]
if services:
rc_args.append(services)
subprocess.check_call(rc_args)
finally:
# Unset environmental variables, no point in them hanging about
del os.environ['RANCHER_URL']
del os.environ['RANCHER_ACCESS_KEY']
del os.environ['RANCHER_SECRET_KEY']
if __name__ == "__main__":
main()
|
Add exception type for script_fields related errors | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ScriptFieldsError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
|
Trim slashes from base URL. | <?php
namespace Orbt\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Main service for materializing services.
*/
class ResourceMirror
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
protected $dispatcher;
/**
* Mirror base URL.
* @var string
*/
protected $baseUrl;
/**
* Base resource directory.
* @var string
*/
protected $directory;
/**
* Creates a new resource mirror.
*
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* Event dispatcher.
* @param string $baseUrl
* Base URL for the backend.
* @param string $directory
* Path to the base directory to materialize resources to.
*
* @throws \InvalidArgumentException
* If the given directory is not writable.
*/
public function __construct(EventDispatcherInterface $dispatcher, $baseUrl, $directory)
{
$this->dispatcher = $dispatcher;
$this->baseUrl = $baseUrl == '/' ? $baseUrl : rtrim($baseUrl, '\\/');
if (!is_dir($directory) || !is_writable($directory)) {
throw new \InvalidArgumentException('Directory is not writable.');
}
$this->directory = $directory;
}
/**
* Returns the base URL of this mirror.
* @return string
*/
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* Returns the base directory used by this mirror.
* @return string
*/
public function getDirectory()
{
return $this->directory;
}
}
| <?php
namespace Orbt\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Main service for materializing services.
*/
class ResourceMirror
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
protected $dispatcher;
/**
* Mirror base URL.
* @var string
*/
protected $baseUrl;
/**
* Base resource directory.
* @var string
*/
protected $directory;
/**
* Creates a new resource mirror.
*
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* Event dispatcher.
* @param string $baseUrl
* Base URL for the backend.
* @param string $directory
* Path to the base directory to materialize resources to.
*
* @throws \InvalidArgumentException
* If the given directory is not writable.
*/
public function __construct(EventDispatcherInterface $dispatcher, $baseUrl, $directory)
{
$this->dispatcher = $dispatcher;
$this->baseUrl = $baseUrl;
if (!is_dir($directory) || !is_writable($directory)) {
throw new \InvalidArgumentException('Directory is not writable.');
}
$this->directory = $directory;
}
/**
* Returns the base URL of this mirror.
* @return string
*/
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* Returns the base directory used by this mirror.
* @return string
*/
public function getDirectory()
{
return $this->directory;
}
}
|
Add optional plugin build options
Adds a `--plugins` CLI option Grunt build command which is a comma separated list of plugins that will be included in the build. | module.exports = function(grunt) {
var _ = grunt.util._;
var plugins = (grunt.option('plugins') || '').split(',');
var gruntConfig = {
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: '\n'
},
dist: {
src: [
'vendor/**/*.js',
'template/_header.js',
'src/**/*.js',
'template/_footer.js'
],
dest: 'build/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! Raven.js <%= pkg.version %> | github.com/getsentry/raven-js */\n'
},
dist: {
files: {
'build/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
}
};
// Create plugin paths and verify hey exist
var plugins = _.map(plugins, function (plugin) {
var path = 'plugins/' + plugin + '.js';
if(!grunt.file.exists(path))
throw new Error("Plugin '" + plugin + "' not found in plugins directory.");
return path;
});
// Amend plugins to the concat source list
gruntConfig.concat.dist.src = gruntConfig.concat.dist.src.concat(plugins);
grunt.initConfig(gruntConfig);
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat', 'uglify']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: '\n'
},
dist: {
src: [
'vendor/**/*.js',
'template/_header.js',
'src/**/*.js',
'template/_footer.js',
'plugins/**/*.js'
],
dest: 'build/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! Raven.js <%= pkg.version %> | github.com/getsentry/raven-js */\n'
},
dist: {
files: {
'build/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat', 'uglify']);
};
|
Fix up syntax error in JS from my merge/port upto V8 - oops :( | (function () {
function CreateNotifyController(
$scope,
contentResource,
navigationService,
angularHelper) {
var vm = this;
var currentForm;
vm.notifyOptions = [];
vm.save = save;
vm.cancel = cancel;
vm.message = {
name: $scope.currentNode.name
};;
function onInit() {
vm.loading = true;
contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) {
currentForm = angularHelper.getCurrentForm($scope);
vm.loading = false;
vm.notifyOptions = options;
});
}
function cancel() {
navigationService.hideMenu();
};
function save(notifyOptions) {
vm.saveState = "busy";
vm.saveError = false;
vm.saveSuccces = false;
var selectedString = [];
angular.forEach(notifyOptions, function (option) {
if (option.checked === true && option.notifyCode) {
selectedString.push(option.notifyCode);
}
})
contentResource.setNotifySettingsById($scope.currentNode.id, selectedString).then(function () {
vm.saveState = "success";
vm.saveSuccces = true;
}, function (error) {
vm.saveState = "error";
vm.saveError = error;
});
}
onInit();
}
angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController);
}()); | (function () {
function CreateNotifyController(
$scope,
contentResource,
navigationService,
angularHelper) {
var vm = this;
var currentForm;
vm.notifyOptions = [];
vm.save = save;
vm.cancel = cancel;
vm.message = {
name: $scope.currentNode.name
};;
function onInit() {
vm.loading = true;
contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) {
currentForm = angularHelper.getCurrentForm($scope);
vm.loading = false;
vm.notifyOptions = options;
});
}
function cancel() {
navigationService.hideMenu();
};
function save(notifyOptions) {
vm.saveState = "busy";
vm.saveError = false;
vm.saveSuccces = false;
var selectedString = [];
angular.forEach(notifyOptions,
function(option) {
if (option.checked === true && option.notifyCode) {
selectedString.push(option.notifyCode);
}
console.log('selectedString', selectedString);
contentResource.setNotifySettingsById($scope.currentNode.id, selectedString).then(function () {
vm.saveState = "success";
vm.saveSuccces = true;
}, function (error) {
vm.saveState = "error";
vm.saveError = error;
});
}
onInit();
}
angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController);
}());
|
Fix default not being used in getSettings | // Requires
var Q = require('q');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
function setup(options, imports, register) {
var workspace = imports.workspace;
var logger = imports.logger.namespace("settings");
var settings = {};
// Return settings
var getSettings = function(key, def) {
return settings[workspace.id][key] || def;
};
// Set settings
var setSettings = function(key, value) {
settings[workspace.id][key] = value
};
// Save settings
var saveSettings = function() {
logger.log("Saving local settings")
return Q().then(function() {
return Q.nfcall(fs.writeFile, options.storageFile, JSON.stringify(settings, undefined, 4));
});
};
// Extend settings
var extendSettings = function(key, value) {
var s = getSettings(key, {});
s = _.extend(s, value);
setSettings(key, s);
};
return Q.nfcall(fs.readFile, options.storageFile, "utf-8").then(function(content) {
settings = JSON.parse(content);
}).fail(function() {
settings = {};
return Q();
}).then(function() {
logger.log("Settings load for", workspace.id);
settings[workspace.id] = settings[workspace.id] || {};
return {
"settings": {
'get': getSettings,
'set': setSettings,
'extend': extendSettings,
'save': saveSettings
}
};
});
}
// Exports
module.exports = setup;
| // Requires
var Q = require('q');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
function setup(options, imports, register) {
var workspace = imports.workspace;
var logger = imports.logger.namespace("settings");
var settings = {};
// Return settings
var getSettings = function(key, def) {
return settings[workspace.id][key] || {};
};
// Set settings
var setSettings = function(key, value) {
settings[workspace.id][key] = value
};
// Save settings
var saveSettings = function() {
logger.log("Saving local settings")
return Q().then(function() {
return Q.nfcall(fs.writeFile, options.storageFile, JSON.stringify(settings, undefined, 4));
});
};
// Extend settings
var extendSettings = function(key, value) {
var s = getSettings(key, {});
s = _.extend(s, value);
setSettings(key, s);
};
return Q.nfcall(fs.readFile, options.storageFile, "utf-8").then(function(content) {
settings = JSON.parse(content);
}).fail(function() {
settings = {};
return Q();
}).then(function() {
logger.log("Settings load for", workspace.id);
settings[workspace.id] = settings[workspace.id] || {};
return {
"settings": {
'get': getSettings,
'set': setSettings,
'extend': extendSettings,
'save': saveSettings
}
};
});
}
// Exports
module.exports = setup; |
Update "X-Molotov-Agent" header for Molotov version 1.2.2. | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":3,\"app_version_name\":\"1.2.2\",\"type\":\"desktop\",\"electron_version\":\"1.4.12\",\"os\":\"Unknown\",\"os_version\":\"Unknown\",\"manufacturer\":\"MoloChrome\",\"serial\":\"Unknown\",\"model\":\"MoloChrome\",\"brand\":\"MoloChrome\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login",
"https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
chrome.webRequest.onCompleted.addListener(
function(details) {
// User successfully logged in.
if (details.method == "POST"
&& details.url == "https://fapi.molotov.tv/v2/auth/login"
&& details.statusCode == "200") {
chrome.tabs.reload();
}
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login"
],
types: ["xmlhttprequest"]
}
);
chrome.browserAction.onClicked.addListener(
function(details) {
chrome.tabs.create({url: "http://app.molotov.tv/"});
}
); | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":2,\"app_version_name\":\"1.0.0\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login",
"https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
chrome.webRequest.onCompleted.addListener(
function(details) {
// User successfully logged in.
if (details.method == "POST"
&& details.url == "https://fapi.molotov.tv/v2/auth/login"
&& details.statusCode == "200") {
chrome.tabs.reload();
}
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login"
],
types: ["xmlhttprequest"]
}
);
chrome.browserAction.onClicked.addListener(
function(details) {
chrome.tabs.create({url: "http://app.molotov.tv/"});
}
); |
Fix deleting all webhooks for a list | <?php namespace JohnRivs\Wunderlist;
trait Webhook {
/**
* Show all the webhooks for a list.
*
* @param array $attributes
* @return array
*/
public function getWebhooks(array $attributes = [])
{
$this->requires(['list_id'], $attributes);
return $this->call('GET', 'webhooks', ['query' => $attributes]);
}
/**
* Create a webhook for a list.
*
* @param array $attributes
* @return array
*/
public function createWebhook(array $attributes = [])
{
$this->requires(['list_id', 'url', 'processor_type', 'configuration'], $attributes);
return $this->call('POST', 'webhooks', ['json' => $attributes]);
}
/**
* Delete a webhook for a list.
*
* @param int $webhookId The id of the webhook.
* @return int
*/
public function deleteWebhook($webhookId)
{
$this->call('DELETE', "webhooks/{$webhookId}");
return $this->getStatusCode();
}
/**
* Deletes all webhooks for a list.
*
* @param $listId The id of the list.
* @return int
*/
public function deleteWebhooks($listId)
{
$webhooks = $this->getWebhooks(['list_id' => $listId]);
foreach ($webhooks as $webhook) {
$this->deleteWebhook($webhook['id']);
}
return $this->getStatusCode();
}
}
| <?php namespace JohnRivs\Wunderlist;
trait Webhook {
/**
* Show all the webhooks for a list.
*
* @param array $attributes
* @return array
*/
public function getWebhooks(array $attributes = [])
{
$this->requires(['list_id'], $attributes);
return $this->call('GET', 'webhooks', ['query' => $attributes]);
}
/**
* Create a webhook for a list.
*
* @param array $attributes
* @return array
*/
public function createWebhook(array $attributes = [])
{
$this->requires(['list_id', 'url', 'processor_type', 'configuration'], $attributes);
return $this->call('POST', 'webhooks', ['json' => $attributes]);
}
/**
* Delete a webhook for a list.
*
* @param int $webhookId The id of the webhook.
* @return int
*/
public function deleteWebhook($webhookId)
{
$this->call('DELETE', "webhooks/{$webhookId}");
return $this->getStatusCode();
}
/**
* Deletes all webhooks for a list.
*
* @param $listId The id of the list.
* @return int
*/
public function deleteWebhooks($listId)
{
$webhooks = $this->getWebhooks($listId);
foreach ($webhooks as $webhook) {
$this->deleteWebhook($webhook['id']);
}
return $this->getStatusCode();
}
}
|
Hide button to delete the first form of the formset | // django-dynamic-formset fixes for bootstrap 3
(function($) {
$(document).ready(function(){
function fixDeleteRow ($deleteClickable) {
// Move .delete-row link immediately after the form input
var $deleteClickableList = $deleteClickable.parent();
var $formInputField = $deleteClickableList.parent().find("input");
$deleteClickableList.insertAfter($formInputField);
// Strip its li tags
$deleteClickableList.replaceWith($deleteClickable);
// Style it with bootstrap3 classes
$deleteClickable.addClass("btn btn-default");
}
// To apply on the initially generated .delete-row link
var $deleteClickable = $(".delete-row");
fixDeleteRow($deleteClickable);
// Style add-row link with bootstrap3 classes
var $addAnotherClickables = $(".add-row");
$addAnotherClickables.addClass("btn btn-default");
// To apply on subsequently generated .delete-row links
$(".add-row").click(function() {
// Move .delete-row link immediately after the form input
var $deleteClickable = $(".delete-row").last();
fixDeleteRow($deleteClickable);
});
// To apply on form validation errors
// .help-block tag comes up when validation error is shown.
if ($(".help-block").length > 0) {
// Slice of the already styled last element.
var $deleteClickables = $(".delete-row").slice(0, -1);
for (i in $deleteClickables) {
fixDeleteRow($deleteClickables.eq(i));
}
}
// Don't show first remove button, user should always fill
// in one form at least.
$(".delete-row").first().hide();
});
})(jQuery);
| // django-dynamic-formset fixes for bootstrap 3
(function($) {
$(document).ready(function(){
function fixDeleteRow ($deleteClickable) {
// Move .delete-row link immediately after the form input
var $deleteClickableList = $deleteClickable.parent();
var $formInputField = $deleteClickableList.parent().find("input");
$deleteClickableList.insertAfter($formInputField);
// Strip its li tags
$deleteClickableList.replaceWith($deleteClickable);
// Style it with bootstrap3 classes
$deleteClickable.addClass("btn btn-default");
}
// To apply on the initially generated .delete-row link
var $deleteClickable = $(".delete-row");
fixDeleteRow($deleteClickable);
// Style add-row link with bootstrap3 classes
var $addAnotherClickables = $(".add-row");
$addAnotherClickables.addClass("btn btn-default");
// To apply on subsequently generated .delete-row links
$(".add-row").click(function() {
// Move .delete-row link immediately after the form input
var $deleteClickable = $(".delete-row").last();
fixDeleteRow($deleteClickable);
});
// To apply on form validation errors
// .help-block tag comes up when validation error is shown.
if ($(".help-block").length > 0) {
// Slice of the already styled last element.
var $deleteClickables = $(".delete-row").slice(0, -1);
for (i in $deleteClickables) {
fixDeleteRow($deleteClickables.eq(i));
}
}
});
})(jQuery);
|
Fix typo which causes memory leak. | define([
'jquery',
'var/eventStorage',
'prototype/var/EmojioneArea'
],
function($, eventStorage, EmojioneArea) {
EmojioneArea.prototype.off = function(events, handler) {
if (events) {
var id = this.id;
$.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i, event) {
if (eventStorage[id][event] && !/^@/.test(event)) {
if (handler) {
$.each(eventStorage[id][event], function(j, fn) {
if (fn === handler) {
eventStorage[id][event].splice(j, 1);
}
});
} else {
eventStorage[id][event] = [];
}
}
});
}
return this;
};
}); | define([
'jquery',
'var/eventStorage',
'prototype/var/EmojioneArea'
],
function($, eventStorage, EmojioneArea) {
EmojioneArea.prototype.off = function(events, handler) {
if (events) {
var id = this.id;
$.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i, event) {
if (eventStorage[id][event] && !/^@/.test(event)) {
if (handler) {
$.each(eventStorage[id][event], function(j, fn) {
if (fn === handler) {
eventStorage[id][event] = eventStorage[id][event].splice(j, 1);
}
});
} else {
eventStorage[id][event] = [];
}
}
});
}
return this;
};
}); |
Fix for different types with the same value giving the same hash, such as "1" and 1 | /*
* Hashcode.js 1.0.0
* https://github.com/stuartbannerman/hashcode
*
* Copyright 2013 Stuart Bannerman ([email protected])
* Released under the MIT license
*
* Date: 07-04-2013
*/
(function(window)
{
window.Hashcode = (function()
{
// Hashes a string
var hash = function(string)
{
var string = string.toString(), hash = 0, i;
for (i = 0; i < string.length; i++)
{
hash = (((hash << 5) - hash) + string.charCodeAt(i)) & 0xFFFFFFFF;
}
return hash;
};
// Deep hashes an object
var object = function(obj)
{
var result = 0;
for(var property in obj)
{
if(obj.hasOwnProperty(property))
{
result += value(obj[property]) + hash(property);
}
}
return result;
};
// Does a type check on the passed in value and calls the appropriate hash method
var value = function(value)
{
var types =
{
'string' : hash,
'number' : hash,
'object' : object,
'function' : 0
};
var type = typeof value;
return types[type] && types[type](value) + hash(type) || 0;
};
return {
value: value
};
})();
})(window); | /*
* Hashcode.js 1.0.0
* https://github.com/stuartbannerman/hashcode
*
* Copyright 2013 Stuart Bannerman ([email protected])
* Released under the MIT license
*
* Date: 07-04-2013
*/
(function(window)
{
window.Hashcode = (function()
{
// Hashes a string
var hash = function(string)
{
var string = string.toString(), hash = 0, i;
for (i = 0; i < string.length; i++)
{
hash = (((hash << 5) - hash) + string.charCodeAt(i)) & 0xFFFFFFFF;
}
return hash;
};
// Deep hashes an object
var object = function(obj)
{
var result = 0;
for(var property in obj)
{
if(obj.hasOwnProperty(property))
{
result += value(obj[property]) + hash(property);
}
}
return result;
};
// Does a type check on the passed in value and calls the appropriate hash method
var value = function(value)
{
var types =
{
'string' : hash,
'number' : hash,
'object' : object,
'function' : 0
};
var type = typeof value;
return types[type] && types[type](value) || 0;
};
return {
value: value
};
})();
})(window); |
Support a range of redis client versions | import os
import re
from setuptools import (
find_packages,
setup,
)
version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]")
def get_version():
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, 'curator/__init__.py')) as initf:
for line in initf:
m = version_re.match(line.strip())
if not m:
continue
return m.groups()[0]
setup(
name='redis-lua-curator',
version=get_version(),
description='Helper for working with lua scripts.',
packages=find_packages(exclude=[
"*.tests",
"*.tests.*",
"tests.*",
"tests",
]),
author='Michael Hahn',
author_email='[email protected]',
url='https://github.com/mhahn/curator/',
download_url='https://github.com/mhahn/curator/tarball/%s' % (
get_version(),
),
setup_requires=[
'nose>=1.0',
'coverage>=1.0',
'mock==1.0.1',
'unittest2==0.5.1',
],
install_requires=[
'redis >= 2.8.0, <= 2.10.1',
'jinja2==2.7.2',
],
keywords=['redis', 'lua'],
)
| import os
import re
from setuptools import (
find_packages,
setup,
)
version_re = re.compile(r"__version__\s*=\s*['\"](.*?)['\"]")
def get_version():
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, 'curator/__init__.py')) as initf:
for line in initf:
m = version_re.match(line.strip())
if not m:
continue
return m.groups()[0]
setup(
name='redis-lua-curator',
version=get_version(),
description='Helper for working with lua scripts.',
packages=find_packages(exclude=[
"*.tests",
"*.tests.*",
"tests.*",
"tests",
]),
author='Michael Hahn',
author_email='[email protected]',
url='https://github.com/mhahn/curator/',
download_url='https://github.com/mhahn/curator/tarball/%s' % (
get_version(),
),
setup_requires=[
'nose>=1.0',
'coverage>=1.0',
'mock==1.0.1',
'unittest2==0.5.1',
],
install_requires=[
'redis==2.10.1',
'jinja2==2.7.2',
],
keywords=['redis', 'lua'],
)
|
Add styles for code blocks | import React from "react";
import { graphql, Link } from "gatsby";
import Layout from "../app/layout";
import "prismjs/themes/prism-solarizedlight.css";
import "./blog-post.scss";
export const BLOG_POST_QUERY = graphql`
query BlogPostTemplate($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
id
excerpt
html
fields {
slug
}
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
}
}
`;
function BlogPostTemplate(props) {
const post = props.data.markdownRemark;
return (
<Layout>
<main>
<article className="BlogPost">
<div className="l-wide">
<div className="BlogPost-metadata">
<h1 className="BlogPost-title">
<Link to={post.fields.slug}>{post.frontmatter.title}</Link>
</h1>
<time className="BlogPost-date">{post.frontmatter.date}</time>
</div>
</div>
<div className="l-narrow">
<div
className="BlogPost-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
</div>
</article>
</main>
</Layout>
);
}
export default BlogPostTemplate;
| import React from "react";
import { graphql, Link } from "gatsby";
import Layout from "../app/layout";
import "./blog-post.scss";
export const BLOG_POST_QUERY = graphql`
query BlogPostTemplate($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
id
excerpt
html
fields {
slug
}
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
}
}
`;
function BlogPostTemplate(props) {
const post = props.data.markdownRemark;
return (
<Layout>
<main>
<article className="BlogPost">
<div className="l-wide">
<div className="BlogPost-metadata">
<h1 className="BlogPost-title">
<Link to={post.fields.slug}>{post.frontmatter.title}</Link>
</h1>
<time className="BlogPost-date">{post.frontmatter.date}</time>
</div>
</div>
<div className="l-narrow">
<div
className="BlogPost-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
</div>
</article>
</main>
</Layout>
);
}
export default BlogPostTemplate;
|
Use vendor and product id for udev rules | #!/usr/bin/env python3
import os
import requests
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os.O_NONBLOCK)
fd = os.fdopen(fd_id, 'rb+')
last = None
return_code = 0
try:
while True:
data = fd.write(bytes(WRITE_BYTES))
data = fd.read(8)
if data is not None and data[0] != last:
if data[0] == CLOSED:
action = 'closed'
elif last == DOWN and data[0] == OPEN:
action = 'up'
elif data[0] == OPEN:
action = 'open'
elif data[0] == DOWN:
action = 'down'
last = data[0]
requests.post('http://requestb.in/ok0w6bok', data={"action": action})
sleep(0.1)
except KeyboardInterrupt:
return_code = 0
except Exception as e:
print(e, file=stderr)
return_code = 1
finally:
fd.close()
return return_code
if __name__ == '__main__':
exit(main())
| #!/usr/bin/env python3
import os
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os.O_NONBLOCK)
fd = os.fdopen(fd_id, 'rb+')
last = None
return_code = 0
try:
while True:
data = fd.write(bytes(WRITE_BYTES))
data = fd.read(8)
if data is not None and data[0] != last:
if data[0] == CLOSED:
print('closed')
elif last == DOWN and data[0] == OPEN:
print('up')
elif data[0] == OPEN:
print('open')
elif data[0] == DOWN:
print('down')
last = data[0]
sleep(0.1)
except KeyboardInterrupt:
return_code = 0
except Exception as e:
print(e, file=stderr)
return_code = 1
finally:
fd.close()
return return_code
if __name__ == '__main__':
exit(main())
|
refact(checkbox): Move cssClass from label to div | package lt.inventi.wicket.component.bootstrap.form;
import org.apache.wicket.util.string.AppendingStringBuffer;
abstract class ChoiceUtils {
public enum InputPosition {
BEFORE_LABEL, AFTER_LABEL
}
private ChoiceUtils() {
// static utils
}
static void moveInputInsideLabel(AppendingStringBuffer buffer, String cssClass, InputPosition position) {
int inputIdx = buffer.lastIndexOf("<input");
if (inputIdx == -1) {
throw new IllegalStateException("Must contain an input!");
}
int labelIdx = buffer.indexOf("<label", inputIdx);
if (labelIdx == -1) {
throw new IllegalStateException("Must contain a label!");
}
int labelEndIdx = buffer.indexOf("</label>", labelIdx);
if (labelEndIdx == -1) {
throw new IllegalStateException("Must contain label's end!");
}
String label = buffer.substring(labelIdx, labelEndIdx);
String labelClass = "class=\"" + cssClass + "\" ";
String labelWithClass = label.substring(0, 7) + labelClass + label.substring(7, label.length());
String input = buffer.substring(inputIdx, labelIdx);
buffer.replace(inputIdx, labelEndIdx, position == InputPosition.BEFORE_LABEL ? "<div class=\"" + cssClass + "\">" + input + label + "</div>" : labelWithClass + input);
}
}
| package lt.inventi.wicket.component.bootstrap.form;
import org.apache.wicket.util.string.AppendingStringBuffer;
abstract class ChoiceUtils {
public enum InputPosition {
BEFORE_LABEL, AFTER_LABEL
}
private ChoiceUtils() {
// static utils
}
static void moveInputInsideLabel(AppendingStringBuffer buffer, String cssClass, InputPosition position) {
int inputIdx = buffer.lastIndexOf("<input");
if (inputIdx == -1) {
throw new IllegalStateException("Must contain an input!");
}
int labelIdx = buffer.indexOf("<label", inputIdx);
if (labelIdx == -1) {
throw new IllegalStateException("Must contain a label!");
}
int labelEndIdx = buffer.indexOf("</label>", labelIdx);
if (labelEndIdx == -1) {
throw new IllegalStateException("Must contain label's end!");
}
String label = buffer.substring(labelIdx, labelEndIdx);
String labelClass = "class=\"" + cssClass + "\" ";
String labelWithClass = label.substring(0, 7) + labelClass + label.substring(7, label.length());
String input = buffer.substring(inputIdx, labelIdx);
buffer.replace(inputIdx, labelEndIdx, position == InputPosition.BEFORE_LABEL ? "<div>" + input + labelWithClass + "</div>" : labelWithClass + input);
}
}
|
Fix to target events (not all card effects) | const DrawCard = require('../../drawcard.js');
const EventRegistrar = require('../../eventregistrar.js');
const { CardTypes, Players } = require('../../Constants');
class MagnificentTriumph extends DrawCard {
setupCardAbilities(ability) {
this.duelWinnersThisConflict = [];
this.eventRegistrar = new EventRegistrar(this.game, this);
this.eventRegistrar.register(['onConflictFinished', 'afterDuel']);
this.action({
title: 'Give a character +2/+2',
condition: () => this.game.isDuringConflict(),
target: {
cardType: CardTypes.Character,
controller: Players.Any,
cardCondition: card => this.duelWinnersThisConflict.includes(card),
gameAction: ability.actions.cardLastingEffect({
effect: [
ability.effects.modifyBothSkills(2),
ability.effects.cardCannot({
cannot: 'target',
restricts: 'opponentsEvents'
})
]
})
},
effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s events',
effectArgs: () => ['military', 'political']
});
}
onConflictFinished() {
this.duelWinnersThisConflict = [];
}
afterDuel(event) {
if(event.duel.winner) {
this.duelWinnersThisConflict.push(event.duel.winner);
}
}
}
MagnificentTriumph.id = 'magnificent-triumph';
module.exports = MagnificentTriumph;
| const DrawCard = require('../../drawcard.js');
const EventRegistrar = require('../../eventregistrar.js');
const { CardTypes, Players } = require('../../Constants');
class MagnificentTriumph extends DrawCard {
setupCardAbilities(ability) {
this.duelWinnersThisConflict = [];
this.eventRegistrar = new EventRegistrar(this.game, this);
this.eventRegistrar.register(['onConflictFinished', 'afterDuel']);
this.action({
title: 'Give a character +2/+2',
condition: () => this.game.isDuringConflict(),
target: {
cardType: CardTypes.Character,
controller: Players.Any,
cardCondition: card => this.duelWinnersThisConflict.includes(card),
gameAction: ability.actions.cardLastingEffect({
effect: [
ability.effects.modifyBothSkills(2),
ability.effects.cardCannot({
cannot: 'target',
restricts: 'opponentsCardEffects'
})
]
})
},
effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s abilities',
effectArgs: () => ['military', 'political']
});
}
onConflictFinished() {
this.duelWinnersThisConflict = [];
}
afterDuel(event) {
if(event.duel.winner) {
this.duelWinnersThisConflict.push(event.duel.winner);
}
}
}
MagnificentTriumph.id = 'magnificent-triumph';
module.exports = MagnificentTriumph;
|
Simplify Eidos reader, use Eidos JSON String call | import json
from indra.java_vm import autoclass, JavaException
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
instance of the reader and are therefore faster.
Attributes
----------
eidos_reader : org.clulab.wm.AgroSystem
A Scala object, an instance of the Eidos reading system. It is
instantiated only when first processing text.
"""
def __init__(self):
self.eidos_reader = None
def process_text(self, text):
"""Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
eidos = autoclass('org.clulab.wm.AgroSystem')
self.eidos_reader = eidos(autoclass('java.lang.Object')())
mentions = self.eidos_reader.extractFrom(text)
ser = autoclass('org.clulab.wm.serialization.json.WMJSONSerializer')
mentions_json = ser.toJsonStr(mentions)
json_dict = json.loads(mentions_json)
return json_dict
| from indra.java_vm import autoclass, JavaException
from .scala_utils import get_python_json
class EidosReader(object):
"""Reader object keeping an instance of the Eidos reader as a singleton.
This allows the Eidos reader to need initialization when the first piece of
text is read, the subsequent readings are done with the same
instance of the reader and are therefore faster.
Attributes
----------
eidos_reader : org.clulab.wm.AgroSystem
A Scala object, an instance of the Eidos reading system. It is
instantiated only when first processing text.
"""
def __init__(self):
self.eidos_reader = None
def process_text(self, text):
"""Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
eidos = autoclass('org.clulab.wm.AgroSystem')
self.eidos_reader = eidos(autoclass('java.lang.Object')())
mentions = self.eidos_reader.extractFrom(text)
ser = autoclass('org.clulab.wm.serialization.json.WMJSONSerializer')
mentions_json = ser.jsonAST(mentions)
json_dict = get_python_json(mentions_json)
return json_dict
|
Revert "Fix url for default user image" | define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
accountUrl: URL_PREFIX + '/account',
//TODO: change the logo_splash.png to user.png
gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' +
encodeURIComponent('https://mist.io/resources/images/user.png') +'&s=36'),
/**
*
* Actions
*
*/
actions: {
meClicked: function(){
$('#user-menu-popup').popup('open');
},
loginClicked: function() {
$('#user-menu-popup').popup('close');
Ember.run.later(function() {
Mist.loginController.open();
}, 300);
},
logoutClicked: function() {
Mist.loginController.logout();
}
}
});
}
);
| define('app/views/user_menu', ['app/views/templated', 'md5'],
/**
* User Menu View
*
* @returns Class
*/
function (TemplatedView) {
'user strict';
return TemplatedView.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
accountUrl: URL_PREFIX + '/account',
gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' +
encodeURIComponent('https://mist.io/resources/images/sprite-images/user.png') +'&s=36'),
/**
*
* Actions
*
*/
actions: {
meClicked: function(){
$('#user-menu-popup').popup('open');
},
loginClicked: function() {
$('#user-menu-popup').popup('close');
Ember.run.later(function() {
Mist.loginController.open();
}, 300);
},
logoutClicked: function() {
Mist.loginController.logout();
}
}
});
}
);
|
Fix test covering pip 1.5.2 error handling. | # coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
builder = wheeler.Builder()
with builder:
with self.assertRaises(wheeler.BuildError):
builder._find_wheel('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
| # coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
Reformat string representation of Credentials | import os
class Credential(object):
def __init__(self, name, login, password, comments):
self.name = name
self.login = login
self.password = password
self.comments = comments
def save(self, database_path):
credential_path = os.path.join(database_path, self.name)
os.makedirs(credential_path)
with open(os.path.join(credential_path, "login"), "w") as f:
f.write(self.login)
with open(os.path.join(credential_path, "password"), "w") as f:
f.write(self.password)
with open(os.path.join(credential_path, "comments"), "w") as f:
f.write(self.comments)
@classmethod
def from_path(cls, path):
return Credential(
name=os.path.basename(path),
login=open(path + "/login").read(),
password=open(path + "/password").read(),
comments=open(path + "/comments").read()
)
def __str__(self):
return "<Credential: name={}, login={}, password='...', {}>".format(
self.name,
self.login,
self.comments
)
| import os
class Credential(object):
def __init__(self, name, login, password, comments):
self.name = name
self.login = login
self.password = password
self.comments = comments
def save(self, database_path):
credential_path = os.path.join(database_path, self.name)
os.makedirs(credential_path)
with open(os.path.join(credential_path, "login"), "w") as f:
f.write(self.login)
with open(os.path.join(credential_path, "password"), "w") as f:
f.write(self.password)
with open(os.path.join(credential_path, "comments"), "w") as f:
f.write(self.comments)
@classmethod
def from_path(cls, path):
return Credential(
name=os.path.basename(path),
login=open(path + "/login").read(),
password=open(path + "/password").read(),
comments=open(path + "/comments").read()
)
def __str__(self):
return "<Credential: {}, {}, {}>".format(
self.name,
self.login,
self.comments
)
|
Fix translation typo message info folders | import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
| import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be in filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
|
Set require debug to be the same as debug. | from .base import * # noqa
DEBUG = True
REQUIRE_DEBUG = DEBUG
INTERNAL_IPS = INTERNAL_IPS + ('', )
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_kdl_dev',
'USER': 'app_kdl',
'PASSWORD': '',
'HOST': ''
},
}
LOGGING_LEVEL = logging.DEBUG
LOGGING['loggers']['kdl']['level'] = LOGGING_LEVEL
TEMPLATES[0]['OPTIONS']['debug'] = True
# -----------------------------------------------------------------------------
# Django Extensions
# http://django-extensions.readthedocs.org/en/latest/
# -----------------------------------------------------------------------------
try:
import django_extensions # noqa
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',)
except ImportError:
pass
# -----------------------------------------------------------------------------
# Django Debug Toolbar
# http://django-debug-toolbar.readthedocs.org/en/latest/
# -----------------------------------------------------------------------------
try:
import debug_toolbar # noqa
INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar',)
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + (
'debug_toolbar.middleware.DebugToolbarMiddleware',)
DEBUG_TOOLBAR_PATCH_SETTINGS = True
except ImportError:
pass
# -----------------------------------------------------------------------------
# Local settings
# -----------------------------------------------------------------------------
try:
from .local import * # noqa
except ImportError:
print('dev, failed to import local settings')
from .test import * # noqa
print('the project is running with test settings')
print('please create a local settings file')
| from .base import * # noqa
DEBUG = True
INTERNAL_IPS = INTERNAL_IPS + ('', )
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_kdl_dev',
'USER': 'app_kdl',
'PASSWORD': '',
'HOST': ''
},
}
LOGGING_LEVEL = logging.DEBUG
LOGGING['loggers']['kdl']['level'] = LOGGING_LEVEL
TEMPLATES[0]['OPTIONS']['debug'] = True
# -----------------------------------------------------------------------------
# Django Extensions
# http://django-extensions.readthedocs.org/en/latest/
# -----------------------------------------------------------------------------
try:
import django_extensions # noqa
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',)
except ImportError:
pass
# -----------------------------------------------------------------------------
# Django Debug Toolbar
# http://django-debug-toolbar.readthedocs.org/en/latest/
# -----------------------------------------------------------------------------
try:
import debug_toolbar # noqa
INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar',)
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + (
'debug_toolbar.middleware.DebugToolbarMiddleware',)
DEBUG_TOOLBAR_PATCH_SETTINGS = True
except ImportError:
pass
# -----------------------------------------------------------------------------
# Local settings
# -----------------------------------------------------------------------------
try:
from .local import * # noqa
except ImportError:
print('dev, failed to import local settings')
from .test import * # noqa
print('the project is running with test settings')
print('please create a local settings file')
|
Set default sales tax rates | <?php
namespace Freeagent\Invoice;
/**
* Class InvoiceItem
*
* @package Freeagent\Invoice
*/
class InvoiceItem
{
/**
* @var string
*/
public $item_type;
/**
* @var int
*/
public $quantity;
/**
* @var float
*/
public $price;
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $sales_tax_rate = 0;
/**
* @var int
*/
public $position;
/**
* @var int
*/
public $second_sales_tax_rate = 0;
/**
* @var string
*/
public $category;
/**
* @return array
*/
public function toArray()
{
return array(
'item_type' => $this->item_type,
'quantity' => $this->quantity,
'price' => $this->price,
'description' => $this->description,
'sales_tax_rate' => $this->sales_tax_rate,
'position' => $this->position,
'second_sales_tax_rate' => $this->second_sales_tax_rate,
'category' => $this->category
);
}
}
| <?php
namespace Freeagent\Invoice;
/**
* Class InvoiceItem
*
* @package Freeagent\Invoice
*/
class InvoiceItem
{
/**
* @var string
*/
public $item_type;
/**
* @var int
*/
public $quantity;
/**
* @var float
*/
public $price;
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $sales_tax_rate;
/**
* @var int
*/
public $position;
/**
* @var string
*/
public $second_sales_tax_rate;
/**
* @var string
*/
public $category;
/**
* @return array
*/
public function toArray()
{
return array(
'item_type' => $this->item_type,
'quantity' => $this->quantity,
'price' => $this->price,
'description' => $this->description,
'sales_tax_rate' => $this->sales_tax_rate,
'position' => $this->position,
'second_sales_tax_rate' => $this->second_sales_tax_rate,
'category' => $this->category
);
}
}
|
Change triggerEvent possible value to mouseover for consistency | (function($){
$.fn.seAccordion = function(options) {
var defaults = {
header: 'h1',
content: 'div',
speed: 'slow',
easing: 'swing',
singleOpen: true,
allowAllClosed: false,
triggerEvent: 'click'
};
var params = $.extend(defaults, options);
return this.each(function() {
var obj = $(this),
triggerEvent = 'touchstart click',
slideOptions = {
duration: params.speed,
easing: params.easing
};
if(params.singleOpen === true && params.allowAllClosed === false)
obj.children(params.content).first().addClass('opened');
obj.children(params.header).css('cursor', 'pointer');
obj.children(params.content + ':not(.opened)').css('display', 'none');
if(params.triggerEvent === 'mouseover')
triggerEvent = 'mouseover';
obj.children(params.header).off().on(triggerEvent, function(e) {
e.preventDefault();
if(!$(this).next(params.content).hasClass('opened'))
{
if(params.singleOpen === true)
obj.children(params.content + '.opened').stop().removeClass('opened').slideUp(slideOptions);
$(this).next(params.content).stop().addClass('opened').slideDown(slideOptions);
}
else
{
if(params.singleOpen === true && params.allowAllClosed === false)
return;
$(this).next(params.content).stop().removeClass('opened').slideUp(slideOptions);
}
});
});
};
})(jQuery);
| (function($){
$.fn.seAccordion = function(options) {
var defaults = {
header: 'h1',
content: 'div',
speed: 'slow',
easing: 'swing',
singleOpen: true,
allowAllClosed: false,
triggerEvent: 'click'
};
var params = $.extend(defaults, options);
return this.each(function() {
var obj = $(this),
triggerEvent = 'touchstart click',
slideOptions = {
duration: params.speed,
easing: params.easing
};
if(params.singleOpen === true && params.allowAllClosed === false)
obj.children(params.content).first().addClass('opened');
obj.children(params.header).css('cursor', 'pointer');
obj.children(params.content + ':not(.opened)').css('display', 'none');
if(params.triggerEvent === 'hover')
triggerEvent = 'mouseover';
obj.children(params.header).off().on(triggerEvent, function(e) {
e.preventDefault();
if(!$(this).next(params.content).hasClass('opened'))
{
if(params.singleOpen === true)
obj.children(params.content + '.opened').stop().removeClass('opened').slideUp(slideOptions);
$(this).next(params.content).stop().addClass('opened').slideDown(slideOptions);
}
else
{
if(params.singleOpen === true && params.allowAllClosed === false)
return;
$(this).next(params.content).stop().removeClass('opened').slideUp(slideOptions);
}
});
});
};
})(jQuery);
|
Convert maxmind raw result to UTF-8 | <?php
namespace Maxmind\MinFraud;
class MinFraudResponse
{
private $isCurlSuccessful;
private $rawResult;
/**
* @param bool $isCurlSuccessful
* @param string $result
*/
public function __construct($isCurlSuccessful, $result)
{
$this->isCurlSuccessful = $isCurlSuccessful;
$this->rawResult = mb_convert_encoding($result, 'UTF-8', 'UTF-8');
}
/**
* @return boolean
*/
public function getIsCurlSuccessful()
{
return $this->isCurlSuccessful;
}
/**
* @return string
*/
public function getRawResult()
{
return $this->rawResult;
}
/**
* @return array
*/
public function getResult()
{
$result = array();
if ($this->getIsCurlSuccessful()) {
$keyValuePairs = explode(";", $this->getRawResult());
foreach ($keyValuePairs as $keyValuePair) {
$keyValue = explode("=", $keyValuePair);
$result[$keyValue[0]] = isset($keyValue[1]) ? $keyValue[1] : '';
}
}
return $result;
}
} | <?php
namespace Maxmind\MinFraud;
class MinFraudResponse
{
private $isCurlSuccessful;
private $rawResult;
/**
* @param bool $isCurlSuccessful
* @param string $result
*/
public function __construct($isCurlSuccessful, $result)
{
$this->isCurlSuccessful = $isCurlSuccessful;
$this->rawResult = $result;
}
/**
* @return boolean
*/
public function getIsCurlSuccessful()
{
return $this->isCurlSuccessful;
}
/**
* @return string
*/
public function getRawResult()
{
return $this->rawResult;
}
/**
* @return array
*/
public function getResult()
{
$result = array();
if ($this->getIsCurlSuccessful()) {
$keyValuePairs = explode(";", $this->getRawResult());
foreach ($keyValuePairs as $keyValuePair) {
$keyValue = explode("=", $keyValuePair);
$result[$keyValue[0]] = isset($keyValue[1]) ? $keyValue[1] : '';
}
}
return $result;
}
} |
Create sentinel rounds on Session creation | from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Session)
def session_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
if created:
i = 1
while i <= instance.num_rounds:
instance.rounds.create(
num=i,
kind=(instance.num_rounds - i) + 1,
)
i += 1
@receiver(post_save, sender=Performance)
def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
if created:
s = 1
while s <= instance.round.num_songs:
song = instance.songs.create(
performance=instance,
num=s,
)
s += 1
judges = instance.round.session.judges.filter(
category__in=[
instance.round.session.judges.model.CATEGORY.music,
instance.round.session.judges.model.CATEGORY.presentation,
instance.round.session.judges.model.CATEGORY.singing,
]
)
for judge in judges:
judge.scores.create(
judge=judge,
song=song,
category=judge.category,
kind=judge.kind,
)
| from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Performance)
def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
if created:
s = 1
while s <= instance.round.num_songs:
song = instance.songs.create(
performance=instance,
num=s,
)
s += 1
judges = instance.round.session.judges.filter(
category__in=[
instance.round.session.judges.model.CATEGORY.music,
instance.round.session.judges.model.CATEGORY.presentation,
instance.round.session.judges.model.CATEGORY.singing,
]
)
for judge in judges:
judge.scores.create(
judge=judge,
song=song,
category=judge.category,
kind=judge.kind,
)
@receiver(post_save, sender=Session)
def session_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
if created:
i = 1
while i <= instance.num_rounds:
instance.rounds.create(
num=i,
kind=(instance.num_rounds - i) + 1,
)
i += 1
|
Fix selector for update credit card form | $(function() {
$("#credit-card input, #credit-card select").attr("disabled", false);
$("form:has(#credit-card)").submit(function() {
var form = this;
$("#user_submit").attr("disabled", true);
$("#credit-card input, #credit-card select").attr("name", "");
$("#credit-card-errors").hide();
if (!$("#credit-card").is(":visible")) {
$("#credit-card input, #credit-card select").attr("disabled", true);
return true;
}
var card = {
number: $("#credit_card_number").val(),
expMonth: $("#_expiry_date_2i").val(),
expYear: $("#_expiry_date_1i").val(),
cvc: $("#cvv").val()
};
Stripe.createToken(card, function(status, response) {
if (status === 200) {
$("#user_last_4_digits").val(response.card.last4);
$("#user_stripe_token").val(response.id);
form.submit();
} else {
$("#stripe-error-message").text(response.error.message);
$("#credit-card-errors").show();
$("#user_submit").attr("disabled", false);
}
});
return false;
});
$("#change-card a").click(function() {
$("#change-card").hide();
$("#credit-card").show();
$("#credit_card_number").focus();
return false;
});
});
| $(function() {
$("#credit-card input, #credit-card select").attr("disabled", false);
$("#new_user, .edit_user").submit(function() {
var form = this;
$("#user_submit").attr("disabled", true);
$("#credit-card input, #credit-card select").attr("name", "");
$("#credit-card-errors").hide();
if (!$("#credit-card").is(":visible")) {
$("#credit-card input, #credit-card select").attr("disabled", true);
return true;
}
var card = {
number: $("#credit_card_number").val(),
expMonth: $("#_expiry_date_2i").val(),
expYear: $("#_expiry_date_1i").val(),
cvc: $("#cvv").val()
};
Stripe.createToken(card, function(status, response) {
if (status === 200) {
$("#user_last_4_digits").val(response.card.last4);
$("#user_stripe_token").val(response.id);
form.submit();
} else {
$("#stripe-error-message").text(response.error.message);
$("#credit-card-errors").show();
$("#user_submit").attr("disabled", false);
}
});
return false;
});
$("#change-card a").click(function() {
$("#change-card").hide();
$("#credit-card").show();
$("#credit_card_number").focus();
return false;
});
});
|
Refactor formatting of save name. | import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
fmt = fmt if fmt is not None else 'png'
if isinstance(fmt, basestring):
fmt = [fmt]
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savepath = os.path.join(directory, filename)
for a_fmt in fmt:
savename = '%s.%s' % (savepath, a_fmt)
plt.savefig(savename)
print("Saved '%s'" % savename)
except(IndexError):
pass
| import os
import matplotlib.pyplot as plt
def save_all_figs(directory='./', fmt=None, default_name='untitled%i'):
"""Save all open figures.
Each figure is saved with the title of the plot, if possible.
Parameters
------------
directory : str
Path where figures are saved.
fmt : str, list of str
Image format(s) of saved figures. If None, default to rc parameter
'savefig.extension'.
default_name : str
Default filename to use if plot has no title. Must contain '%i' for the
figure number.
Examples
--------
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
for fignum in plt.get_fignums():
try:
filename = plt.figure(fignum).get_axes()[0].get_title()
if filename == '':
filename = default_name % fignum
savename = os.path.join(directory, filename)
if fmt is None:
fmt = plt.rcParams.get('savefig.extension','png')
if isinstance(fmt, basestring):
fmt = [fmt]
for a_fmt in fmt:
plt.savefig(savename + '.' + a_fmt)
print ('Saved \'%s\' '% (savename + '.' + a_fmt))
except(IndexError):
pass
|
Add title to the site | <!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.lawniczak.me/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//stats.lawniczak.me/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
<title>ekosme.me</title>
@yield('head')
</head>
<body>
<div class="container">
@yield('content')
</div>
@include('analytics')
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!-- Piwik -->
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.lawniczak.me/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', 1]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//stats.lawniczak.me/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
@yield('head')
</head>
<body>
<div class="container">
@yield('content')
</div>
@include('analytics')
</body>
</html>
|
Tag parser now instruct the issue as related to metadata | package alien4cloud.tosca.parser.impl.advanced;
import java.util.List;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import alien4cloud.model.common.Tag;
import alien4cloud.tosca.parser.ParserUtils;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Lists;
@Component
public class TagParser extends DefaultParser<List<Tag>> {
@Override
public List<Tag> parse(Node node, ParsingContextExecution context) {
List<Tag> tagList = Lists.newArrayList();
if (node instanceof MappingNode) {
MappingNode mapNode = (MappingNode) node;
for (NodeTuple entry : mapNode.getValue()) {
String key = ParserUtils.getScalar(entry.getKeyNode(), context);
String value = ParserUtils.getScalar(entry.getValueNode(), context);
if (value != null) {
tagList.add(new Tag(key, value));
}
}
} else {
ParserUtils.addTypeError(node, context.getParsingErrors(), "metadata");
}
return tagList;
}
} | package alien4cloud.tosca.parser.impl.advanced;
import java.util.List;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import alien4cloud.model.common.Tag;
import alien4cloud.tosca.parser.ParserUtils;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Lists;
@Component
public class TagParser extends DefaultParser<List<Tag>> {
@Override
public List<Tag> parse(Node node, ParsingContextExecution context) {
List<Tag> tagList = Lists.newArrayList();
if (node instanceof MappingNode) {
MappingNode mapNode = (MappingNode) node;
for (NodeTuple entry : mapNode.getValue()) {
String key = ParserUtils.getScalar(entry.getKeyNode(), context);
String value = ParserUtils.getScalar(entry.getValueNode(), context);
if (value != null) {
tagList.add(new Tag(key, value));
}
}
} else {
ParserUtils.addTypeError(node, context.getParsingErrors(), "Alien Tag");
}
return tagList;
}
} |
Send state when dispatched 'JUMP_TO_STATE' | export default function createDevToolsStore(onDispatch) {
const initialState = {
actionsById: {},
computedStates: [],
currentStateIndex: -1,
monitorState: {},
nextActionId: 0,
skippedActionIds: [],
stagedActionIds: []
};
let currentState = [];
let listeners = [];
let initiated = false;
let instance;
function dispatch(action) {
if (action.type[0] !== '@') {
if (action.type === 'JUMP_TO_STATE') {
let state = getState();
onDispatch(action, instance, state.computedStates[action.index].state);
setState({ ...state, currentStateIndex: action.index }, instance);
} else onDispatch(action, instance);
}
return action;
}
function getState() {
return (
(instance ? currentState[instance] : initialState) || initialState
);
}
function getInitialState() {
return initialState;
}
function isSet() {
return initiated;
}
function setState(state, id) {
const isNew = !currentState[id];
currentState[id] = state;
listeners.forEach(listener => listener());
initiated = true;
return isNew;
}
function setInstance(id) {
instance = id;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
dispatch,
getState,
subscribe,
liftedStore: {
dispatch,
getInitialState,
getState,
setState,
setInstance,
subscribe,
isSet
}
};
}
| export default function createDevToolsStore(onDispatch) {
const initialState = {
actionsById: {},
computedStates: [],
currentStateIndex: -1,
monitorState: {},
nextActionId: 0,
skippedActionIds: [],
stagedActionIds: []
};
let currentState = [];
let listeners = [];
let initiated = false;
let instance;
function dispatch(action) {
if (action.type[0] !== '@') {
if (action.type === 'JUMP_TO_STATE') {
let state = getState();
onDispatch(action, instance, state.computedStates[action.index]);
setState({ ...state, currentStateIndex: action.index }, instance);
} else onDispatch(action, instance);
}
return action;
}
function getState() {
return (
(instance ? currentState[instance] : initialState) || initialState
);
}
function getInitialState() {
return initialState;
}
function isSet() {
return initiated;
}
function setState(state, id) {
const isNew = !currentState[id];
currentState[id] = state;
listeners.forEach(listener => listener());
initiated = true;
return isNew;
}
function setInstance(id) {
instance = id;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
dispatch,
getState,
subscribe,
liftedStore: {
dispatch,
getInitialState,
getState,
setState,
setInstance,
subscribe,
isSet
}
};
}
|
Create key if not exists. | <?php
namespace App\Http\Services;
use App\Hospital;
use Illuminate\Database\Eloquent\Collection;
use App\Key;
class KeyService
{
public function generateKey(): string
{
return chr(mt_rand(ord( 'a' ), ord( 'z' ))) . substr(md5(time()), 1);
}
public function saveKey(string $key): ?Key
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
$instance = new Key(['secret' => $key]);
$instance->save();
}
return $instance;
}
public function deleteKey(string $key)
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
return ['error' => 404];
}
if (!$instance->delete()) {
return ['error' => 500];
}
return ['error' => true];
}
public function createLevel(string $key, string $level)
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
$instance = new Key(['secret' => $key]);
}
$instance->level = $level;
$instance->save();
return $instance;
}
} | <?php
namespace App\Http\Services;
use App\Hospital;
use Illuminate\Database\Eloquent\Collection;
use App\Key;
class KeyService
{
public function generateKey(): string
{
return chr(mt_rand(ord( 'a' ), ord( 'z' ))) . substr(md5(time()), 1);
}
public function saveKey(string $key): ?Key
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
$instance = new Key(['secret' => $key]);
$instance->save();
}
return $instance;
}
public function deleteKey(string $key)
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
return ['error' => 404];
}
if (!$instance->delete()) {
return ['error' => 500];
}
return ['error' => true];
}
public function createLevel(string $key, string $level)
{
$instance = Key::where('secret', $key)->first();
if (!$instance) {
return null;
}
$instance->level = $level;
$instance->save();
return $instance;
}
} |
Move 'me' check outside of author lookup | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':
user = get_current_user()
if user is None:
return
return Author.query.filter_by(email=user.email).first()
return Author.query.get(author_id)
def get(self, author_id):
if author_id == 'me' and not get_current_user():
return '', 401
author = self._get_author(author_id)
if not author:
return self.respond([])
queryset = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
joinedload('source'),
).filter(
Build.author_id == author.id,
).order_by(Build.date_created.desc(), Build.date_started.desc())
return self.paginate(queryset)
def get_stream_channels(self, author_id):
author = self._get_author(author_id)
if not author:
return []
return ['authors:{0}:builds'.format(author.id.hex)]
| from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':
user = get_current_user()
if user is None:
return
return Author.query.filter_by(email=user.email).first()
return Author.query.get(author_id)
def get(self, author_id):
author = self._get_author(author_id)
if not author:
if author_id == 'me':
return '', 401
return self.respond([])
queryset = Build.query.options(
joinedload('project', innerjoin=True),
joinedload('author'),
joinedload('source'),
).filter(
Build.author_id == author.id,
).order_by(Build.date_created.desc(), Build.date_started.desc())
return self.paginate(queryset)
def get_stream_channels(self, author_id):
author = self._get_author(author_id)
if not author:
return []
return ['authors:{0}:builds'.format(author.id.hex)]
|
Add dummy attribute to drawable node | package gui;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* Created by TUDelft SID on 17-5-2017.
*/
public class DrawableNode {
private static final int ARC_SIZE = 10;
private static GraphicsContext gc;
private int id;
private double xCoordinate;
private double yCoordinate;
private double width;
private double height;
private boolean highlighted;
private boolean isDummy;
public DrawableNode (int id, GraphicsContext gc) {
this.gc = gc;
this.id = id;
}
public void setCoordinates(double x, double y, double width, double height) {
this.xCoordinate = x;
this.yCoordinate = y;
this.width = width;
this.height = height;
}
public int getId() {
return this.id;
}
public boolean isDummy() {
return isDummy;
}
public void setDummy(boolean dummy) {
isDummy = dummy;
}
public void highlight() {
this.highlighted = true;
draw();
}
public void lowlight() {
this.highlighted = false;
draw();
}
public void draw() {
if (highlighted) {
gc.setFill(Color.ORANGE);
} else {
gc.setFill(Color.BLUE);
}
gc.fillRoundRect(xCoordinate, yCoordinate, width, height, ARC_SIZE, ARC_SIZE);
}
public boolean checkClick(double xEvent, double yEvent) {
return (xEvent > xCoordinate && xEvent < xCoordinate + width && yEvent > yCoordinate && yEvent < yCoordinate + height);
}
}
| package gui;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* Created by TUDelft SID on 17-5-2017.
*/
public class DrawableNode {
private static final int ARC_SIZE = 10;
private static GraphicsContext gc;
private int id;
private double xCoordinate;
private double yCoordinate;
private double width;
private double height;
private boolean highlighted;
public DrawableNode (int id, GraphicsContext gc) {
this.gc = gc;
this.id = id;
}
public void setCoordinates(double x, double y, double width, double height) {
this.xCoordinate = x;
this.yCoordinate = y;
this.width = width;
this.height = height;
}
public int getId() {
return this.id;
}
public void highlight() {
this.highlighted = true;
draw();
}
public void lowlight() {
this.highlighted = false;
draw();
}
public void draw() {
if (highlighted) {
gc.setFill(Color.ORANGE);
} else {
gc.setFill(Color.BLUE);
}
gc.fillRoundRect(xCoordinate, yCoordinate, width, height, ARC_SIZE, ARC_SIZE);
}
public boolean checkClick(double xEvent, double yEvent) {
return (xEvent > xCoordinate && xEvent < xCoordinate + width && yEvent > yCoordinate && yEvent < yCoordinate + height);
}
}
|
Test reaching end of stack |
/*
* composable-middleware
* https://github.com/randymized/composable-middleware
*
* Copyright (c) 2013 Randy McLaughlin
* Licensed under the MIT license.
*/
'use strict';
module.exports= function composable_middleware(components) {
var stack= [];
function middleware(req,res,out) {
var layer= 0;
var stacklength= stack.length;
(function next(err) {
var fn= stack[layer++];
if (fn == null) {
return out(err);
}
else {
if (err) {
if (fn.length == 4) {
fn(err,req,res,next);
}
else {
next(err);
}
}
else {
if (fn.length == 3) {
fn(req,res,next);
}
else {
next();
}
}
}
})()
}
var use= middleware.use= function(mw) {
for (var i=0, len=arguments.length; i<len; i++) {
var a= arguments[i];
if (Array.isArray(a)) {
use.apply(this,a)
}
else if (typeof a === 'function' && (a.length === 3 || a.length === 4)){
stack.push(a);
}
else {
throw new TypeError('Middleware function was expected');
}
}
return middleware;
}
use.apply(middleware,arguments);
return middleware;
}
|
/*
* composable-middleware
* https://github.com/randymized/composable-middleware
*
* Copyright (c) 2013 Randy McLaughlin
* Licensed under the MIT license.
*/
'use strict';
module.exports= function composable_middleware(components) {
var stack= [];
function middleware(req,res,out) {
var layer= 0;
var stacklength= stack.length;
(function next(err) {
var fn= stack[layer++];
if (!fn) {
return out(err);
}
else {
if (err) {
if (fn.length == 4) {
fn(err,req,res,next);
}
else {
next(err);
}
}
else {
if (fn.length == 3) {
fn(req,res,next);
}
else {
next();
}
}
}
})()
}
var use= middleware.use= function(mw) {
for (var i=0, len=arguments.length; i<len; i++) {
var a= arguments[i];
if (Array.isArray(a)) {
use.apply(this,a)
}
else if (typeof a === 'function' && (a.length === 3 || a.length === 4)){
stack.push(a);
}
else {
throw new TypeError('Middleware function was expected');
}
}
return middleware;
}
use.apply(middleware,arguments);
return middleware;
}
|
Update header of beatmapset discussion votes | {{--
Copyright (c) ppy Pty Ltd <[email protected]>.
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/>.
--}}
@extends('master', ['legacyNav' => false])
{{-- FIXME: move to user modding history --}}
@section('content')
@include('layout._page_header_v4', ['params' => [
'section' => trans('layout.header.beatmapsets._'),
'subSection' => trans('beatmapset_discussion_votes.index.title'),
]])
<div class="osu-page osu-page--generic">
<div class="beatmapset-activities">
@if (isset($user))
<h2>{{ trans('users.beatmapset_activities.title', ['user' => $user->username]) }}</h2>
@endif
@foreach ($votes as $vote)
@include('beatmapset_discussion_votes._item', compact('vote'))
@endforeach
@include('objects._pagination_v2', ['object' => $votes])
</div>
</div>
@endsection
| {{--
Copyright (c) ppy Pty Ltd <[email protected]>.
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/>.
--}}
@extends('master')
{{-- FIXME: move to user modding history --}}
@section('content')
<div class="osu-layout__row osu-layout__row--page">
<div class="beatmapset-activities">
@if (isset($user))
<h2>{{ trans('users.beatmapset_activities.title', ['user' => $user->username]) }}</h2>
@endif
<h3>{{ trans('beatmapset_discussion_votes.index.title') }}</h3>
@foreach ($votes as $vote)
@include('beatmapset_discussion_votes._item', compact('vote'))
@endforeach
@include('objects._pagination_v2', ['object' => $votes])
</div>
</div>
@endsection
|
Fix code error in template | import ATV from 'atvjs';
// templates
import listTemplate from './templates/list.jade';
let myPageStyles = `
.text-bold {
font-weight: bold;
}
.text-white {
color: rgb(255, 255, 255);
}
`;
App.onLaunch = function (options) {
var demoPage = ATV.Page.create({
name: 'demo',
style: myPageStyles,
template: listTemplate,
data: {
title: 'Demo',
results: [
{
id: 1,
style: '',
title: 'First item',
preview: {
url: '',
style: '',
title:'First Preview'
}
}
]
}
});
// create menu page
ATV.Menu.create({
// any attributes that you want to set on the root level menuBar element of TVML
attributes: {},
// array of menu item configurations
items: [{
id: 'top',
name: 'Top'
}, {
id: 'demo',
name: 'Demo',
page: demoPage
}]
});
ATV.Navigation.navigateToMenuPage();
};
App.onWillResignActive = function() {
}
App.onDidEnterBackground = function() {
}
App.onWillEnterForeground = function() {
}
App.onDidBecomeActive = function() {
}
App.onWillTerminate = function() {
}
| import ATV from 'atvjs';
// templates
import listTemplate from './templates/list.jade';
let myPageStyles = `
.text-bold {
font-weight: bold;
}
.text-white {
color: rgb(255, 255, 255);
}
`;
App.onLaunch = function (options) {
var demoPage = ATV.Page.create({
name: 'demo',
style: myPageStyles,
template: listTemplate,
data: {
title: 'Demo',
results: [
{
id: 1,
style: '',
title: 'First item',
preview: {
url: ''
style: ''
title:'First Preview'
}
}
]
}
});
// create menu page
ATV.Menu.create({
// any attributes that you want to set on the root level menuBar element of TVML
attributes: {},
// array of menu item configurations
items: [{
id: 'top',
name: 'Top'
}, {
id: 'demo',
name: 'Demo',
page: demoPage
}]
});
ATV.Navigation.navigateToMenuPage();
};
App.onWillResignActive = function() {
}
App.onDidEnterBackground = function() {
}
App.onWillEnterForeground = function() {
}
App.onDidBecomeActive = function() {
}
App.onWillTerminate = function() {
}
|
Allow adding extra form-data to FileUpload component | define([
'require',
'../inheritance',
'../component',
'../event',
'../view',
'../collections',
'../network',
'!fileupload.css',
'!fileupload.html'
],function(require,inheritance,component,event,element,collections,network){
var factory = component.ComponentFactory(require,{
});
var collection = collections.collection;
var FileUpload = inheritance.Class(function FileUpload(){
this._extraFormData = {};
}).extend(component.ComponentBase);
FileUpload.prototype.onInit = function(args){
this.action = args.action;
};
FileUpload.prototype.onLoaded = function(){
};
FileUpload.prototype.append = function(name, value){
this._extraFormData[name] = value;
};
FileUpload.prototype.upload = function(){
// build form data
var files = this.elements.fileSelector.node.files;
var formData = new FormData();
collection(files).forEach(function(file){
formData.append('files',file,file.name)
});
collection(this._extraFormData).forEach(function(value,key){
formData.append(key, value);
});
var _this = this;
return new Promise(function(resolve, reject){
network.http.post({
url:_this.action,
data:formData
})({
ok:function(result){
resolve(result);
},
fail:function(result){
reject(result);
}
});
});
};
FileUpload.Component = factory.define('FileUpload:fileupload.html', FileUpload);
return FileUpload;
}); | define([
'require',
'../inheritance',
'../component',
'../event',
'../view',
'../collections',
'../network',
'!fileupload.css',
'!fileupload.html'
],function(require,inheritance,component,event,element,collections,network){
var factory = component.ComponentFactory(require,{
});
var collection = collections.collection;
var FileUpload = inheritance.Class(function FileUpload(){
}).extend(component.ComponentBase);
FileUpload.prototype.onInit = function(args){
this.action = args.action;
};
FileUpload.prototype.onLoaded = function(){
};
FileUpload.prototype.upload = function(){
// build form data
var files = this.elements.fileSelector.node.files;
var formData = new FormData();
collection(files).forEach(function(file){
formData.append('files',file,file.name)
});
var _this = this;
return new Promise(function(resolve, reject){
network.http.post({
url:_this.action,
data:formData
})({
ok:function(result){
resolve(result);
},
fail:function(result){
reject(result);
}
});
});
};
FileUpload.Component = factory.define('FileUpload:fileupload.html', FileUpload);
return FileUpload;
}); |
Add a function to write a sequence of nodes into a file | from graph import Graph
class Writer:
'''
Write a graph or a list of nodes into a file.
'''
def write_blossom_iv(self, graph, file_location):
'''
Write a graph to a file, use the blossom IV format
@type: graph: graph
@param: graph: graph that should be written to file
@type: file_location: string
@param: location to save the file
'''
f = open(file_location, 'w')
# write number of nodes and edges
print('{0} {1}'.format(graph.size, graph.edge_count), file=f)
# write and edge on every line
# ID node_1 node_2 weight
#TODO: Use a more generic solution, do not just print odd_node_nr
for node in graph.nodes:
for neighbour in graph.neighbour_nodes(node):
edge_list = graph.edge_by_nodes(node, neighbour)
for edge in edge_list:
print('{0} {1} {2}' \
.format(node.odd_node_nr, neighbour.odd_node_nr,
edge.weight), \
file=f)
f.close()
def write_nodes(self, nodes, file_location):
'''
Writes a list of nodes into a file with their x and y coordinates
@type nodes: list
@param: nodes: a list of nodes.
@type file_location: string
@param: location to save the file
'''
f = open(file_location, 'w')
for node in nodes:
print('{0} {1} {2}'.format(node.label, node.x, node.y), file=f)
f.close()
| from graph import Graph
class Writer:
'''
Write a graph into file.
'''
def write_blossom_iv(self, graph, file_location):
'''
Write a graph to a file, use the blossom IV format
@type: graph: graph
@param: graph: graph that should be written to file
@type: file_location: string
@param: string that contains the file location
@rtype: boolean
@return: True, if the file was written successfully and False if
someting went wrong
'''
f = open(file_location, 'w')
# write number of nodes and edges
print('{0} {1}'.format(graph.size, graph.edge_count), file=f)
# write and edge on every line
# ID node_1 node_2 weight
#TODO: Use a more generic solution, do not just print odd_node_nr
for node in graph.nodes:
for neighbour in graph.neighbour_nodes(node):
edge_list = graph.edge_by_nodes(node, neighbour)
for edge in edge_list:
print('{0} {1} {2}' \
.format(node.odd_node_nr, neighbour.odd_node_nr,
edge.weight), \
file=f)
|
Change anonymous response transformation function to a reusable named function
- This function always does the same, but was implemented twice (duplicate
code is eeevil!).
- In addition, fixed a bug causing the function to fail when the server
response is not successful. | (function() {
'use strict';
angular.module('app.feature.weather').factory('_owmWeatherFactory', [
'$log', '$resource', 'WEATHER_SETTINGS',
function($log, $resource, weatherSettings) {
var owmSettings = weatherSettings.OPEN_WEATHER_MAP;
var _dateTimeReviver = function(key, value) {
if (angular.isNumber(value) && (key === 'dt' || key === 'sunrise' || key === 'sunset')) {
// NOTE: DateTime is a unix timestamp in seconds, so multiply with 1000 to get milliseconds
return new Date(value * 1000);
}
return value;
};
var transformResponse = function(data) {
return angular.isString(data) && data !== '' ? JSON.parse(data, _dateTimeReviver) : {};
};
return $resource(owmSettings.BASE_URI + '/:intent/:subIntent', {
id: owmSettings.CITY_ID,
units: owmSettings.UNITS,
lang: owmSettings.LANGUAGE_ID,
appid: owmSettings.API_KEY
}, {
getWeatherInfo: {
method: 'GET',
params: {
intent: 'weather'
},
isArray: false,
transformResponse: transformResponse
},
getWeatherForecast: {
method: 'GET',
params: {
intent: 'forecast',
subIntent: 'daily',
cnt: 5
},
isArray: false,
transformResponse: transformResponse
}
});
}
]);
})();
| (function() {
'use strict';
angular.module('app.feature.weather').factory('_owmWeatherFactory', [
'$log', '$resource', 'WEATHER_SETTINGS',
function($log, $resource, weatherSettings) {
var owmSettings = weatherSettings.OPEN_WEATHER_MAP;
var _dateTimeReviver = function(key, value) {
if (angular.isNumber(value) && (key === 'dt' || key === 'sunrise' || key === 'sunset')) {
// NOTE: DateTime is a unix timestamp in seconds, so multiply with 1000 to get milliseconds
return new Date(value * 1000);
}
return value;
};
return $resource(owmSettings.BASE_URI + '/:intent/:subIntent', {
id: owmSettings.CITY_ID,
units: owmSettings.UNITS,
lang: owmSettings.LANGUAGE_ID,
appid: owmSettings.API_KEY
}, {
getWeatherInfo: {
method: 'GET',
params: {
intent: 'weather'
},
isArray: false,
transformResponse: function(data) {
return JSON.parse(data, _dateTimeReviver);
}
},
getWeatherForecast: {
method: 'GET',
params: {
intent: 'forecast',
subIntent: 'daily',
cnt: 5
},
isArray: false,
transformResponse: function(data) {
return JSON.parse(data, _dateTimeReviver);
}
}
});
}
]);
})();
|
Add test for round tripping via chronicle indexed. | package vanilla.java.echo;
import net.openhft.affinity.AffinityLock;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.ExcerptTailer;
import java.io.IOException;
public class QueueServerMain {
public static void main(String... args) throws IOException {
String host = args[0];
Chronicle inbound = ChronicleQueueBuilder
.indexed("/tmp/server-inbound")
.sink().connectAddress(host, 54001)
.build();
ExcerptTailer tailer = inbound.createTailer().toEnd();
Chronicle outbound = ChronicleQueueBuilder
.indexed("/tmp/server-outbound")
.source().bindAddress(54002)
.build();
ExcerptAppender appender = outbound.createAppender();
if (!host.equals("localhost"))
AffinityLock.acquireLock();
long count = 0, next = 1000000;
while (true) {
if (tailer.nextIndex()) {
appender.startExcerpt();
appender.write(tailer);
appender.finish();
count++;
/*
System.out.print(".");
if ((count & 127) == 0)
System.out.println();
*/
} else {
if (count >= next)
System.out.println(count);
next += 1000000;
}
}
}
}
| package vanilla.java.echo;
import net.openhft.affinity.AffinityLock;
import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.ExcerptTailer;
import java.io.IOException;
public class QueueServerMain {
public static void main(String... args) throws IOException {
String host = args[0];
if (!host.equals("localhost"))
AffinityLock.acquireLock();
Chronicle inbound = ChronicleQueueBuilder
.indexed("/tmp/server-inbound")
.sink().connectAddress(host, 54001)
.build();
ExcerptTailer tailer = inbound.createTailer().toEnd();
Chronicle outbound = ChronicleQueueBuilder
.indexed("/tmp/server-outbound")
.source().bindAddress(54002)
.build();
ExcerptAppender appender = outbound.createAppender();
long count = 0, next = 1000000;
while (true) {
if (tailer.nextIndex()) {
appender.startExcerpt();
appender.write(tailer);
appender.finish();
count++;
/*
System.out.print(".");
if ((count & 127) == 0)
System.out.println();
*/
} else {
if (count >= next)
System.out.println(count);
next += 1000000;
}
}
}
}
|
Test PrintReport with a real stream | import sys
import unittest
from mock import MagicMock
from chainer import testing
from chainer.training import extensions
class TestPrintReport(unittest.TestCase):
def _setup(self, stream=None, delete_flush=False):
self.logreport = MagicMock(spec=extensions.LogReport(
['epoch'], trigger=(1, 'iteration'), log_name=None))
if stream is None:
self.stream = MagicMock()
if delete_flush:
del self.stream.flush
else:
self.stream = stream
self.report = extensions.PrintReport(
['epoch'], log_report=self.logreport, out=self.stream)
self.trainer = testing.get_trainer_with_mock_updater(
stop_trigger=(1, 'iteration'))
self.trainer.extend(self.logreport)
self.trainer.extend(self.report)
self.logreport.log = [{'epoch': 0}]
def test_stream_with_flush_is_flushed(self):
self._setup(delete_flush=False)
self.assertTrue(hasattr(self.stream, 'flush'))
self.stream.flush.assert_not_called()
self.report(self.trainer)
self.stream.flush.assert_called_with()
def test_stream_without_flush_raises_no_exception(self):
self._setup(delete_flush=True)
self.assertFalse(hasattr(self.stream, 'flush'))
self.report(self.trainer)
def test_real_stream_raises_no_exception(self):
self._setup(stream=sys.stderr)
self.report(self.trainer)
testing.run_module(__name__, __file__)
| import sys
import unittest
from mock import MagicMock
from chainer import testing
from chainer.training import extensions
class TestPrintReport(unittest.TestCase):
def _setup(self, delete_flush=False):
self.logreport = MagicMock(spec=extensions.LogReport(
['epoch'], trigger=(1, 'iteration'), log_name=None))
self.stream = MagicMock()
if delete_flush:
del self.stream.flush
self.report = extensions.PrintReport(
['epoch'], log_report=self.logreport, out=self.stream)
self.trainer = testing.get_trainer_with_mock_updater(
stop_trigger=(1, 'iteration'))
self.trainer.extend(self.logreport)
self.trainer.extend(self.report)
self.logreport.log = [{'epoch': 0}]
def test_stream_with_flush_is_flushed(self):
self._setup(delete_flush=False)
self.assertTrue(hasattr(self.stream, 'flush'))
self.stream.flush.assert_not_called()
self.report(self.trainer)
self.stream.flush.assert_called_with()
def test_stream_without_flush_raises_no_exception(self):
self._setup(delete_flush=True)
self.assertFalse(hasattr(self.stream, 'flush'))
self.report(self.trainer)
testing.run_module(__name__, __file__)
|
Add tabId to test-app serverInfo | if (Meteor.isClient) {
var Info = new Mongo.Collection("info");
var Counter = new Mongo.Collection("counter");
Template.hello.onCreated(function () {
Meteor.subscribe("info");
Meteor.subscribe("counter");
});
Template.hello.helpers({
counter: function () {
if (!Template.instance().subscriptionsReady()) return "not ready";
return Counter.findOne("counter").counter;
},
serverInfo: function () {
var obj = Info.findOne("info");
console.log("server", Meteor.loggingIn && Meteor.loggingIn(), obj);
return JSON.stringify(obj, null, 2);
},
clientInfo: function () {
var obj = Meteor.sandstormUser();
console.log("client", Meteor.loggingIn && Meteor.loggingIn(), obj);
return JSON.stringify(obj, null, 2);
},
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.publish("info", function () {
var user = Meteor.users && this.userId && Meteor.users.findOne(this.userId);
this.added("info", "info", {userId: this.userId, user: user, sandstormUser: this.connection.sandstormUser(),
sessionId: this.connection.sandstormSessionId(),
tabId: this.connection.sandstormTabId()});
this.ready();
});
var counter = 0;
Meteor.publish("counter", function () {
this.added("counter", "counter", {counter: counter++});
this.ready();
});
}
| if (Meteor.isClient) {
var Info = new Mongo.Collection("info");
var Counter = new Mongo.Collection("counter");
Template.hello.onCreated(function () {
Meteor.subscribe("info");
Meteor.subscribe("counter");
});
Template.hello.helpers({
counter: function () {
if (!Template.instance().subscriptionsReady()) return "not ready";
return Counter.findOne("counter").counter;
},
serverInfo: function () {
var obj = Info.findOne("info");
console.log("server", Meteor.loggingIn && Meteor.loggingIn(), obj);
return JSON.stringify(obj, null, 2);
},
clientInfo: function () {
var obj = Meteor.sandstormUser();
console.log("client", Meteor.loggingIn && Meteor.loggingIn(), obj);
return JSON.stringify(obj, null, 2);
},
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.publish("info", function () {
var user = Meteor.users && this.userId && Meteor.users.findOne(this.userId);
this.added("info", "info", {userId: this.userId, user: user, sandstormUser: this.connection.sandstormUser(),
sessionId: this.connection.sandstormSessionId()});
this.ready();
});
var counter = 0;
Meteor.publish("counter", function () {
this.added("counter", "counter", {counter: counter++});
this.ready();
});
}
|
Fix for os.path.join with model_id, was breaking on non-string model_id values. | import os
import requests
class LumidatumClient(object):
def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'):
self.authentication_token = authentication_token
self.model_id = str(model_id)
self.host_address = host_address
def getRecommendations(self, parameters, model_id=None):
"""
Get recommendations for a model specified by model_id.
Returns a list of id/score pairs in descending order from the highest score.
"""
selected_model_id = str(model_if) if model_id else self.model_id
if selected_model_id is None:
raise ValueError('model_id must be specified either at initialization of LumidatumClient or in client method call.')
headers = {
'Authorization': self.authentication_token,
'content-type': 'application/json',
}
response = requests.post(
os.path.join(self.host_address, 'api/predict', selected_model_id),
parameters,
headers=headers
)
return response.json()
def getRecommendationDescriptions(self, parameters, model_id=None):
"""
Get human readable recommendations.
"""
parameters['human_readable'] = True
return self.getRecommendations(self, parameters, model_id)
| import os
import requests
class LumidatumClient(object):
def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'):
self.authentication_token = authentication_token
self.model_id = model_id
self.host_address = host_address
def getRecommendations(self, parameters, model_id=None):
"""
Get recommendations for a model specified by model_id.
Returns a list of id/score pairs in descending order from the highest score.
"""
selected_model_id = model_if if model_id else self.model_id
if selected_model_id is None:
raise ValueError('model_id must be specified either at initialization of LumidatumClient or in client method call.')
headers = {
'Authorization': self.authentication_token,
'content-type': 'application/json',
}
response = requests.post(
os.path.join(self.host_address, 'api/predict', selected_model_id),
parameters,
headers=headers
)
return response.json()
def getRecommendationDescriptions(self, parameters, model_id=None):
"""
Get human readable recommendations.
"""
parameters['human_readable'] = True
return self.getRecommendations(self, parameters, model_id)
|
Change variable name consistently to pool_config | # pylint: disable=W0401
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.oracle.base import *
from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper
import cx_Oracle
class DatabaseWrapper(DjDatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
default_pool = {
'min': 1,
'max': 2,
'increment': 1,
}
pool_config = self.settings_dict.get('POOL', default_pool)
if set(pool_config.keys()) != {'min', 'max', 'increment'}:
raise ImproperlyConfigured('POOL database option requires \'min\', \'max\', and \'increment\'')
if not all(isinstance(val, int) for val in pool_config.values()):
raise ImproperlyConfigured('POOL database option values must be numeric')
self.pool = cx_Oracle.SessionPool(
user=self.settings_dict['USER'],
password=self.settings_dict['PASSWORD'],
dsn=self.settings_dict['NAME'], **pool_config)
def get_new_connection(self, conn_params):
conn_params.update({
'pool': self.pool,
})
return super(DatabaseWrapper, self).get_new_connection(conn_params)
def _close(self):
if self.connection is not None:
with self.wrap_database_errors:
return self.pool.release(self.connection)
| # pylint: disable=W0401
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.oracle.base import *
from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper
import cx_Oracle
class DatabaseWrapper(DjDatabaseWrapper):
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
default_pool = {
'min': 1,
'max': 2,
'increment': 1,
}
poolconfig = self.settings_dict.get('POOL', default_pool)
if set(pool_config.keys()) != {'min', 'max', 'increment'}:
raise ImproperlyConfigured('POOL database option requires \'min\', \'max\', and \'increment\'')
if not all(isinstance(val, int) for val in pool_config.values()):
raise ImproperlyConfigured('POOL database option values must be numeric')
self.pool = cx_Oracle.SessionPool(
user=self.settings_dict['USER'],
password=self.settings_dict['PASSWORD'],
dsn=self.settings_dict['NAME'], **poolconfig)
def get_new_connection(self, conn_params):
conn_params.update({
'pool': self.pool,
})
return super(DatabaseWrapper, self).get_new_connection(conn_params)
def _close(self):
if self.connection is not None:
with self.wrap_database_errors:
return self.pool.release(self.connection)
|
Update to use Session helper
Session no longer available with $request | <?php
/**
* Part of the CSCMS package by Coder Studios.
*
* NOTICE OF LICENSE
*
* Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
*
* @package CSCMS
* @version 1.0.0
* @author Coder Studios Ltd
* @license MIT https://opensource.org/licenses/MIT
* @copyright (c) 2017, Coder Studios Ltd
* @link https://www.coderstudios.com
*/
namespace CoderStudios\CSCMS\Middleware;
use Closure;
use Session;
use Illuminate\Contracts\Cache\Repository as Cache;
class ClearCache
{
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Cache\Repository $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
*/
public function handle($request, Closure $next)
{
if (!config('app.coderstudios.cache_enabled')) {
$this->cache->flush();
}
if (Session()->get('clear_cache')) {
$this->cache->flush();
Session()->remove('clear_cache');
}
return $next($request);
}
}
| <?php
/**
* Part of the CSCMS package by Coder Studios.
*
* NOTICE OF LICENSE
*
* Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
*
* @package CSCMS
* @version 1.0.0
* @author Coder Studios Ltd
* @license MIT https://opensource.org/licenses/MIT
* @copyright (c) 2017, Coder Studios Ltd
* @link https://www.coderstudios.com
*/
namespace CoderStudios\CSCMS\Middleware;
use Closure;
use Illuminate\Contracts\Cache\Repository as Cache;
class ClearCache
{
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Cache\Repository $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
*/
public function handle($request, Closure $next)
{
if (!config('app.coderstudios.cache_enabled')) {
$this->cache->flush();
}
if ($request->session()->get('clear_cache')) {
$this->cache->flush();
$request->session()->remove('clear_cache');
}
return $next($request);
}
}
|
Allow user-override of pcp config variable like PCP_TMP_DIR.
This is implemented in the same way that the PCP C code does - if
the same-named environment variable is set, use its value (and no
extra checking added). | package com.custardsource.parfait.dxm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.google.common.io.Closeables;
public class PcpConfig {
private final static String pcpConf = System.getenv("PCP_CONF");
private final static String pcpDir = System.getenv("PCP_DIR");
public File getRoot() {
return new File(pcpDir, "/");
}
private File getConfigFile() {
if (pcpConf == null) {
File etcDir = new File(getRoot(), "etc");
return new File(etcDir, "pcp.conf");
}
return new File(pcpConf);
}
public String getValue(String key) {
Properties properties = new Properties();
File configuration = getConfigFile();
InputStream is = null;
String value = System.getenv(key);
if (value != null) {
return value;
}
try {
is = new FileInputStream(configuration);
properties.load(is);
value = properties.get(key).toString();
} catch (FileNotFoundException e) {
} catch (IOException e) {
// just drop these, and go with defaults
}
finally {
Closeables.closeQuietly(is);
}
return value;
}
}
| package com.custardsource.parfait.dxm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.google.common.io.Closeables;
public class PcpConfig {
private final static String pcpConf = System.getenv("PCP_CONF");
private final static String pcpDir = System.getenv("PCP_DIR");
public File getRoot() {
return new File(pcpDir, "/");
}
private File getConfigFile() {
if (pcpConf == null) {
File etcDir = new File(getRoot(), "etc");
return new File(etcDir, "pcp.conf");
}
return new File(pcpConf);
}
public String getValue(String key) {
Properties properties = new Properties();
File configuration = getConfigFile();
InputStream is = null;
String value = null;
try {
is = new FileInputStream(configuration);
properties.load(is);
value = properties.get(key).toString();
} catch (FileNotFoundException e) {
} catch (IOException e) {
// just drop these, and go with defaults
}
finally {
Closeables.closeQuietly(is);
}
return value;
}
}
|
Fix expected PDF E2E warning count | package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
| package org.dita.dost;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.nio.file.Paths;
import static org.dita.dost.AbstractIntegrationTest.Transtype.*;
public class EndToEndTest extends AbstractIntegrationTest {
@Test
public void xhtml() throws Throwable {
builder().name("e2e")
.transtype(XHTML)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void html5() throws Throwable {
builder().name("e2e")
.transtype(HTML5)
.input(Paths.get("root.ditamap"))
.run();
}
@Test
public void pdf() throws Throwable {
builder().name("e2e")
.transtype(PDF)
.input(Paths.get("root.ditamap"))
.put("args.fo.userconfig", new File(resourceDir, "e2e" + File.separator + "fop.xconf").getAbsolutePath())
.warnCount(10)
.run();
}
@Test
public void eclipsehelp() throws Throwable {
builder().name("e2e")
.transtype(ECLIPSEHELP)
.input(Paths.get("root.ditamap"))
.run();
}
@Ignore
@Test
public void htmlhelp() throws Throwable {
builder().name("e2e")
.transtype(HTMLHELP)
.input(Paths.get("root.ditamap"))
.run();
}
}
|
Add validation state to story title component | import _ from 'lodash';
import React from 'react/addons';
const TITLE_ATTRS = {
who: {
title: "As an",
placeholder: "e.g. an accountant"
},
what: {
title: "I Want",
placeholder: "e.g. Quickbooks integration"
},
why: {
title: "so that",
placeholder: "e.g. I don't have to import CSV's daily"
}
};
const STORY_ATTRS = ['who', 'what', 'why'];
function toTitleCase(str) {
return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
}
let AddItemStoryTitle = React.createClass({
propTypes: {
who: React.PropTypes.object.isRequired,
what: React.PropTypes.object.isRequired,
why: React.PropTypes.object.isRequired,
validation: React.PropTypes.object.isRequired
},
titleNodes() {
return _.map(STORY_ATTRS, (attr) => {
var classes = React.addons.classSet({
"form-control": true,
'invalid': !this.props.validation.value[attr]
});
return (
<div className={`add-item__field ${attr}`}>
<span>{TITLE_ATTRS[attr].title}</span>
<div className="input-group">
<label>{toTitleCase(attr)}</label>
<input className={classes}
type="text"
name={attr}
placeholder={attr.placeholder}
valueLink={this.props[attr]} />
</div>
</div>
)
})
},
render() {
return (
<div className="form-group story-title">
{this.titleNodes()}
</div>
)
}
});
export default AddItemStoryTitle;
| import React from 'react/addons';
let AddItemStoryTitle = React.createClass({
propTypes: {
who: React.PropTypes.object.isRequired,
what: React.PropTypes.object.isRequired,
why: React.PropTypes.object.isRequired
},
render() {
return (
<div className="form-group story-title">
<div className="add-item__field who">
<span>As an</span>
<div className="input-group">
<label>Who</label>
<input className="form-control" type="text" name="who" placeholder="e.g. accountant" valueLink={this.props.who}/>
</div>
</div>
<div className="add-item__field what">
<span>I want</span>
<div className="input-group">
<label>What</label>
<input className="form-control" type="text" name="what" placeholder="e.g. Quickbooks integration" valueLink={this.props.what}/>
</div>
</div>
<div className="add-item__field why">
<span>so that</span>
<div className="input-group">
<label>Why</label>
<input className="form-control" type="text" name="what" placeholder="e.g. Quickbooks integration" valueLink={this.props.why}/>
</div>
</div>
</div>
)
}
});
export default AddItemStoryTitle;
|
Use proper divider for advisors selector buttons on mobile | <div class="box">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-question-circle"></i> Consult advisor</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.production') }}" class="btn btn-app btn-block">
<i class="fa fa-industry"></i> Production
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.military') }}" class="btn btn-app btn-block">
<i class="ra ra-sword"></i> Military
</a>
</div>
<div class="col-xs-12 visible-xs"> </div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.land') }}" class="btn btn-app btn-block">
<i class="ra ra-honeycomb"></i> Land
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.construction') }}" class="btn btn-app btn-block">
<i class="fa fa-home"></i> Construction
</a>
</div>
</div>
</div>
</div>
| <div class="box">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-question-circle"></i> Consult advisor</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.production') }}" class="btn btn-app btn-block">
<i class="fa fa-industry"></i> Production
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.military') }}" class="btn btn-app btn-block">
<i class="ra ra-sword"></i> Military
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.land') }}" class="btn btn-app btn-block">
<i class="ra ra-honeycomb"></i> Land
</a>
</div>
<div class="visible-xs"> </div>
<div class="col-xs-6 col-sm-3">
<a href="{{ route('dominion.advisors.construction') }}" class="btn btn-app btn-block">
<i class="fa fa-home"></i> Construction
</a>
</div>
</div>
</div>
</div>
|
Rename edit prop and add default value | import React from 'react';
import SchemaForm from './SchemaForm';
import SchemaFormUtil from '../utils/SchemaFormUtil';
const METHODS_TO_BIND = [
'handleFormChange',
'validateForm'
];
class JobForm extends SchemaForm {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
componentWillMount() {
this.multipleDefinition = this.getNewDefinition();
// On edit hide the id field.
if (this.props.isEdit) {
this.multipleDefinition.general.definition.forEach(function (definition) {
if (definition.name === 'id') {
definition.formElementClass = 'hidden';
}
});
}
this.props.getTriggerSubmit(this.handleExternalSubmit);
}
getDataTriple() {
let model = this.triggerTabFormSubmit();
return {
model: SchemaFormUtil.processFormModel(model, this.multipleDefinition)
};
}
validateForm() {
// TODO: Overwrite the default behaviour until DCOS-7669 is fixed.
return true;
}
}
JobForm.defaultProps = {
className: 'multiple-form row',
getTriggerSubmit: function () {},
isEdit: false,
onChange: function () {},
schema: {}
};
JobForm.propTypes = {
className: React.PropTypes.string,
isEdit: React.PropTypes.bool,
getTriggerSubmit: React.PropTypes.func,
onChange: React.PropTypes.func,
schema: React.PropTypes.object
};
module.exports = JobForm;
| import React from 'react';
import SchemaForm from './SchemaForm';
import SchemaFormUtil from '../utils/SchemaFormUtil';
const METHODS_TO_BIND = [
'handleFormChange',
'validateForm'
];
class JobForm extends SchemaForm {
constructor() {
super();
METHODS_TO_BIND.forEach((method) => {
this[method] = this[method].bind(this);
});
}
componentWillMount() {
this.multipleDefinition = this.getNewDefinition();
// On edit hide the id field.
if (this.props.edit) {
this.multipleDefinition.general.definition.forEach(function (definition) {
if (definition.name === 'id') {
definition.formElementClass = 'hidden';
}
});
}
this.props.getTriggerSubmit(this.handleExternalSubmit);
}
getDataTriple() {
let model = this.triggerTabFormSubmit();
return {
model: SchemaFormUtil.processFormModel(model, this.multipleDefinition)
};
}
validateForm() {
// TODO: Overwrite the default behaviour until DCOS-7669 is fixed.
return true;
}
}
JobForm.defaultProps = {
className: 'multiple-form row',
getTriggerSubmit: function () {},
onChange: function () {},
schema: {}
};
JobForm.propTypes = {
className: React.PropTypes.string,
edit: React.PropTypes.bool,
getTriggerSubmit: React.PropTypes.func,
onChange: React.PropTypes.func,
schema: React.PropTypes.object
};
module.exports = JobForm;
|
Fix error in UT because of problem with merge conflicts | <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return [
$this->createHasHeyFunction(),
$this->createIsRecoverableFunction(),
];
}
/**
* @return ExpressionFunction
*/
protected function createHasHeyFunction()
{
return new ExpressionFunction(
'hasKey',
function ($key, $array) {
return sprintf('(array_key_exists(%s,%s))', $key, $array);
},
function ($arguments, $key, $array) {
if (!is_array($array)) {
throw new \RuntimeException('Second argument passed to "hasKey" should be an array.');
}
return array_key_exists($key, $array);
}
);
}
/**
* @return ExpressionFunction
*/
protected function createIsRecoverableFunction()
{
return new ExpressionFunction(
'isRecoverable',
function ($object) {
return sprintf('(%s instanceof \Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface)', $object);
},
function ($arguments, $object) {
if (!is_object($object) || !($object instanceof \Exception)) {
throw new \RuntimeException('First argument should be an exception');
}
return ($object instanceof RecoverableExceptionInterface);
}
);
}
}
| <?php
namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;
use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return [$this->createIsRecoverableFunction()];
}
/**
* @return ExpressionFunction
*/
protected function createHasHeyFunction()
{
return new ExpressionFunction(
'hasKey',
function ($key, $array) {
return sprintf('(array_key_exists(%s,%s))', $key, $array);
},
function ($arguments, $key, $array) {
if (!is_array($array)) {
throw new \RuntimeException('Second argument passed to "hasKey" should be an array.');
}
return array_key_exists($key, $array);
}
);
}
/**
* @return ExpressionFunction
*/
protected function createIsRecoverableFunction()
{
return new ExpressionFunction(
'isRecoverable',
function ($object) {
return sprintf('(%s instanceof \Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface)', $object);
},
function ($arguments, $object) {
if (!is_object($object) || !($object instanceof \Exception)) {
throw new \RuntimeException('First argument should be an exception');
}
return ($object instanceof RecoverableExceptionInterface);
}
);
}
}
|
Use the right port number
I find this makes all the difference... | import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myConfig = {
...config,
plugins: config.plugins.concat(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
),
};
webpack(myConfig, (err, stats) => {
if (err) {
throw new gutil.PluginError('webpack:build', err);
}
gutil.log('[webpack:build]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task('webpack-dev-server', callback => {
var myConfig = {
...config,
debug: true,
};
new WebpackDevServer(webpack(myConfig), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true,
},
}).listen(3000, 'localhost', err => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
gutil.log('[webpack-dev-server]', 'http://localhost:3000');
});
});
| import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myConfig = {
...config,
plugins: config.plugins.concat(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
),
};
webpack(myConfig, (err, stats) => {
if (err) {
throw new gutil.PluginError('webpack:build', err);
}
gutil.log('[webpack:build]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task('webpack-dev-server', callback => {
var myConfig = {
...config,
debug: true,
};
new WebpackDevServer(webpack(myConfig), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true,
},
}).listen(8080, 'localhost', err => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
gutil.log('[webpack-dev-server]', 'http://localhost:3000');
});
});
|
Add get_filter_set_kwargs for instanciating FilterSet with additional arguments | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_filter_set_kwargs(self):
"""
Returns the keyword arguments for instanciating the filterset.
"""
return {
'data': self.request.GET,
'queryset': self.get_base_queryset(),
}
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(**self.get_filter_set_kwargs())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
| from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(self.request.GET,
queryset=self.get_base_queryset())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
|
Fix detecting if timings are enabled | package com.github.games647.lagmonitor.command.timing;
import com.github.games647.lagmonitor.LagMonitor;
import com.github.games647.lagmonitor.command.LagCommand;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public abstract class TimingCommand extends LagCommand {
public TimingCommand(LagMonitor plugin) {
super(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!canExecute(sender, command)) {
return true;
}
if (!isTimingsEnabled()) {
sendError(sender,"The server deactivated timing reports");
sendError(sender,"Go to paper.yml or spigot.yml and activate timings");
return true;
}
sendTimings(sender);
return true;
}
protected abstract void sendTimings(CommandSender sender);
protected abstract boolean isTimingsEnabled();
protected String highlightPct(float percent, int low, int med, int high) {
ChatColor prefix = ChatColor.GRAY;
if (percent > high) {
prefix = ChatColor.DARK_RED;
} else if (percent > med) {
prefix = ChatColor.GOLD;
} else if (percent > low) {
prefix = ChatColor.YELLOW;
}
return prefix + String.valueOf(percent) + '%' + ChatColor.GRAY;
}
}
| package com.github.games647.lagmonitor.command.timing;
import com.github.games647.lagmonitor.LagMonitor;
import com.github.games647.lagmonitor.command.LagCommand;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public abstract class TimingCommand extends LagCommand {
public TimingCommand(LagMonitor plugin) {
super(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!canExecute(sender, command)) {
return true;
}
if (isTimingsEnabled()) {
sendError(sender,"The server deactivated timing reports");
sendError(sender,"Go to paper.yml or spigot.yml and activate timings");
return true;
}
sendTimings(sender);
return true;
}
protected abstract void sendTimings(CommandSender sender);
protected abstract boolean isTimingsEnabled();
protected String highlightPct(float percent, int low, int med, int high) {
ChatColor prefix = ChatColor.GRAY;
if (percent > high) {
prefix = ChatColor.DARK_RED;
} else if (percent > med) {
prefix = ChatColor.GOLD;
} else if (percent > low) {
prefix = ChatColor.YELLOW;
}
return prefix + String.valueOf(percent) + '%' + ChatColor.GRAY;
}
}
|
Subsets and Splits