text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Transform args into proper arrays
|
'use strict';
var Bluebird = require('bluebird');
var _path = require('path');
var redefine = require('redefine');
module.exports = redefine.Class({
constructor: function(path, options) {
this.path = _path.resolve(path);
this.file = _path.basename(this.path);
this.options = options;
},
migration: function () {
return require(this.path);
},
up: function () {
return this._exec('up', [].slice.apply(arguments));
},
down: function () {
return this._exec('down', [].slice.apply(arguments));
},
testFileName: function (needle) {
return this.file.indexOf(needle) === 0;
},
_exec: function (method, args) {
var migration = this.migration();
return (migration[method] || Bluebird.resolve).apply(migration, args);
}
});
|
'use strict';
var Bluebird = require('bluebird');
var _path = require('path');
var redefine = require('redefine');
module.exports = redefine.Class({
constructor: function(path, options) {
this.path = _path.resolve(path);
this.file = _path.basename(this.path);
this.options = options;
},
migration: function () {
return require(this.path);
},
up: function () {
return this._exec('up', arguments);
},
down: function () {
return this._exec('down', arguments);
},
testFileName: function (needle) {
return this.file.indexOf(needle) === 0;
},
_exec: function (method, args) {
var migration = this.migration();
return (migration[method] || Bluebird.resolve).apply(migration, args);
}
});
|
Use django.get_version in prerequisite checker
|
#!/usr/bin/env python
import sys
# Check that we are in an activated virtual environment
try:
import os
virtual_env = os.environ['VIRTUAL_ENV']
except KeyError:
print("It doesn't look like you are in an activated virtual environment.")
print("Did you make one?")
print("Did you activate it?")
sys.exit(1)
# Check that we have installed Django
try:
import django
except ImportError:
print("It doesn't look like Django is installed.")
print("Are you in an activated virtual environment?")
print("Did you pip install from requirements.txt?")
sys.exit(1)
# Check that we have the expected version of Django
expected_version = '1.7.1'
installed_version = django.get_version()
try:
assert installed_version == expected_version
except AssertionError:
print("It doesn't look like you have the expected version "
"of Django installed.")
print("You have {0}.".format(installed_version))
sys.exit(1)
# All good, have fun!
print("Everything looks okay to me... Have fun!")
|
#!/usr/bin/env python
import sys
# Check that we are in an activated virtual environment
try:
import os
virtual_env = os.environ['VIRTUAL_ENV']
except KeyError:
print("It doesn't look like you are in an activated virtual environment.")
print("Did you make one?")
print("Did you activate it?")
sys.exit(1)
# Check that we have installed Django
try:
import django
except ImportError:
print("It doesn't look like Django is installed.")
print("Are you in an activated virtual environment?")
print("Did you pip install from requirements.txt?")
sys.exit(1)
# Check that we have the expected version of Django
expected_version = (1, 7, 1)
try:
assert django.VERSION[:3] == expected_version
except AssertionError:
print("It doesn't look like you have the expected version "
"of Django installed.")
print("You have {0}".format('.'.join([str(i) for i in django.VERSION][:3])))
sys.exit(1)
# All good, have fun!
print("Everything looks okay to me... Have fun!")
|
Change on the regex variable such that it distinguish warnings from errors.
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""This module exports the Cppcheck plugin class."""
from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
"""Provides an interface to cppcheck."""
syntax = 'c++'
cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@')
regex = r'^.+:(?P<line>\d+):\s+((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+(?P<message>.+)'
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
tempfile_suffix = 'cpp'
defaults = {
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
inline_settings = 'std'
inline_overrides = 'enable'
comment_re = r'\s*/[/*]'
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""This module exports the Cppcheck plugin class."""
from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
"""Provides an interface to cppcheck."""
syntax = 'c++'
cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@')
regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)'
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
tempfile_suffix = 'cpp'
defaults = {
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
inline_settings = 'std'
inline_overrides = 'enable'
comment_re = r'\s*/[/*]'
|
Use $log instead of console and use angulars isObject method for typechecking
|
angular
.module('ngSharepoint')
.provider('$spLog', function($log) {
var prefix = '[ngSharepoint] ';
var enabled = true;
return {
setPrefix: function(prefix) {
this.prefix = '[' + prefix + '] ';
},
setEnabled: function(enabled) {
this.enabled = enabled;
},
$get: function() {
return ({
error: function(msg) {
if (enabled) {
if (angular.isObject(msg)) {
$log.error(prefix + 'Object: %O', msg);
}else {
$log.error(prefix + msg);
}
}
},
warn: function(msg) {
if (enabled) {
if (angular.isObject(msg)) {
$log.warn(prefix + 'Object: %O', msg);
}else {
$log.warn(prefix + msg);
}
}
},
log: function(msg) {
if (enabled) {
if (angular.isObject(msg)) {
$log.log(prefix + 'Object: %O', msg);
}else {
$log.log(prefix + msg);
}
}
}
});
}
};
});
|
angular
.module('ngSharepoint')
.provider('$spLog', function() {
var prefix = '[ngSharepoint] ';
var enabled = true;
return {
setPrefix: function(prefix) {
this.prefix = '[' + prefix + '] ';
},
setEnabled: function(enabled) {
this.enabled = enabled;
},
$get: function() {
return ({
error: function(msg) {
if (enabled) {
if (typeof msg === 'object') {
console.error(prefix + 'Object: %O', msg);
}else {
console.error(prefix + msg);
}
}
},
warn: function(msg) {
if (enabled) {
if (typeof msg === 'object') {
console.warn(prefix + 'Object: %O', msg);
}else {
console.warn(prefix + msg);
}
}
},
log: function(msg) {
if (enabled) {
if (typeof msg === 'object') {
console.log(prefix + 'Object: %O', msg);
}else {
console.log(prefix + msg);
}
}
}
});
}
};
});
|
Allow configuration of reviewers on project info screen
Change-Id: Ib529ce8b2593daba58a2c8f737a932323b2f9220
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.reviewers;
import com.google.gerrit.common.ChangeListener;
import com.google.gerrit.extensions.annotations.Exports;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.server.config.FactoryModule;
import com.google.gerrit.server.config.ProjectConfigEntry;
public class Module extends FactoryModule {
@Override
protected void configure() {
DynamicSet.bind(binder(), ChangeListener.class).to(
ChangeEventListener.class);
factory(DefaultReviewers.Factory.class);
bind(ProjectConfigEntry.class)
.annotatedWith(Exports.named("reviewers"))
.toInstance(
new ProjectConfigEntry("Reviewers", null,
ProjectConfigEntry.Type.ARRAY, null, false,
"Users or groups can be provided as reviewers"));
}
}
|
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.reviewers;
import com.google.gerrit.common.ChangeListener;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.server.config.FactoryModule;
public class Module extends FactoryModule {
@Override
protected void configure() {
DynamicSet.bind(binder(), ChangeListener.class).to(
ChangeEventListener.class);
factory(DefaultReviewers.Factory.class);
}
}
|
Add long description / url
|
#!/usr/bin/env python
import os
import setuptools
setuptools.setup(
name='remoteconfig',
version='0.2.4',
author='Max Zheng',
author_email='maxzheng.os @t gmail.com',
description='A simple wrapper for localconfig that allows for reading config from a remote server',
long_description=open('README.rst').read(),
url='https://github.com/maxzheng/remoteconfig',
install_requires=[
'localconfig>=0.4',
'requests',
],
license='MIT',
package_dir={'': 'src'},
packages=setuptools.find_packages('src'),
include_package_data=True,
setup_requires=['setuptools-git'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='configuration remote http config',
)
|
#!/usr/bin/env python
import os
import setuptools
setuptools.setup(
name='remoteconfig',
version='0.2.4',
author='Max Zheng',
author_email='maxzheng.os @t gmail.com',
description=open('README.rst').read(),
install_requires=[
'localconfig>=0.4',
'requests',
],
license='MIT',
package_dir={'': 'src'},
packages=setuptools.find_packages('src'),
include_package_data=True,
setup_requires=['setuptools-git'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Configuration',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='configuration remote http config',
)
|
Add configuration properties for legend title specifications.
|
import {GuideTitleStyle} from './constants';
import guideMark from './guide-mark';
import {lookup} from './guide-util';
import {TextMark} from '../marks/marktypes';
import {LegendTitleRole} from '../marks/roles';
import {addEncode, encoder} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter;
encode.enter = enter = {
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}},
opacity: zero
};
addEncode(enter, 'align', lookup('titleAlign', spec, config));
addEncode(enter, 'baseline', lookup('titleBaseline', spec, config));
addEncode(enter, 'fill', lookup('titleColor', spec, config));
addEncode(enter, 'font', lookup('titleFont', spec, config));
addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config));
addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config));
addEncode(enter, 'limit', lookup('titleLimit', spec, config));
encode.exit = {
opacity: zero
};
encode.update = {
opacity: {value: 1},
text: encoder(spec.title)
};
return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
}
|
import {GuideTitleStyle} from './constants';
import guideMark from './guide-mark';
import {TextMark} from '../marks/marktypes';
import {LegendTitleRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
title = spec.title,
encode = {}, enter;
encode.enter = enter = {
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}},
opacity: zero
};
addEncode(enter, 'align', config.titleAlign);
addEncode(enter, 'baseline', config.titleBaseline);
addEncode(enter, 'fill', config.titleColor);
addEncode(enter, 'font', config.titleFont);
addEncode(enter, 'fontSize', config.titleFontSize);
addEncode(enter, 'fontWeight', config.titleFontWeight);
addEncode(enter, 'limit', config.titleLimit);
encode.exit = {
opacity: zero
};
encode.update = {
opacity: {value: 1},
text: title && title.signal ? {signal: title.signal} : {value: title + ''}
};
return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
}
|
Allow dates in Datetime scalar
|
from __future__ import absolute_import
import datetime
try:
import iso8601
except:
raise ImportError("iso8601 package is required for DateTime Scalar.\nYou can install it using: pip install iso8601.")
from graphql.language import ast
from .scalars import Scalar
class DateTime(Scalar):
@staticmethod
def serialize(dt):
assert isinstance(dt, (datetime.datetime, datetime.date)), 'Received not compatible datetime "{}"'.format(repr(dt))
return dt.isoformat()
@staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
return iso8601.parse_date(node.value)
@staticmethod
def parse_value(value):
return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
|
from __future__ import absolute_import
import datetime
try:
import iso8601
except:
raise ImportError("iso8601 package is required for DateTime Scalar.\nYou can install it using: pip install iso8601.")
from graphql.language import ast
from .scalars import Scalar
class DateTime(Scalar):
@staticmethod
def serialize(dt):
assert isinstance(dt, datetime.datetime)
return dt.isoformat()
@staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
return iso8601.parse_date(node.value)
@staticmethod
def parse_value(value):
return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
|
Rename to internal / external
|
/* jshint -W078 */
'use strict';
let stream = require('stream');
function BidiTransform(options) {
this._externalToInternal = new stream.Transform();
this._internalToExternal = new stream.Transform();
if (options.external) {
this.externalState = options.external;
}
if (options.internal) {
this.internalState = options.internal;
}
}
BidiTransform.prototype = {
get to() {
return {
external: this._internalToExternal,
internal: this._externalToInternal
};
},
get from() {
return {
external: this._externalToInternal,
internal: this._internalToExternal
};
},
set externalState(options) {
for (let option in options) {
this._externalToInternal._writableState[option] = options[option];
this._internalToExternal._readableState[option] = options[option];
}
},
set internalState(options) {
for (let option in options) {
this._externalToInternal._readableState[option] = options[option];
this._internalToExternal._writableState[option] = options[option];
}
}
};
module.exports = BidiTransform;
|
/* jshint -W078 */
'use strict';
let stream = require('stream');
function BidiTransform(options) {
this._clientToServer = new stream.Transform();
this._serverToClient = new stream.Transform();
if (options.client) {
this.clientEndState = options.client;
}
if (options.server) {
this.serverEndState = options.server;
}
}
BidiTransform.prototype = {
get to() {
return {
client: this._serverToClient,
server: this._clientToServer
};
},
get from() {
return {
client: this._clientToServer,
server: this._serverToClient
};
},
set clientEndState(options) {
for (let option in options) {
this._clientToServer._writableState[option] = options[option];
this._serverToClient._readableState[option] = options[option];
}
},
set serverEndState(options) {
for (let option in options) {
this._clientToServer._readableState[option] = options[option];
this._serverToClient._writableState[option] = options[option];
}
}
};
module.exports = BidiTransform;
|
Remove onModule method that is no longer needed.
|
/**
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.plugin.querytemplate;
import org.elasticsearch.plugins.AbstractPlugin;
/**
* Plugin to enable referencing query templates and parameters.
*
* This class is also referenced in the plugin configuration - make sure
* you change the class name in src/main/resources/es.plugin.properties
* when refactoring this class to a different name.
*/
public class QueryTemplatePlugin extends AbstractPlugin {
@Override
public String name() {
return "query-template";
}
@Override
public String description() {
return "Query template plugin allowing to add reference queries by template name";
}
// public void onModule() {
// }
}
|
/**
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.plugin.querytemplate;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.querytemplate.QueryTemplateEngineService;
/**
* Plugin to enable referencing query templates and parameters.
*
* This class is also referenced in the plugin configuration - make sure
* you change the class name in src/main/resources/es.plugin.properties
* when refactoring this class to a different name.
*/
public class QueryTemplatePlugin extends AbstractPlugin {
@Override
public String name() {
return "query-template";
}
@Override
public String description() {
return "Query template plugin allowing to add reference queries by template name";
}
public void onModule(ScriptModule module) {
module.addScriptEngine(QueryTemplateEngineService.class);
}
}
|
Add gradient clipping value and norm
|
from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def PixelCNN(input_shape, filters, blocks, softmax=False, build=True):
input_map = Input(shape=input_shape)
model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map)
model = PReLU()(model)
model = ResidualBlockList(model, filters, blocks)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(1, 1, 1)(model)
if not softmax:
model = Activation('sigmoid')(model)
else:
raise NotImplementedError()
if build:
model = Model(input=input_map, output=model)
model.compile(loss='binary_crossentropy',
optimizer=Nadam(clipnorm=1., clipvalue=1.),
metrics=['accuracy', 'fbeta_score', 'matthews_correlation'])
return model
|
from keras.models import Model
from keras.layers import Input, Convolution2D, Activation, Flatten, Dense
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.residual_block import ResidualBlockList
from eva.layers.masked_convolution2d import MaskedConvolution2D
def PixelCNN(input_shape, filters, blocks, softmax=False, build=True):
input_map = Input(shape=input_shape)
model = MaskedConvolution2D(filters, 7, 7, mask='A', border_mode='same')(input_map)
model = PReLU()(model)
model = ResidualBlockList(model, filters, blocks)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(filters//2, 1, 1)(model)
model = PReLU()(model)
model = Convolution2D(1, 1, 1)(model)
if not softmax:
model = Activation('sigmoid')(model)
else:
raise NotImplementedError()
if build:
model = Model(input=input_map, output=model)
model.compile(loss='binary_crossentropy',
optimizer=Nadam(),
metrics=['accuracy', 'fbeta_score', 'matthews_correlation'])
return model
|
Fix logic error in inlineKeyboard
|
'use strict'
var tgTypes = {};
tgTypes.InlineKeyboardMarkup = function (rowWidth) {
this['inline_keyboard'] = [[]];
var rowWidth = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row
//Closure to make this property private
this._rowWidth = function () {
return rowWidth;
};
};
tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) {
this['inline_keyboard'][this._lastRow()].push(
{
'text': text,
[field]: fieldValue
}
);
if (this._isRowFull()) {
this.newRow();
};
return this;
};
tgTypes.InlineKeyboardMarkup.prototype.newRow = function () {
this['inline_keyboard'].push([]);
return this;
};
tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () {
if (this['inline_keyboard'][this._lastRow()].length === this._rowWidth()) {
return true;
};
};
tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () {
return this['inline_keyboard'].length-1;
};
module.exports = tgTypes;
|
'use strict'
var tgTypes = {};
tgTypes.InlineKeyboardMarkup = function (rowWidth) {
this['inline_keyboard'] = [[]];
var rowWidth = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row
//Closure to make this property private
this._rowWidth = function () {
return rowWidth;
};
};
tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) {
this['inline_keyboard'][this._lastRow()].push(
{
'text': text,
[field]: fieldValue
}
);
if (this._isRowFull()) {
this.newRow();
};
return this;
};
tgTypes.InlineKeyboardMarkup.prototype.newRow = function () {
this['inline_keyboard'].push([]);
return this;
};
tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () {
if (this['inline_keyboard'][this._lastRow()] === this._rowWidth()-1) {
return true;
};
};
tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () {
return this['inline_keyboard'].length-1;
};
module.exports = tgTypes;
|
Rename function to match module.
|
/*global define*/
define(function() {
"use strict";
function createObservableProperty(name, privateName) {
return {
get : function() {
return this[privateName];
},
set : function(value) {
var oldValue = this[privateName];
if (oldValue !== value) {
this[privateName] = value;
this._propertyAssigned.raiseEvent(this, name, value, oldValue);
}
}
};
}
return createObservableProperty;
});
|
/*global define*/
define(function() {
"use strict";
function createProperty(name, privateName) {
return {
get : function() {
return this[privateName];
},
set : function(value) {
var oldValue = this[privateName];
if (oldValue !== value) {
this[privateName] = value;
this._propertyAssigned.raiseEvent(this, name, value, oldValue);
}
}
};
}
return createProperty;
});
|
i18n: Annotate Python UML diagrams support
GitOrigin-RevId: 492135bbc194d71e7a869ef591be574b1225b66b
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.psi;
import com.intellij.openapi.util.NlsSafe;
import org.jetbrains.annotations.Nullable;
/**
* Base class for elements that have a qualified name (classes and functions).
*
* @author yole
*/
public interface PyQualifiedNameOwner extends PyElement {
/**
* Returns the qualified name of the element.
*
* @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
* is contained inside an element that doesn't have a qualified name.
*/
@Nullable
@NlsSafe String getQualifiedName();
}
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.psi;
import org.jetbrains.annotations.Nullable;
/**
* Base class for elements that have a qualified name (classes and functions).
*
* @author yole
*/
public interface PyQualifiedNameOwner extends PyElement {
/**
* Returns the qualified name of the element.
*
* @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
* is contained inside an element that doesn't have a qualified name.
*/
@Nullable
String getQualifiedName();
}
|
Simplify class by removing unnecessary stuff
|
package coatapp.coat;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ForecastRequestTask extends AsyncTask<String, Void, String> {
private static String getForecastRequest(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
@Override
protected String doInBackground(String... params) {
String forecastRequestResponse = "";
try {
forecastRequestResponse = getForecastRequest(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return forecastRequestResponse;
}
@Override
protected void onPostExecute(String message) {
//process message
}
}
|
package coatapp.coat;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ForecastRequestTask extends AsyncTask<String, Void, String> {
public String result;
public static String getForecastRequest(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
@Override
protected String doInBackground(String... params) {
String forecastRequestResponse = "";
try {
forecastRequestResponse = getForecastRequest(params[0].toString());
result = forecastRequestResponse;
} catch (Exception e) {
e.printStackTrace();
}
return forecastRequestResponse;
}
@Override
protected void onPostExecute(String message) {
//process message
}
}
|
Move deferred command additions to be processed after `'after_wp_load'` hook.
For the command additions within (mu-)plugins to work, they need to be processed after all plugins have actually been loaded.
Fixes #4122
|
<?php
namespace WP_CLI\Bootstrap;
/**
* Class RegisterDeferredCommands.
*
* Registers the deferred commands that for which no parent was registered yet.
* This is necessary, because we can have sub-commands that have no direct
* parent, like `wp network meta`.
*
* @package WP_CLI\Bootstrap
*/
final class RegisterDeferredCommands implements BootstrapStep {
/**
* Process this single bootstrapping step.
*
* @param BootstrapState $state Contextual state to pass into the step.
*
* @return BootstrapState Modified state to pass to the next step.
*/
public function process( BootstrapState $state ) {
\WP_CLI::add_hook(
'after_wp_load',
array( $this, 'add_deferred_commands' )
);
return $state;
}
/**
* Add deferred commands that are still waiting to be processed.
*/
public function add_deferred_commands() {
$deferred_additions = \WP_CLI::get_deferred_additions();
foreach ( $deferred_additions as $name => $addition ) {
\WP_CLI::add_command(
$name,
$addition['callable'],
$addition['args']
);
}
}
}
|
<?php
namespace WP_CLI\Bootstrap;
/**
* Class RegisterDeferredCommands.
*
* Registers the deferred commands that for which no parent was registered yet.
* This is necessary, because we can have sub-commands that have no direct
* parent, like `wp network meta`.
*
* @package WP_CLI\Bootstrap
*/
final class RegisterDeferredCommands implements BootstrapStep {
/**
* Process this single bootstrapping step.
*
* @param BootstrapState $state Contextual state to pass into the step.
*
* @return BootstrapState Modified state to pass to the next step.
*/
public function process( BootstrapState $state ) {
$deferred_additions = \WP_CLI::get_deferred_additions();
foreach ( $deferred_additions as $name => $addition ) {
\WP_CLI::add_command(
$name,
$addition['callable'],
$addition['args']
);
}
return $state;
}
}
|
Fix syntax error in layouts.base view.
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title')</title>
<link href="css/main.css" rel="stylesheet">
@yield('head')
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="@yield('body_class')">
@yield('header')
@yield('body')
@yield('footer')
<script type="text/javascript" src="js/nodeFrameworks.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title')</title>
<link href="css/main.css" rel="stylesheet">
@yeild('head')
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="@yield('body_class')">
@yield('header')
@yield('body')
@yield('footer')
<script type="text/javascript" src="js/nodeFrameworks.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
|
Add comment about when auto layout doesn't work
|
/**
* Convert monitors from VM format to what the GUI needs to render.
* - Convert opcode to a label and a category
* - Add missing XY position data if needed
*/
const OpcodeLabels = require('../lib/opcode-labels.js');
const PADDING = 5;
const MONITOR_HEIGHT = 23;
const isUndefined = a => typeof a === 'undefined';
module.exports = function ({id, opcode, params, value, x, y}, monitorIndex) {
let {label, category, labelFn} = OpcodeLabels(opcode);
// Use labelFn if provided for dynamic labelling (e.g. variables)
if (!isUndefined(labelFn)) label = labelFn(params);
// Simple layout if x or y are undefined
// @todo scratch2 has a more complex layout behavior we may want to adopt
// @todo e.g. this does not work well when monitors have already been moved
if (isUndefined(x)) x = PADDING;
if (isUndefined(y)) y = PADDING + (monitorIndex * (PADDING + MONITOR_HEIGHT));
return {id, label, category, value, x, y};
};
|
/**
* Convert monitors from VM format to what the GUI needs to render.
* - Convert opcode to a label and a category
* - Add missing XY position data if needed
*/
const OpcodeLabels = require('../lib/opcode-labels.js');
const PADDING = 5;
const MONITOR_HEIGHT = 23;
const isUndefined = a => typeof a === 'undefined';
module.exports = function ({id, opcode, params, value, x, y}, monitorIndex) {
let {label, category, labelFn} = OpcodeLabels(opcode);
// Use labelFn if provided for dynamic labelling (e.g. variables)
if (!isUndefined(labelFn)) label = labelFn(params);
// Simple layout if x or y are undefined
// @todo scratch2 has a more complex layout behavior we may want to adopt
if (isUndefined(x)) x = PADDING;
if (isUndefined(y)) y = PADDING + (monitorIndex * (PADDING + MONITOR_HEIGHT));
return {id, label, category, value, x, y};
};
|
Remove unused arguments from test
|
<?php
namespace Emarref\Namer\Detector;
class ArrayDetectorTest extends \PHPUnit_Framework_TestCase
{
/**
* @array
*/
private static $pool = [
'Apple',
];
/**
* @var ArrayDetector
*/
private $detector;
public function setup()
{
$this->detector = new ArrayDetector(self::$pool);
}
public function testIsAvailable()
{
$this->assertTrue($this->detector->isAvailable('Test'), 'Available names return true');
$this->assertFalse($this->detector->isAvailable('Apple'), 'Unavailable names return false');
}
public function tearDown()
{
unset($this->detector);
}
}
|
<?php
namespace Emarref\Namer\Detector;
class ArrayDetectorTest extends \PHPUnit_Framework_TestCase
{
/**
* @array
*/
private static $pool = [
'Apple',
];
/**
* @var ArrayDetector
*/
private $detector;
public function setup()
{
$this->detector = new ArrayDetector(self::$pool);
}
public function testIsAvailable()
{
$this->assertTrue($this->detector->isAvailable('Test', 0), 'Available names return true');
$this->assertFalse($this->detector->isAvailable('Apple', 0), 'Unavailable names return false');
}
public function tearDown()
{
unset($this->detector);
}
}
|
Test the app list generation a bit
|
from django.contrib import admin
from django.contrib.auth.models import User
from django.test import Client, RequestFactory, TestCase
from fhadmin.templatetags.fhadmin_module_groups import generate_group_list
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
# print(response, response.content.decode("utf-8"))
def test_app_list(self):
request = RequestFactory().get("/")
request.user = User.objects.create(is_superuser=True)
groups = list(generate_group_list(admin.sites.site, request))
# from pprint import pprint; pprint(groups)
self.assertEqual(groups[0][0], "Modules")
self.assertEqual(groups[0][1][0]["app_label"], "testapp")
self.assertEqual(len(groups[0][1][0]["models"]), 1)
|
from django.contrib.auth.models import User
from django.test import Client, TestCase
class AdminTest(TestCase):
def login(self):
client = Client()
u = User.objects.create(
username="test", is_active=True, is_staff=True, is_superuser=True
)
client.force_login(u)
return client
def test_dashboard(self):
client = self.login()
response = client.get("/admin/")
self.assertContains(response, '<div class="groups">')
self.assertContains(response, "<h2>Modules</h2>")
self.assertContains(response, "<h2>Preferences</h2>")
print(response, response.content.decode("utf-8"))
|
Set delete expense action as HTTP Put
|
package agoodfriendalwayspayshisdebts.web.actions.expense;
import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Put;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;
import javax.inject.Inject;
import java.util.UUID;
@Resource
public class DeleteExpense extends BaseAction {
@Inject
public DeleteExpense(CommandBus commandBus) {
this.commandBus = commandBus;
}
@Put("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
final DeleteExpenseCommand command = new DeleteExpenseCommand();
command.eventId = UUID.fromString(stringifiedEventId);
command.expenseId = UUID.fromString(stringifiedExpenseUuid);
final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
}
private final CommandBus commandBus;
}
|
package agoodfriendalwayspayshisdebts.web.actions.expense;
import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Delete;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;
import javax.inject.Inject;
import java.util.UUID;
@Resource
public class DeleteExpense extends BaseAction {
@Inject
public DeleteExpense(CommandBus commandBus) {
this.commandBus = commandBus;
}
@Delete("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
final DeleteExpenseCommand command = new DeleteExpenseCommand();
command.eventId = UUID.fromString(stringifiedEventId);
command.expenseId = UUID.fromString(stringifiedExpenseUuid);
final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
}
private final CommandBus commandBus;
}
|
Fix bug in unit test
|
#!/usr/bin/env python
#------------------------------------------------------------------------
# Copyright (c) 2015 SGW
#
# Distributed under the terms of the New BSD License.
#
# The full License is in the file LICENSE
#------------------------------------------------------------------------
import unittest
import numpy as np
import velvet as vt
class TestUtilFunctions(unittest.TestCase):
def test_isodd(self):
x = np.array([1,2,1,1,-3,-4,7,8,9,10,-2,1,-3,5,6,7,-10])
y = vt.isodd(x)
yCorrect = np.array([1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0])
for ind in np.arange(len(y)):
self.assertEqual(y[ind],yCorrect[ind])
def mysuite():
return unittest.TestLoader().loadTestsFromTestCase(TestUtilFunctions)
if __name__ == '__main__':
suite = mysuite()
unittest.TextTestRunner(verbosity=2).run(suite)
|
#!/usr/bin/env python
#------------------------------------------------------------------------
# Copyright (c) 2015 SGW
#
# Distributed under the terms of the New BSD License.
#
# The full License is in the file LICENSE
#------------------------------------------------------------------------
import unittest
import numpy as np
import velvet as vt
class TestUtilFunctions(unittest.TestCase):
def test_isodd(self):
x = np.array([1,2,1,1,-3,-4,7,8,9,10,-2,1,-3,5,6,7,-10])
y = vt.isodd(x)
yCorrect = np.array([1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0])
for ind in xrange(len(y)):
self.assertEqual(y[ind],yCorrect[ind])
def mysuite():
return unittest.TestLoader().loadTestsFromTestCase(TestUtilFunctions)
if __name__ == '__main__':
suite = mysuite()
unittest.TextTestRunner(verbosity=2).run(suite)
|
feat(login): Set monitoring as the default page after login (SDNTB-180)
|
/**
* This file is part of Superdesk.
*
* Copyright 2013, 2014 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
window.bootstrapSuperdesk = function bootstrap(config, apps) {
angular.module('superdesk.config').constant('config', config);
angular.module('superdesk').constant('lodash', _);
// setup default route for superdesk - set it here to avoid it being used in unit tests
angular.module('superdesk').config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {redirectTo: '/workspace/monitoring'});
}]);
// load apps & bootstrap
var body = angular.element('body');
body.ready(function() {
angular.bootstrap(body, apps, {strictDi: true});
window.superdeskIsReady = true;
});
};
})();
|
/**
* This file is part of Superdesk.
*
* Copyright 2013, 2014 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
window.bootstrapSuperdesk = function bootstrap(config, apps) {
angular.module('superdesk.config').constant('config', config);
angular.module('superdesk').constant('lodash', _);
// setup default route for superdesk - set it here to avoid it being used in unit tests
angular.module('superdesk').config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {redirectTo: '/workspace'});
}]);
// load apps & bootstrap
var body = angular.element('body');
body.ready(function() {
angular.bootstrap(body, apps, {strictDi: true});
window.superdeskIsReady = true;
});
};
})();
|
Make Display for the window numbers linear because of chrome.
|
var body = document.getElementById("body");
var currentWindow = null;
var ul = null;
function clickHandler(){
chrome.tabs.update(this.tabId, {active:true});
chrome.windows.update(this.windowId, {focused: true});
}
//loop through the tabs and group them by windows for display
chrome.tabs.query({}, function(tabs){
var windowDisplayNum = 1;
for(var i = 0, len = tabs.length; i < len; i++){
var li = document.createElement("li");
var link = document.createElement("a");
var isNewWindow = !(currentWindow === tabs[i].windowId);
if(isNewWindow){
//insert a new window header and change the ul
currentWindow = tabs[i].windowId;
ul = document.createElement("ul")
var windowTitle = document.createElement("h2");
windowTitle.innerText = "Window " + windowDisplayNum++;
body.appendChild(windowTitle);
body.appendChild(ul)
}
link.href = "#";
link.onclick = clickHandler;
link.tabId = tabs[i].id;
link.windowId = tabs[i].windowId;
link.innerText = tabs[i].title || tabs[i].url;
li.appendChild(link)
ul.appendChild(li);
}
});
// where to go to possibly fix the tab title bug when there are tabs that have been unloaded
// http://searchfox.org/mozilla-central/source/browser/components/extensions/ext-utils.js#386
|
var body = document.getElementById("body");
var currentWindow = null;
var ul = null;
function clickHandler(){
chrome.tabs.update(this.tabId, {active:true});
chrome.windows.update(this.windowId, {focused: true});
}
//loop through the tabs and group them by windows for display
chrome.tabs.query({}, function(tabs){
for(var i = 0, len = tabs.length; i < len; i++){
var li = document.createElement("li");
var link = document.createElement("a");
var isNewWindow = !(currentWindow === tabs[i].windowId);
console.log("is new window: " + currentWindow + " " + tabs[i].windowId);
if(isNewWindow){
//insert a new window header and change the ul
currentWindow = tabs[i].windowId;
ul = document.createElement("ul")
var windowTitle = document.createElement("h2");
windowTitle.innerText = "Window " + currentWindow;
body.appendChild(windowTitle);
body.appendChild(ul)
}
link.href = "#";
link.onclick = clickHandler;
link.tabId = tabs[i].id;
link.windowId = tabs[i].windowId;
link.innerText = tabs[i].title || tabs[i].url;
li.appendChild(link)
ul.appendChild(li);
}
});
// where to go to possibly fix the tab title bug when there are tabs that have been unloaded
// http://searchfox.org/mozilla-central/source/browser/components/extensions/ext-utils.js#386
|
Test config does not require an entry setting
|
var webpack = require("webpack");
var nodeExternals = require("webpack-node-externals");
module.exports = {
target: "node",
externals: [nodeExternals()],
module: {
preLoaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "eslint" }
],
loaders: [
{
test: /.js$/,
loader: "babel",
exclude: /node_modules/,
query: {
presets: ["es2015"],
cacheDirectory: true
}
},
{ test: /\.json$/, loader: "json" },
{ test: /\.css$/, loader: "css" },
{ test: /\.html$/, loader: "dom!html" },
]
},
plugins: [
new webpack.DefinePlugin({PRODUCTION: false,
BROWSER: false}),
],
devtool: "source-map"
};
|
var webpack = require("webpack");
var nodeExternals = require("webpack-node-externals");
module.exports = {
target: "node",
externals: [nodeExternals()],
entry: './test/start.js',
module: {
preLoaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "eslint" }
],
loaders: [
{
test: /.js$/,
loader: "babel",
exclude: /node_modules/,
query: {
presets: ["es2015"],
cacheDirectory: true
}
},
{ test: /\.json$/, loader: "json" },
{ test: /\.css$/, loader: "css" },
{ test: /\.html$/, loader: "dom!html" },
]
},
plugins: [
new webpack.DefinePlugin({PRODUCTION: false,
BROWSER: false}),
],
devtool: "source-map"
};
|
Use state for random number.
|
import React, { Component } from 'react'
import RandomNumber from '../RandomNumber'
import RoundImage from '../RoundImage'
import WelcomeNote from '../WelcomeNote'
import style from './style.css'
import classnames from 'classnames'
const classes = classnames.bind(style)
export default class App extends Component {
state = {
number: Math.random().toFixed(3)
}
render () {
const cx = classes(`vh-100 dt w-100 ${style.image}`)
return (
<div className={cx}>
<div className='dtc v-mid tc white ph3 ph4-l'>
<RoundImage />
<WelcomeNote />
<RandomNumber number={this.state.number}/>
</div>
</div>
)
}
}
|
import React, { Component } from 'react'
import RandomNumber from '../RandomNumber'
import RoundImage from '../RoundImage'
import WelcomeNote from '../WelcomeNote'
import style from './style.css'
import classnames from 'classnames'
const classes = classnames.bind(style)
// import src from '../../assets/images/crossword.png'
export default class App extends Component {
render () {
const cx = classes(`vh-100 dt w-100 ${style.image}`)
return (
<div className={cx}>
<div className='dtc v-mid tc white ph3 ph4-l'>
<RoundImage />
<WelcomeNote />
<RandomNumber number={Math.random().toFixed(3)}/>
</div>
</div>
)
}
}
|
Add service name for replacement pattern type registry
|
<?php
/*
* This file is part of the PcdxParameterEncryptionBundle package.
*
* (c) picodexter <https://picodexter.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;
/**
* ServiceNames.
*
* Contains names for this bundle's Symfony services that are referenced in the code.
*/
final class ServiceNames
{
const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.';
const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';
const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry';
const REPLACEMENT_PATTERN_TYPE_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.type_registry';
/**
* Constructor.
*
* Forbid instantiation.
*/
public function __construct()
{
throw new \BadMethodCallException('This class cannot be instantiated.');
}
}
|
<?php
/*
* This file is part of the PcdxParameterEncryptionBundle package.
*
* (c) picodexter <https://picodexter.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;
/**
* ServiceNames.
*
* Contains names for this bundle's Symfony services that are referenced in the code.
*/
final class ServiceNames
{
const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.';
const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';
const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry';
/**
* Constructor.
*
* Forbid instantiation.
*/
public function __construct()
{
throw new \BadMethodCallException('This class cannot be instantiated.');
}
}
|
Allow consumers to specify custom theme for react-autosuggest in autosuggest component
|
import React from 'react'
import Autosuggest from 'react-autosuggest'
import style from './bpk-autosuggest.scss'
const defaultTheme = {
container: 'bpk-autosuggest__container',
containerOpen: 'bpk-autosuggest__container--open',
input: 'bpk-autosuggest__input',
suggestionsContainer: 'bpk-autosuggest__suggestions-container',
suggestionsList: 'bpk-autosuggest__suggestions-list',
suggestion: 'bpk-autosuggest__suggestion',
suggestionFocused: 'bpk-autosuggest__suggestion--focused',
sectionContainer: 'bpk-autosuggest__section-container',
sectionTitle: 'bpk-autosuggest__section-title'
}
const BpkAutosuggest = (props) => {
const inputProps = {
value: props.value,
onChange: props.onChange
}
return (
<Autosuggest
suggestions={props.suggestions}
onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested}
onSuggestionsClearRequested={props.onSuggestionsClearRequested || (() => {})}
getSuggestionValue={props.getSuggestionValue || ((suggestion) => suggestion)}
renderSuggestion={props.renderSuggestion}
onSuggestionSelected={props.onSuggestionSelected || (() => {})}
inputProps={inputProps}
theme={props.theme || defaultTheme}
/>
)
}
export default BpkAutosuggest
|
import React from 'react'
import Autosuggest from 'react-autosuggest'
import style from './bpk-autosuggest.scss'
const defaultTheme = {
container: 'bpk-autosuggest__container',
containerOpen: 'bpk-autosuggest__container--open',
input: 'bpk-autosuggest__input',
suggestionsContainer: 'bpk-autosuggest__suggestions-container',
suggestionsList: 'bpk-autosuggest__suggestions-list',
suggestion: 'bpk-autosuggest__suggestion',
suggestionFocused: 'bpk-autosuggest__suggestion--focused',
sectionContainer: 'bpk-autosuggest__section-container',
sectionTitle: 'bpk-autosuggest__section-title'
}
const BpkAutosuggest = (props) => {
const inputProps = {
value: props.value,
onChange: props.onChange
}
return (
<Autosuggest
suggestions={props.suggestions}
onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested}
onSuggestionsClearRequested={props.onSuggestionsClearRequested || (() => {})}
getSuggestionValue={props.getSuggestionValue || ((suggestion) => suggestion)}
renderSuggestion={props.renderSuggestion}
onSuggestionSelected={props.onSuggestionSelected || (() => {})}
inputProps={inputProps}
theme={defaultTheme}
/>
)
}
export default BpkAutosuggest
|
Add /r and /m to muted commands
|
package net.simpvp.NoSpam;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
public CommandListener(NoSpam plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String message = event.getMessage().toLowerCase();
/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
if (message.startsWith("/tell ")
|| message.startsWith("/me ")
|| message.startsWith("/msg ")
|| message.startsWith("/w ")
|| message.startsWith("/op ")
|| message.startsWith("/r ")
|| message.startsWith("/m ")
|| message.equals("/op")) {
boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam
if ( cancel ) event.setCancelled(true);
}
}
}
|
package net.simpvp.NoSpam;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
public CommandListener(NoSpam plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String message = event.getMessage().toLowerCase();
/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
if (message.startsWith("/tell ")
|| message.startsWith("/me ")
|| message.startsWith("/msg ")
|| message.startsWith("/w ")
|| message.startsWith("/op ")
|| message.equals("/op")) {
boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam
if ( cancel ) event.setCancelled(true);
}
}
}
|
Stop interlude removes non-player characters.
|
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Addison Arches is distributed in the hope that it will be useful, but
# 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 Addison Arches. If not, see <http://www.gnu.org/licenses/>.
from turberfield.dialogue.types import Player
async def default(folder, ensemble:list, log=None, loop=None):
if log is not None:
log.debug("No activity during interlude")
return folder
async def stop(folder, ensemble:list, log=None, loop=None):
if log is not None:
log.debug("Interlude stops dialogue")
for entity in ensemble[:]:
if not isinstance(entity, Player):
ensemble.remove(entity)
return None
|
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Addison Arches is distributed in the hope that it will be useful, but
# 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 Addison Arches. If not, see <http://www.gnu.org/licenses/>.
async def default(folder, ensemble, log=None, loop=None):
if log is not None:
log.debug("No activity during interlude")
return folder
async def stop(folder, ensemble, log=None, loop=None):
if log is not None:
log.debug("Interlude stops dialogue")
return None
|
Set creation date via field, not via constructor
|
# -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
version = SnippetVersion(
snippet=snippet,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
if created_at is not None:
version.created_at = created_at
return version
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
|
# -*- coding: utf-8 -*-
"""
testfixtures.snippet
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.blueprints.snippet.models.snippet import \
CurrentVersionAssociation, Snippet, SnippetVersion
def create_snippet(party, name):
return Snippet(
party=party,
name=name)
def create_snippet_version(snippet, creator, *, created_at=None,
title='', head='', body='', image_url_path=None):
return SnippetVersion(
snippet=snippet,
created_at=created_at,
creator=creator,
title=title,
head=head,
body=body,
image_url_path=image_url_path)
def create_current_version_association(snippet, version):
return CurrentVersionAssociation(
snippet=snippet,
version=version)
|
chore(tests): Remove console logging during test run.
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
require('ass')
var dbServer = require('fxa-auth-db-server')
var backendTests = require('fxa-auth-db-server/test/backend')
var config = require('../../config')
var noop = function () {}
var log = { trace: noop, error: noop, stat: noop, info: noop }
var DB = require('../../db/mysql')(log, dbServer.errors)
var P = require('bluebird')
var server
// defer to allow ass code coverage results to complete processing
if (process.env.ASS_CODE_COVERAGE) {
process.on('SIGINT', function() {
process.nextTick(process.exit)
})
}
var db
DB.connect(config)
.then(function (newDb) {
db = newDb
server = dbServer.createServer(db)
var d = P.defer()
server.listen(config.port, config.hostname, function() {
d.resolve()
})
return d.promise
})
.then(function() {
return backendTests.remote(config)
})
.then(function() {
server.close()
db.close()
})
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
require('ass')
var dbServer = require('fxa-auth-db-server')
var backendTests = require('fxa-auth-db-server/test/backend')
var config = require('../../config')
var log = { trace: console.log, error: console.log, stat: console.log, info: console.log }
var DB = require('../../db/mysql')(log, dbServer.errors)
var P = require('bluebird')
var server
// defer to allow ass code coverage results to complete processing
if (process.env.ASS_CODE_COVERAGE) {
process.on('SIGINT', function() {
process.nextTick(process.exit)
})
}
var db
DB.connect(config)
.then(function (newDb) {
db = newDb
server = dbServer.createServer(db)
var d = P.defer()
server.listen(config.port, config.hostname, function() {
d.resolve()
})
server.on('failure', function (d) { console.error(d.err.code, d.url)})
server.on('success', function (d) { console.log(d.method, d.url)})
return d.promise
})
.then(function() {
return backendTests.remote(config)
})
.then(function() {
server.close()
db.close()
})
|
Make infinibow lowest priority to give other mod behaviors priority
|
package com.enderio.core.common.tweaks;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.ArrowNockEvent;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class InfiniBow extends Tweak {
public InfiniBow() {
super("infinibow", "Makes bows with Infinity enchant able to be fired with no arrows in the inventory.");
}
@Override
public void load() {
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onArrowNock(ArrowNockEvent event) {
EntityPlayer player = event.entityPlayer;
ItemStack stack = player.getHeldItem();
if (player.capabilities.isCreativeMode || player.inventory.hasItem(Items.arrow)
|| EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0) {
player.setItemInUse(stack, stack.getItem().getMaxItemUseDuration(stack));
}
event.result = stack;
event.setCanceled(true);
}
}
|
package com.enderio.core.common.tweaks;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.ArrowNockEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class InfiniBow extends Tweak {
public InfiniBow() {
super("infinibow", "Makes bows with Infinity enchant able to be fired with no arrows in the inventory.");
}
@Override
public void load() {
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onArrowNock(ArrowNockEvent event) {
EntityPlayer player = event.entityPlayer;
ItemStack stack = player.getHeldItem();
if (player.capabilities.isCreativeMode || player.inventory.hasItem(Items.arrow)
|| EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0) {
player.setItemInUse(stack, stack.getItem().getMaxItemUseDuration(stack));
}
event.result = stack;
event.setCanceled(true);
}
}
|
Add cache in sitemap section
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.contrib.sitemaps import views as sitemap_views
from opps.core.cache import cache_page
from opps.sitemaps.sitemaps import GenericSitemap, InfoDisct
sitemaps = {
'containers': GenericSitemap(InfoDisct(), priority=0.6),
}
sitemaps_googlenews = {
'containers': GenericSitemap(InfoDisct(True), priority=0.6),
}
urlpatterns = patterns(
'',
url(r'^\.xml$', cache_page(86400)(sitemap_views.index),
{'sitemaps': sitemaps}),
url(r'^-googlenews\.xml$', cache_page(86400)(sitemap_views.sitemap),
{'sitemaps': sitemaps_googlenews,
'template_name': 'sitemap_googlenews.xml'}),
url(r'^-(?P<section>.+)\.xml$', cache_page(86400)(sitemap_views.sitemap),
{'sitemaps': sitemaps}),
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.contrib.sitemaps import views as sitemap_views
from opps.core.cache import cache_page
from opps.sitemaps.sitemaps import GenericSitemap, InfoDisct
sitemaps = {
'articles': GenericSitemap(InfoDisct(), priority=0.6),
}
sitemaps_googlenews = {
'articles': GenericSitemap(InfoDisct(True), priority=0.6),
}
urlpatterns = patterns(
'',
url(r'^\.xml$', cache_page(86400)(sitemap_views.index),
{'sitemaps': sitemaps}),
url(r'^-googlenews\.xml$', cache_page(86400)(sitemap_views.sitemap),
{'sitemaps': sitemaps_googlenews,
'template_name': 'sitemap_googlenews.xml'}),
url(r'^-(?P<section>.+)\.xml$', sitemap_views.sitemap,
{'sitemaps': sitemaps}),
)
|
Include env.system_install PATH as part of version checking to work with installed software not on the global PATH. Thanks to James Cuff
|
"""Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from distutils.version import LooseVersion
from fabric.api import quiet
from cloudbio.custom import shared
def _parse_from_stdoutflag(out, flag):
"""Extract version information from a flag in verbose stdout.
"""
for line in out.split("\n") + out.stderr.split("\n"):
if line.find(flag) >= 0:
parts = [x for x in line.split() if not x.startswith(flag)]
return parts[0]
return ""
def up_to_date(env, cmd, version, args=None, stdout_flag=None):
"""Check if the given command is up to date with the provided version.
"""
if shared._executable_not_on_path(cmd):
return False
if args:
cmd = cmd + " " + " ".join(args)
with quiet():
path_safe = "export PATH=$PATH:%s/bin && "
out = env.safe_run_output(path_safe + cmd)
if stdout_flag:
iversion = _parse_from_stdoutflag(out, stdout_flag)
else:
iversion = out.strip()
return LooseVersion(iversion) >= LooseVersion(version)
|
"""Tool specific version checking to identify out of date dependencies.
This provides infrastructure to check version strings against installed
tools, enabling re-installation if a version doesn't match. This is a
lightweight way to avoid out of date dependencies.
"""
from distutils.version import LooseVersion
from fabric.api import quiet
from cloudbio.custom import shared
def _parse_from_stdoutflag(out, flag):
"""Extract version information from a flag in verbose stdout.
"""
for line in out.split("\n") + out.stderr.split("\n"):
if line.find(flag) >= 0:
parts = [x for x in line.split() if not x.startswith(flag)]
return parts[0]
return ""
def up_to_date(env, cmd, version, args=None, stdout_flag=None):
"""Check if the given command is up to date with the provided version.
"""
if shared._executable_not_on_path(cmd):
return False
if args:
cmd = cmd + " " + " ".join(args)
with quiet():
out = env.safe_run_output(cmd)
if stdout_flag:
iversion = _parse_from_stdoutflag(out, stdout_flag)
else:
iversion = out.strip()
return LooseVersion(iversion) >= LooseVersion(version)
|
Set an API load every hour as a scheduled job
|
'use strict';
// Dependencies
var config = require('./config');
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var compress = require('compression');
var multipart = require('connect-multiparty');
var schedule = require('node-schedule');
var feed = require('./app/controllers/feed');
var app = express();
// Configuration
app.enable('trust proxy');
app.set('port', config.app.settings.port);
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.use(compress());
app.use(bodyParser.json({ limit: '128kb'}));
app.use(multipart());
app.use(express.static('public'));
app.use(methodOverride());
// Routes
require('./app/routes')(app);
// Schedule
schedule.scheduleJob('0 * * * *', function(){
feed.API.load( { verbose: true } );
});
module.exports = app;
|
'use strict';
// Dependencies
var config = require('./config');
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var compress = require('compression');
var multipart = require('connect-multiparty');
var app = express();
// Configuration
app.enable('trust proxy');
app.set('port', config.app.settings.port);
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.use(compress());
app.use(bodyParser.json({ limit: '128kb'}));
app.use(multipart());
app.use(express.static('public'));
app.use(methodOverride());
// Routes
require('./app/routes')(app);
module.exports = app;
|
Add trigger as an alias for schedule
"Have you triggered that pipeline" is a fairly common thing to say.
|
from gocd.api.endpoint import Endpoint
class Pipeline(Endpoint):
base_path = 'go/api/pipelines/{id}'
id = 'name'
def __init__(self, server, name):
self.server = server
self.name = name
def history(self, offset=0):
return self._get('/history/{offset:d}'.format(offset=offset or 0))
def release(self):
return self._post('/releaseLock')
unlock = release
def pause(self, reason=''):
return self._post('/pause', pauseCause=reason)
def unpause(self):
return self._post('/unpause')
def status(self):
return self._get('/status')
def instance(self, counter):
return self._get('/instance/{counter:d}'.format(counter=counter))
def schedule(self, **material_args):
return self._post('/schedule', ok_status=202, **material_args)
run = schedule
trigger = schedule
|
from gocd.api.endpoint import Endpoint
class Pipeline(Endpoint):
base_path = 'go/api/pipelines/{id}'
id = 'name'
def __init__(self, server, name):
self.server = server
self.name = name
def history(self, offset=0):
return self._get('/history/{offset:d}'.format(offset=offset or 0))
def release(self):
return self._post('/releaseLock')
unlock = release
def pause(self, reason=''):
return self._post('/pause', pauseCause=reason)
def unpause(self):
return self._post('/unpause')
def status(self):
return self._get('/status')
def instance(self, counter):
return self._get('/instance/{counter:d}'.format(counter=counter))
def schedule(self, **material_args):
return self._post('/schedule', ok_status=202, **material_args)
run = schedule
|
Allow version to have subrevision.
|
from setuptools import setup, find_packages
# Dynamically calculate the version based on dbsettings.VERSION
version_tuple = (0, 4, None)
if version_tuple[2] is not None:
if type(version_tuple[2]) == int:
version = "%d.%d.%s" % version_tuple
else:
version = "%d.%d_%s" % version_tuple
else:
version = "%d.%d" % version_tuple[:2]
setup(
name='django-dbsettings',
version=version,
description='Application settings whose values can be updated while a project is up and running.',
long_description=open('README.rst').read(),
author='Samuel Cormier-Iijima',
author_email='sciyoshi@gmail.com',
maintainer='Jacek Tomaszewski',
maintainer_email='jacek.tomek@gmail.com',
url='http://github.com/zlorf/django-dbsettings',
packages=find_packages(),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
from setuptools import setup, find_packages
# Dynamically calculate the version based on dbsettings.VERSION
version_tuple = (0, 4, None)
if version_tuple[2] is not None:
version = "%d.%d_%s" % version_tuple
else:
version = "%d.%d" % version_tuple[:2]
setup(
name='django-dbsettings',
version=version,
description='Application settings whose values can be updated while a project is up and running.',
long_description=open('README.rst').read(),
author='Samuel Cormier-Iijima',
author_email='sciyoshi@gmail.com',
maintainer='Jacek Tomaszewski',
maintainer_email='jacek.tomek@gmail.com',
url='http://github.com/zlorf/django-dbsettings',
packages=find_packages(),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
)
|
Add copyright header to CommitteeDetailGetTestCase.
|
# Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from huxley.utils.test import TestCommittees
class CommitteeDetailGetTestCase(TestCase):
def setUp(self):
self.client = Client()
def get_url(self, committee_id):
return reverse('api:committee_detail', args=(committee_id,))
def get_response(self, url):
return json.loads(self.client.get(url).content)
def test_anonymous_user(self):
'''It should return the correct fields for a committee.'''
c = TestCommittees.new_committee()
url = self.get_url(c.id)
data = self.get_response(url)
self.assertEqual(data['delegation_size'], c.delegation_size)
self.assertEqual(data['special'], c.special)
self.assertEqual(data['id'], c.id)
self.assertEqual(data['full_name'], c.full_name)
self.assertEqual(data['name'], c.name)
|
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from huxley.utils.test import TestCommittees
class CommitteeDetailGetTestCase(TestCase):
def setUp(self):
self.client = Client()
def get_url(self, committee_id):
return reverse('api:committee_detail', args=(committee_id,))
def get_response(self, url):
return json.loads(self.client.get(url).content)
def test_anonymous_user(self):
'''It should return the correct fields for a committee.'''
c = TestCommittees.new_committee()
url = self.get_url(c.id)
data = self.get_response(url)
self.assertEqual(data['delegation_size'], c.delegation_size)
self.assertEqual(data['special'], c.special)
self.assertEqual(data['id'], c.id)
self.assertEqual(data['full_name'], c.full_name)
self.assertEqual(data['name'], c.name)
|
Fix model connection for sqlite tests
|
<?php namespace GeneaLabs\LaravelModelCaching\Traits;
use Illuminate\Container\Container;
trait CachePrefixing
{
protected function getCachePrefix() : string
{
$cachePrefix = Container::getInstance()
->make("config")
->get("laravel-model-caching.cache-prefix", "");
if ($this->model
&& property_exists($this->model, "cachePrefix")
) {
$cachePrefix = $this->model->cachePrefix;
}
$cachePrefix = $cachePrefix
? "{$cachePrefix}:"
: "";
return "genealabs:laravel-model-caching:"
. $this->getConnectionName() . ":"
. $this->getDatabaseName() . ":"
. $cachePrefix;
}
protected function getDatabaseName() : string
{
return $this->model->getConnection()->getDatabaseName();
}
protected function getConnectionName() : string
{
return $this->model->getConnection()->getName();
}
}
|
<?php namespace GeneaLabs\LaravelModelCaching\Traits;
use Illuminate\Container\Container;
trait CachePrefixing
{
protected function getCachePrefix() : string
{
$cachePrefix = Container::getInstance()
->make("config")
->get("laravel-model-caching.cache-prefix", "");
if ($this->model
&& property_exists($this->model, "cachePrefix")
) {
$cachePrefix = $this->model->cachePrefix;
}
$cachePrefix = $cachePrefix
? "{$cachePrefix}:"
: "";
return "genealabs:laravel-model-caching:"
. $this->getConnectionName() . ":"
. $this->getDatabaseName() . ":"
. $cachePrefix;
}
protected function getDatabaseName() : string
{
return $this->query->getConnection()->getDatabaseName();
}
protected function getConnectionName() : string
{
return $this->model->getConnection()->getName();
}
}
|
Delete testonly namespaces from the duplicate namespaces exemption list
GITHUB_BREAKING_CHANGES=none
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=360768962
|
/*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.internal.exemptions;
import com.google.common.collect.ImmutableSet;
/** A list of all allowed duplicate namespaces and a simple predicate for querying it. */
public final class NamespaceExemptions {
public static boolean isKnownDuplicateNamespace(String namespace) {
return ALLOWED_DUPLICATE_NAMESPACES.contains(namespace);
}
private static final ImmutableSet<String> ALLOWED_DUPLICATE_NAMESPACES =
ImmutableSet.of(
);
private NamespaceExemptions() {}
}
|
/*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.internal.exemptions;
import com.google.common.collect.ImmutableSet;
/** A list of all allowed duplicate namespaces and a simple predicate for querying it. */
public final class NamespaceExemptions {
public static boolean isKnownDuplicateNamespace(String namespace) {
return ALLOWED_DUPLICATE_NAMESPACES.contains(namespace);
}
// TODO(b/180904763): burn this down!
private static final ImmutableSet<String> ALLOWED_DUPLICATE_NAMESPACES =
ImmutableSet.of(
);
private NamespaceExemptions() {}
}
|
Change meal name to charfield
|
from __future__ import unicode_literals
from django.db import models
class Weekday(models.Model):
"""Model representing the day of the week."""
name = models.CharField(max_length=60, unique=True)
def clean(self):
"""
Capitalize the first letter of the first word to avoid case
insensitive duplicates for name field.
"""
self.name = self.name.capitalize()
def save(self, *args, **kwargs):
self.clean()
return super(Weekday, self).save(*args, **kwargs)
class Meal(models.Model):
name = models.CharField(max_length=60)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return self.name
|
from __future__ import unicode_literals
from django.db import models
class Weekday(models.Model):
"""Model representing the day of the week."""
name = models.CharField(max_length=60, unique=True)
def clean(self):
"""
Capitalize the first letter of the first word to avoid case
insensitive duplicates for name field.
"""
self.name = self.name.capitalize()
def save(self, *args, **kwargs):
self.clean()
return super(Weekday, self).save(*args, **kwargs)
class Meal(models.Model):
name = models.TextField()
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return self.name
|
Convert task output to UTF8
|
import bosh_client
import os
import yaml
def do_step(context):
settings = context.meta['settings']
username = settings["username"]
home_dir = os.path.join("/home", username)
f = open('manifests/index.yml')
manifests = yaml.safe_load(f)
f.close()
client = bosh_client.BoshClient("https://10.0.0.4:25555", "admin", "admin")
for m in manifests['manifests']:
print "Running errands for {0}/manifests/{1}...".format(home_dir, m['file'])
for errand in m['errands']:
print "Running errand {0}".format(errand)
task_id = client.run_errand(m['deployment-name'], errand)
client.wait_for_task(task_id)
result = client.get_task_result(task_id)
print "Errand finished with exit code {0}".format(result['exit_code'])
print "=========== STDOUT ==========="
print result['stdout'].encode('utf8')
print "=========== STDERR ==========="
print result['stderr'].encode('utf8')
return context
|
import bosh_client
import os
import yaml
def do_step(context):
settings = context.meta['settings']
username = settings["username"]
home_dir = os.path.join("/home", username)
f = open('manifests/index.yml')
manifests = yaml.safe_load(f)
f.close()
client = bosh_client.BoshClient("https://10.0.0.4:25555", "admin", "admin")
for m in manifests['manifests']:
print "Running errands for {0}/manifests/{1}...".format(home_dir, m['file'])
for errand in m['errands']:
print "Running errand {0}".format(errand)
task_id = client.run_errand(m['deployment-name'], errand)
client.wait_for_task(task_id)
result = client.get_task_result(task_id)
print "Errand finished with exit code {0}".format(result['exit_code'])
print "=========== STDOUT ==========="
print result['stdout']
print "=========== STDERR ==========="
print result['stderr']
return context
|
Add Force flag to CW events rule deletion
Use aws.Bool
Adding ec2-launch-templates resource file
Add --quiet flag to remove filtered resources from output
Without this change, output showing what is (or will be) removed can
easily be lost on the output showing filtered resources. It's useful
to be able to just see what is (or will be) affected in order to focus
on that.
Add import
add mailing list to README
add contributing guidelines
support for robomaker resources
Add Force flag to CW events rule deletion
Use aws.Bool
Adding ec2-launch-templates resource file
Add --quiet flag to remove filtered resources from output
Without this change, output showing what is (or will be) removed can
easily be lost on the output showing filtered resources. It's useful
to be able to just see what is (or will be) affected in order to focus
on that.
Add import
add mailing list to README
add contributing guidelines
support for robomaker resources
|
package resources
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func init() {
register("CloudWatchEventsRule", ListCloudWatchEventsRules)
}
func ListCloudWatchEventsRules(sess *session.Session) ([]Resource, error) {
svc := cloudwatchevents.New(sess)
resp, err := svc.ListRules(nil)
if err != nil {
return nil, err
}
resources := make([]Resource, 0)
for _, rule := range resp.Rules {
resources = append(resources, &CloudWatchEventsRule{
svc: svc,
name: rule.Name,
})
}
return resources, nil
}
type CloudWatchEventsRule struct {
svc *cloudwatchevents.CloudWatchEvents
name *string
}
func (rule *CloudWatchEventsRule) Remove() error {
_, err := rule.svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{
Name: rule.name,
Force: aws.Bool(true),
})
return err
}
func (rule *CloudWatchEventsRule) String() string {
return fmt.Sprintf("Rule: %s", *rule.name)
}
|
package resources
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func init() {
register("CloudWatchEventsRule", ListCloudWatchEventsRules)
}
func ListCloudWatchEventsRules(sess *session.Session) ([]Resource, error) {
svc := cloudwatchevents.New(sess)
resp, err := svc.ListRules(nil)
if err != nil {
return nil, err
}
resources := make([]Resource, 0)
for _, rule := range resp.Rules {
resources = append(resources, &CloudWatchEventsRule{
svc: svc,
name: rule.Name,
})
}
return resources, nil
}
type CloudWatchEventsRule struct {
svc *cloudwatchevents.CloudWatchEvents
name *string
}
func (rule *CloudWatchEventsRule) Remove() error {
_, err := rule.svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{
Name: rule.name,
})
return err
}
func (rule *CloudWatchEventsRule) String() string {
return fmt.Sprintf("Rule: %s", *rule.name)
}
|
Add a little bit of documentation.
|
// Copyright 2015, Mike Houston, see LICENSE for details.
// A bitset Bloom filter for a reduced memory password representation.
//
// See https://github.com/AndreasBriese/bbloom
package bloompw
import (
"github.com/AndreasBriese/bbloom"
)
type BloomPW struct {
Filter *bbloom.Bloom
}
// New will return a new Database interface that stores entries in
// a bloom filter
func New(filter *bbloom.Bloom) (*BloomPW, error) {
b := &BloomPW{Filter: filter}
return b, nil
}
// Has satisfies the password.DB interface
func (b BloomPW) Has(s string) (bool, error) {
return b.Filter.Has([]byte(s)), nil
}
// Has satisfies the password.DbWriter interface.
// It writes a single password to the database
func (b BloomPW) Add(s string) error {
b.Filter.Add([]byte(s))
return nil
}
// AddMultiple satisfies the password.BulkWriter interface.
// It writes a number of passwords to the database
func (b BloomPW) AddMultiple(s []string) error {
for _, v := range s {
if err := b.Add(v); err != nil {
return err
}
}
return nil
}
|
// Copyright 2015, Mike Houston, see LICENSE for details.
package bloompw
import (
"github.com/AndreasBriese/bbloom"
)
type BloomPW struct {
Filter *bbloom.Bloom
}
// New will return a new Database interface that stores entries in
// a bloom filter
func New(filter *bbloom.Bloom) (*BloomPW, error) {
b := &BloomPW{Filter: filter}
return b, nil
}
// Has satisfies the password.DB interface
func (b BloomPW) Has(s string) (bool, error) {
return b.Filter.Has([]byte(s)), nil
}
// Has satisfies the password.DbWriter interface.
// It writes a single password to the database
func (b BloomPW) Add(s string) error {
b.Filter.Add([]byte(s))
return nil
}
// AddMultiple satisfies the password.BulkWriter interface.
// It writes a number of passwords to the database
func (b BloomPW) AddMultiple(s []string) error {
for _, v := range s {
if err := b.Add(v); err != nil {
return err
}
}
return nil
}
|
Fix Hover Out when Clicking Minimize Button
|
function updateImageUrl(image_id, new_image_url) {
var image = document.getElementById(image_id);
if (image)
image.src = new_image_url;
}
function addButtonHandlers(button_id, normal_image_url, hover_image_url, click_func) {
var button = $("#"+button_id)[0];
button.onmouseover = function() {
updateImageUrl(button_id, "images/"+hover_image_url);
}
button.onmouseout = function() {
updateImageUrl(button_id, "images/"+normal_image_url);
}
button.onclick = click_func;
}
function closeWindow() { window.close(); }
function winMin() {
win.minimize();
$("#top-titlebar-minimize-button").trigger("mouseout");
}
function winRestore() { win.restore(); }
function winMax() { win.maximize(); }
function winTitleCenter(newtitle) {
if ($(".top-titlebar-text").hasClass("top-text-left")) $(".top-titlebar-text").removeClass("top-text-left").addClass("top-text-center");
$(".top-titlebar-text").html(newtitle);
}
function winTitleLeft(newtitle) {
if ($(".top-titlebar-text").hasClass("top-text-center")) $(".top-titlebar-text").removeClass("top-text-center").addClass("top-text-left");
$(".top-titlebar-text").html(newtitle);
}
|
function updateImageUrl(image_id, new_image_url) {
var image = document.getElementById(image_id);
if (image)
image.src = new_image_url;
}
function addButtonHandlers(button_id, normal_image_url, hover_image_url, click_func) {
var button = $("#"+button_id)[0];
button.onmouseover = function() {
updateImageUrl(button_id, "images/"+hover_image_url);
}
button.onmouseout = function() {
updateImageUrl(button_id, "images/"+normal_image_url);
}
button.onclick = click_func;
}
function closeWindow() { window.close(); }
function winMin() { win.minimize(); }
function winRestore() { win.restore(); }
function winMax() { win.maximize(); }
function winTitleCenter(newtitle) {
if ($(".top-titlebar-text").hasClass("top-text-left")) $(".top-titlebar-text").removeClass("top-text-left").addClass("top-text-center");
$(".top-titlebar-text").html(newtitle);
}
function winTitleLeft(newtitle) {
if ($(".top-titlebar-text").hasClass("top-text-center")) $(".top-titlebar-text").removeClass("top-text-center").addClass("top-text-left");
$(".top-titlebar-text").html(newtitle);
}
|
Update CLI with new property names
|
#!/usr/bin/env node
'use strict';
var pkg = require('./package.json');
var klParkingSpots = require('./');
var argv = process.argv.slice(2);
var columnify = require('columnify')
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Example',
' kl-parking',
'',
' => PLACE SPOTS',
' Sgwang 467',
' Lowyat 634',
' Lot10 461',
' Fahrenheit 283',
' Starhill 1030',
' Pavilion 1207',
' Klcc 1526'
].join('\n'));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
klParkingSpots(function(parkingSpots){
var columns = columnify(parkingSpots, {
columns: ['name', 'lot'],
config: {
lot: { align: 'right' }
}
});
console.log(columns);
});
|
#!/usr/bin/env node
'use strict';
var pkg = require('./package.json');
var klParkingSpots = require('./');
var argv = process.argv.slice(2);
var columnify = require('columnify')
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Example',
' kl-parking',
'',
' => PLACE SPOTS',
' Sgwang 467',
' Lowyat 634',
' Lot10 461',
' Fahrenheit 283',
' Starhill 1030',
' Pavilion 1207',
' Klcc 1526'
].join('\n'));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
klParkingSpots(function(parkingSpots){
var columns = columnify(parkingSpots, {
columns: ['place', 'spots'],
config: {
spots: { align: 'right' }
}
});
console.log(columns);
});
|
Change tooltip delay to 3secs
|
(function () {
// event triggers
$('a.person-link').live('click.linkPerson', function (e) {
var $this = $(this);
// Preserve hashtag if the current page is of a person
if (window.currentPage == 'person' && location.hash) {
location.href = $this.attr('href') + location.hash;
return false;
}
});
/* Warm-up scripts */
$(window).load(onLoad);
function onLoad() {
$('.person-img').clipImage();
$('.tooltipped:not(.tooltipped-delay)').tooltip();
$('.tooltipped-delay').tooltip({
delay: {
show: 3000,
hide: 0
}
});
};
}());
|
(function () {
// event triggers
$('a.person-link').live('click.linkPerson', function (e) {
var $this = $(this);
// Preserve hashtag if the current page is of a person
if (window.currentPage == 'person' && location.hash) {
location.href = $this.attr('href') + location.hash;
return false;
}
});
/* Warm-up scripts */
$(window).load(onLoad);
function onLoad() {
$('.person-img').clipImage();
$('.tooltipped:not(.tooltipped-delay)').tooltip();
$('.tooltipped-delay').tooltip({
delay: {
show: 1000,
hide: 0
}
});
};
}());
|
Put back the trailing / and fix it in the JS model
|
from django.conf.urls import patterns, url
from openbudget.apps.projects.views import api
urlpatterns = patterns('',
url(r'^$',
api.ProjectList.as_view(),
name='project-list'
),
url(r'^states/$',
api.StateList.as_view(),
name='state-list'
),
url(
r'^(?P<uuid>\w+)/$',
api.ProjectDetail.as_view(),
name='project-detail'
),
url(
r'^states/(?P<uuid>\w+)/$',
api.StateDetail.as_view(),
name='state-detail'
),
)
|
from django.conf.urls import patterns, url
from openbudget.apps.projects.views import api
urlpatterns = patterns('',
url(r'^$',
api.ProjectList.as_view(),
name='project-list'
),
url(r'^states/$',
api.StateList.as_view(),
name='state-list'
),
url(
r'^(?P<uuid>\w+)/$',
api.ProjectDetail.as_view(),
name='project-detail'
),
url(
r'^states/(?P<uuid>\w+)$',
api.StateDetail.as_view(),
name='state-detail'
),
)
|
Add test for localized spoken language name
|
const test = require('tap').test;
const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js');
const fakeStage = {
textToSpeechLanguage: null
};
const fakeRuntime = {
getTargetForStage: () => fakeStage,
on: () => {} // Stub out listener methods used in constructor.
};
const ext = new TextToSpeech(fakeRuntime);
test('if no language is saved in the project, use default', t => {
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if an unsupported language is dropped onto the set language block, use default', t => {
ext.setLanguage({LANGUAGE: 'nope'});
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if a supported language name is dropped onto the set language block, use it', t => {
ext.setLanguage({LANGUAGE: 'español'});
t.strictEqual(ext.getCurrentLanguage(), 'es');
t.end();
});
test('get the extension locale for a supported locale that differs', t => {
ext.setLanguage({LANGUAGE: 'ja-hira'});
t.strictEqual(ext.getCurrentLanguage(), 'ja');
t.end();
});
test('use localized spoken language name in place of localized written language name', t => {
ext.getEditorLanguage = () => 'es';
const languageMenu = ext.getLanguageMenu();
const localizedNameForChineseInSpanish = languageMenu.find(el => el.value === 'zh-cn').text;
t.strictEqual(localizedNameForChineseInSpanish, 'Chino (Mandarín)'); // i.e. should not be 'Chino (simplificado)'
t.end();
});
|
const test = require('tap').test;
const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js');
const fakeStage = {
textToSpeechLanguage: null
};
const fakeRuntime = {
getTargetForStage: () => fakeStage,
on: () => {} // Stub out listener methods used in constructor.
};
const ext = new TextToSpeech(fakeRuntime);
test('if no language is saved in the project, use default', t => {
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if an unsupported language is dropped onto the set language block, use default', t => {
ext.setLanguage({LANGUAGE: 'nope'});
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if a supported language name is dropped onto the set language block, use it', t => {
ext.setLanguage({LANGUAGE: 'español'});
t.strictEqual(ext.getCurrentLanguage(), 'es');
t.end();
});
test('get the extension locale for a supported locale that differs', t => {
ext.setLanguage({LANGUAGE: 'ja-hira'});
t.strictEqual(ext.getCurrentLanguage(), 'ja');
t.end();
});
|
Make build separate src and test directories
|
var gulp = require('gulp');
var path = require('path');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var typescript = require('gulp-typescript');
var dirs = {
build: path.join(__dirname, 'build'),
src: path.join(__dirname, 'src'),
test: path.join(__dirname, 'test'),
typings: path.join(__dirname, 'typings')
};
var files = {
src: path.join(dirs.src, '**', '*.ts'),
test: path.join(dirs.test, '**', '*.ts'),
typings: path.join(dirs.typings, '**', '*.d.ts'),
ts: path.join(__dirname, '{src,test}', '**', '*.ts')
};
var project = typescript.createProject({
removeComments: false,
noImplicitAny: true,
noLib: false,
target: 'ES5',
module: 'commonjs',
declarationFiles: true,
noExternalResolve: true
});
gulp.task('lint', function() {
return gulp.src([files.src, files.test])
.pipe(tslint())
.pipe(tslint.report('prose'));
});
gulp.task('scripts', function() {
var ts = gulp.src([files.ts, files.typings])
.pipe(typescript(project));
return ts.js.pipe(gulp.dest(dirs.build));
});
gulp.task('test', function(callback) {
return runSequence('lint', 'scripts', callback);
});
|
var gulp = require('gulp');
var path = require('path');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var typescript = require('gulp-typescript');
var dirs = {
build: path.join(__dirname, 'build'),
src: path.join(__dirname, 'src'),
test: path.join(__dirname, 'test'),
typings: path.join(__dirname, 'typings')
};
var files = {
src: path.join(dirs.src, '**', '*.ts'),
test: path.join(dirs.test, '**', '*.ts'),
typings: path.join(dirs.typings, '**', '*.d.ts')
};
var project = typescript.createProject({
removeComments: false,
noImplicitAny: true,
noLib: false,
target: 'ES5',
module: 'commonjs',
declarationFiles: true,
noExternalResolve: true
});
gulp.task('lint', function() {
return gulp.src([files.src, files.test])
.pipe(tslint())
.pipe(tslint.report('prose'));
});
gulp.task('scripts', function() {
var ts = gulp.src([files.src, files.test, files.typings])
.pipe(typescript(project));
return ts.js.pipe(gulp.dest(dirs.build));
});
gulp.task('test', function(callback) {
return runSequence('lint', 'scripts', callback);
});
|
Add equlaity comparisons to LineChange class.
|
#!/usr/bin/env python3
from enum import Enum
class LineChange:
class ChangeType(Enum):
added = 1
deleted = 2
modified = 3
def __init__(self, line_number=None, change_type=None, file_path=None, commit_sha=None):
self.line_number = line_number
self.change_type = change_type
self.file_path = file_path
self.commit_sha = commit_sha
self.author = None
def __str__(self):
return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items())
def __repr__(self):
return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self))
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
|
#!/usr/bin/env python3
from enum import Enum
class LineChange:
class ChangeType(Enum):
added = 1
deleted = 2
modified = 3
def __init__(self, number=None, change_type=None, filename=None, commit=None):
self.number = number
self.change_type = change_type
self.filename = filename
self.commit = commit
self.author = None
def __str__(self):
return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items())
def __repr__(self):
return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self))
|
Remove some debug logging from the frontend
|
import { put, call, fork } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga';
import { getBranches, register } from './resources';
import {
BRANCH_LIST_REQUESTED, branchListUpdated,
registerStart,
REGISTER_REQUESTED, registerSuccess,
clearPageError, pageError,
} from './actions';
export function* fetchBranchList() {
try {
yield put(clearPageError());
const { branches } = yield call(getBranches);
yield put(branchListUpdated(branches));
yield put(registerStart());
} catch (error) {
yield put(pageError('There was an error loading the page content'));
}
}
export function* registerMember({ payload }) {
const { member, onSuccess, onFailure } = payload;
try {
yield put(clearPageError());
yield call(register, member);
yield put(registerSuccess());
yield call(onSuccess);
} catch (error) {
yield put(pageError('There was an error saving your changes'));
yield call(onFailure);
}
}
export function* watchBranchListRequest() {
yield* takeLatest(BRANCH_LIST_REQUESTED, fetchBranchList);
}
export function* watchRegisterRequest() {
yield* takeLatest(REGISTER_REQUESTED, registerMember);
}
export default function* rootSaga() {
yield [
fork(watchBranchListRequest),
fork(watchRegisterRequest),
];
}
|
import { put, call, fork } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga';
import { getBranches, register } from './resources';
import {
BRANCH_LIST_REQUESTED, branchListUpdated,
registerStart,
REGISTER_REQUESTED, registerSuccess,
clearPageError, pageError,
} from './actions';
export function* fetchBranchList() {
try {
yield put(clearPageError());
const { branches } = yield call(getBranches);
yield put(branchListUpdated(branches));
yield put(registerStart());
} catch (error) {
yield put(pageError('There was an error loading the page content'));
}
}
export function* registerMember({ payload }) {
const { member, onSuccess, onFailure } = payload;
try {
yield put(clearPageError());
yield call(register, member);
yield put(registerSuccess());
yield call(onSuccess);
} catch (error) {
console.log('ERROR', error);
yield put(pageError('There was an error saving your changes'));
yield call(onFailure);
}
}
export function* watchBranchListRequest() {
yield* takeLatest(BRANCH_LIST_REQUESTED, fetchBranchList);
}
export function* watchRegisterRequest() {
yield* takeLatest(REGISTER_REQUESTED, registerMember);
}
export default function* rootSaga() {
yield [
fork(watchBranchListRequest),
fork(watchRegisterRequest),
];
}
|
Define baseURL variable to get base_url func from codeigniter
|
<?php
echo doctype('html5');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php
$meta = array(
array(
'name' => 'Content-Type',
'content' => 'text/html; charset=UTF-8',
'type' => 'equiv'
),
array(
'name' => 'X-UA-Compatible',
'content' => 'IE=edge',
'type' => 'equiv'
),
array(
'name' => 'viewport',
'content' => 'width=device-width, initial-scale=1'
)
);
echo meta($meta);
echo get_title();
echo get_css();
if(get_favicon()){
echo link_tag(get_favicon());
}
?>
<script type="text/javascript">
var baseURL = '<?php echo base_url();?>';
</script>
</head>
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="col-md-3 left_col">
<?php $this->load->view('sidebar'); ?>
</div>
<div class="top_nav">
<?php $this->load->view('top-nav'); ?>
</div>
<div class="right_col" role="main">
|
<?php
echo doctype('html5');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php
$meta = array(
array(
'name' => 'Content-Type',
'content' => 'text/html; charset=UTF-8',
'type' => 'equiv'
),
array(
'name' => 'X-UA-Compatible',
'content' => 'IE=edge',
'type' => 'equiv'
),
array(
'name' => 'viewport',
'content' => 'width=device-width, initial-scale=1'
)
);
echo meta($meta);
echo get_title();
echo get_css();
if(get_favicon()){
echo link_tag(get_favicon());
}
?>
</head>
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="col-md-3 left_col">
<?php $this->load->view('sidebar'); ?>
</div>
<div class="top_nav">
<?php $this->load->view('top-nav'); ?>
</div>
<div class="right_col" role="main">
|
Update huge wave zombie spawn delay.
|
package avs.models;
public class ZombieSummoner implements Runnable{
private Thread thread;
private boolean isHugeWave;
public ZombieSummoner(){
this.thread = new Thread(this);
}
public void run(){
try {
Thread.sleep(30000);
while (true) {
if(!isHugeWave){
Game.getInstance().createZombie();
Thread.sleep(10000);
}else{
Thread.sleep(3000);
for(int i = 0; i < 10; i++){
Game.getInstance().createZombie();
Thread.sleep(3000);
}
isHugeWave = false;
}
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void start(){
this.thread.start();
}
public void setIsHugeWave(boolean isHugeWave){
this.isHugeWave = isHugeWave;
}
public boolean getIsHugeWave(){
return this.isHugeWave;
}
}
|
package avs.models;
public class ZombieSummoner implements Runnable{
private Thread thread;
private boolean isHugeWave;
public ZombieSummoner(){
this.thread = new Thread(this);
}
public void run(){
try {
Thread.sleep(30000);
while (true) {
if(!isHugeWave){
Game.getInstance().createZombie();
Thread.sleep(10000);
}else{
Thread.sleep(3000);
for(int i = 0; i < 10; i++){
Game.getInstance().createZombie();
Thread.sleep(5000);
}
isHugeWave = false;
}
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void start(){
this.thread.start();
}
public void setIsHugeWave(boolean isHugeWave){
this.isHugeWave = isHugeWave;
}
public boolean getIsHugeWave(){
return this.isHugeWave;
}
}
|
Add possibility to override MultiBaseLocalDiskRepositoryManager
Add possibility to override MultiBaseLocalDiskRepositoryManager in lib
module by making GitRepositoryManagerModule as replaceable with module
that is annotated with 'git-manager' name.
Bug: Issue 15407
Change-Id: Ie470a035167225494d2b6f1977a0f7988f164aa4
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.ModuleImpl;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;
/**
* Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
* LocalDiskRepositoryManager} if needed.
*/
@ModuleImpl(name = GitRepositoryManagerModule.MANAGER_MODULE)
public class GitRepositoryManagerModule extends LifecycleModule {
public static final String MANAGER_MODULE = "git-manager";
private final RepositoryConfig repoConfig;
@Inject
public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
this.repoConfig = repoConfig;
}
@Override
protected void configure() {
if (repoConfig.getAllBasePaths().isEmpty()) {
install(new LocalDiskRepositoryManager.Module());
} else {
install(new MultiBaseLocalDiskRepositoryManager.Module());
}
}
}
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;
/**
* Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
* LocalDiskRepositoryManager} if needed.
*/
public class GitRepositoryManagerModule extends LifecycleModule {
private final RepositoryConfig repoConfig;
@Inject
public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
this.repoConfig = repoConfig;
}
@Override
protected void configure() {
if (repoConfig.getAllBasePaths().isEmpty()) {
install(new LocalDiskRepositoryManager.Module());
} else {
install(new MultiBaseLocalDiskRepositoryManager.Module());
}
}
}
|
Remove callback url and bring uploads together
|
"""
Predict app's urls
"""
#
# pylint: disable=bad-whitespace
#
from django.conf.urls import patterns, include, url
from .views import *
def url_tree(regex, *urls):
"""Quick access to stitching url patterns"""
return url(regex, include(patterns('', *urls)))
urlpatterns = patterns('',
url(r'^$', Datasets.as_view(), name="view_my_datasets"),
url_tree(r'^upload/',
url(r'^$', UploadChoices.as_view(), name="upload"),
url(r'^(?P<type>[\w-]+)/', UploadView.as_view(), name="upload"),
),
url_tree(r'^(?P<slug>\w{32})/',
url(r'^$', DatasetView.as_view(), name="view_single_dataset"),
url(r'^note/$', AddNote.as_view(), name="add_note"),
),
)
|
"""
Predict app's urls
"""
#
# pylint: disable=bad-whitespace
#
from django.conf.urls import patterns, include, url
from .views import *
def url_tree(regex, *urls):
"""Quick access to stitching url patterns"""
return url(regex, include(patterns('', *urls)))
urlpatterns = patterns('',
url(r'^$', Datasets.as_view(), name="view_my_datasets"),
url_tree(r'^upload/',
url(r'^$', UploadChoices.as_view(), name="upload"),
url(r'^manual/$', UploadManual.as_view(), name="upload_manual"),
url_tree(r'^(?P<type>[\w-]+)/',
url(r'^$', UploadView.as_view(), name="upload"),
url(r'^(?P<fastq>[\w-]+)/$', UploadView.as_view(), name="upload"),
),
),
url_tree(r'^(?P<slug>\w{32})/',
url(r'^$', DatasetView.as_view(), name="view_single_dataset"),
url(r'^callback/$', Callback.as_view(), name="callback"),
url(r'^note/$', AddNote.as_view(), name="add_note"),
),
)
|
Update grunt file after switch to grunt-contrib-sass
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
autoprefixer: {
options: {
browsers: ['last 3 iOS versions', 'Android 2.3', 'Android 4', 'last 2 Chrome versions']
},
multiple_files: {
flatten: true,
src: 'test/*.css', // -> src/css/file1.css, src/css/file2.css
},
},
sass: {
dist: {
options: {
style: 'nested'
},
files: {
'test/test.css': 'test/test.scss'
}
}
}
});
// Default task(s).
grunt.registerTask('default', ['sass', 'autoprefixer']);
};
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
autoprefixer: {
options: {
browsers: ['last 3 iOS versions', 'Android 2.3', 'Android 4', 'last 2 Chrome versions']
},
multiple_files: {
flatten: true,
src: 'test/*.css', // -> src/css/file1.css, src/css/file2.css
},
},
sass: {
dist: {
options: {
includePaths: ['bower_components/'],
outputStyle: 'nested'
},
files: {
'test/test.css': 'test/test.scss'
}
}
}
});
// Default task(s).
grunt.registerTask('default', ['sass', 'autoprefixer']);
};
|
Fix method visibility after refactoring.
|
/*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.metrics.core.impl.mapper;
import org.hawkular.metrics.core.api.NumericMetric;
import com.google.common.base.Function;
/**
* @author John Sanda
*/
public abstract class MetricMapper<T> implements Function<NumericMetric, T> {
@Override
public T apply(NumericMetric metric) {
if (metric == null) {
throw new NoResultsException();
}
return doApply(metric);
}
public abstract T doApply(NumericMetric metric);
}
|
/*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.metrics.core.impl.mapper;
import org.hawkular.metrics.core.api.NumericMetric;
import com.google.common.base.Function;
/**
* @author John Sanda
*/
public abstract class MetricMapper<T> implements Function<NumericMetric, T> {
@Override
public T apply(NumericMetric metric) {
if (metric == null) {
throw new NoResultsException();
}
return doApply(metric);
}
abstract T doApply(NumericMetric metric);
}
|
Make South optional since we now support Django migrations.
|
import io
from setuptools import setup, find_packages
def read(*filenames, **kwargs):
"""
From http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
"""
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
setup(
name="djangocms-markdown",
version='0.3.0',
description=read('DESCRIPTION'),
long_description=read('README.md'),
license='The MIT License',
platforms=['OS Independent'],
keywords='django, django-cms, plugin, markdown, editor',
author='Olle Vidner',
author_email='olle@vidner.se',
url="https://github.com/ovidner/djangocms-markdown",
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'South',
'django-cms>=3.0.0',
'django-markdown-deux',
], extras_require = {
'Django_less_than_17': ["South>=1.0"]
}
)
|
import io
from setuptools import setup, find_packages
def read(*filenames, **kwargs):
"""
From http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
"""
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
setup(
name="djangocms-markdown",
version='0.3.0',
description=read('DESCRIPTION'),
long_description=read('README.md'),
license='The MIT License',
platforms=['OS Independent'],
keywords='django, django-cms, plugin, markdown, editor',
author='Olle Vidner',
author_email='olle@vidner.se',
url="https://github.com/ovidner/djangocms-markdown",
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'South',
'django-cms>=3.0.0',
'django-markdown-deux',
],
)
|
Remove the test for / via the API.
Makes no sense; the root of the API is /api.
|
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
}
|
package hello;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {
@Autowired
private MockMvc mvc;
@Test
public void getRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void getJsonRoot() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
|
Modify the test for the new function name on RisFieldsMapping
|
<?php
namespace Funstaff\RefLibRis\Tests;
use Funstaff\RefLibRis\RisFieldsMapping;
/**
* RisFieldsMappingTest
*
* @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
*/
class RisFieldsMappingTest extends \PHPUnit_Framework_TestCase
{
/**
* testFindField
*/
public function testFindField()
{
$fieldMapping = new RisFieldsMapping($this->getMapping());
$this->assertEquals('CN', $fieldMapping->findRisFieldByFieldName('isbn'));
$this->assertNull($fieldMapping->findRisFieldByFieldName('ZZ'));
}
private function getMapping()
{
return [
'TY' => ['type'],
'CN' => ['isbn', 'issn'],
'LA' => ['language'],
];
}
}
|
<?php
namespace Funstaff\RefLibRis\Tests;
use Funstaff\RefLibRis\RisFieldsMapping;
/**
* RisFieldsMappingTest
*
* @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
*/
class RisFieldsMappingTest extends \PHPUnit_Framework_TestCase
{
/**
* testFindField
*/
public function testFindField()
{
$fieldMapping = new RisFieldsMapping($this->getMapping());
$this->assertEquals('CN', $fieldMapping->findTagByField('isbn'));
$this->assertNull($fieldMapping->findTagByField('ZZ'));
}
private function getMapping()
{
return [
'TY' => ['type'],
'CN' => ['isbn', 'issn'],
'LA' => ['language'],
];
}
}
|
Load the missing image synchronously, improve assert error messages.
We need to load sync so that the error is logged while our log collector is in
place. Yay testing.
|
//
// $Id$
package playn.java;
import org.junit.Test;
import static org.junit.Assert.*;
import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;
/**
* Tests various JavaImage behavior.
*/
public class JavaImageTest extends AbstractPlayNTest {
@Test
public void testMissingImage() {
final StringBuilder buf = new StringBuilder();
PlayN.log().setCollector(new Log.Collector() {
public void logged(Log.Level level, String msg, Throwable cause) {
buf.append(msg).append("\n");
}
});
Image missing;
try {
missing = PlayN.assets().getImageSync("missing.png");
} finally {
PlayN.log().setCollector(null);
}
assertNotNull(missing);
// ensure that width/height do not NPE
missing.width();
missing.height();
// TODO: depending on the error text is somewhat fragile, but I want to be sure that a
// reasonably appropriate error was logged
String errlog = buf.toString();
assertTrue(errlog + " must contain 'Could not load image'",
errlog.startsWith("Could not load image"));
assertTrue(errlog + " must contain 'missing.png'",
errlog.contains("missing.png"));
}
}
|
//
// $Id$
package playn.java;
import org.junit.Test;
import static org.junit.Assert.*;
import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;
/**
* Tests various JavaImage behavior.
*/
public class JavaImageTest extends AbstractPlayNTest {
@Test
public void testMissingImage() {
final StringBuilder buf = new StringBuilder();
PlayN.log().setCollector(new Log.Collector() {
public void logged(Log.Level level, String msg, Throwable cause) {
buf.append(msg).append("\n");
}
});
Image missing;
try {
missing = PlayN.assets().getImage("missing.png");
} finally {
PlayN.log().setCollector(null);
}
assertNotNull(missing);
// ensure that width/height do not NPE
missing.width();
missing.height();
// TODO: depending on the error text is somewhat fragile, but I want to be sure that a
// reasonably appropriate error was logged
String errlog = buf.toString();
assertTrue(errlog.startsWith("Could not load image"));
assertTrue(errlog.contains("missing.png"));
}
}
|
Fix a typo in an error
|
function normalizeName(name) {
if (name.charAt(0) === '-') {
name = name.substr(1)
}
if (name.charAt(0) === '-') {
name = name.substr(1)
}
return name
}
class Option {
constructor(name, parent) {
if (!parent) {
throw new Error('An option must have a parent command')
}
if (!name || typeof name !== 'string') {
throw new Error('The first argument of the Option constructor must be its name (a non-empty string)')
}
name = normalizeName(name)
this.parent = parent
this.config = {
name,
id: `${parent.config.id}#${name}`,
}
}
aliases(...aliases) {
this.config.aliases = aliases.map((a) => normalizeName(a))
return this
}
shared() {
this.parent.sharedOptions.push(this.config.id)
return this
}
command(...args) {
return this.parent.command(...args)
}
option(...args) {
return this.parent.option(...args)
}
handle(...args) {
return this.parent.handle(...args)
}
end() {
return this.parent
}
}
module.exports = Option
|
function normalizeName(name) {
if (name.charAt(0) === '-') {
name = name.substr(1)
}
if (name.charAt(0) === '-') {
name = name.substr(1)
}
return name
}
class Option {
constructor(name, parent) {
if (!parent) {
throw new Error('An option must have a parent command')
}
if (!name || typeof name !== 'string') {
throw new Error('The first argument of the Option constructor must be a its name (a non-empty string)')
}
name = normalizeName(name)
this.parent = parent
this.config = {
name,
id: `${parent.config.id}#${name}`,
}
}
aliases(...aliases) {
this.config.aliases = aliases.map((a) => normalizeName(a))
return this
}
shared() {
this.parent.sharedOptions.push(this.config.id)
return this
}
command(...args) {
return this.parent.command(...args)
}
option(...args) {
return this.parent.option(...args)
}
handle(...args) {
return this.parent.handle(...args)
}
end() {
return this.parent
}
}
module.exports = Option
|
Add the score to Engine.chat return values
|
# -*- coding: utf-8 -*-
class Engine:
def __init__(self,
response_pairs,
knowledge={}):
self.response_pairs = response_pairs
self.knowledge = knowledge
def chat(self, user_utterance, context):
best_score = 0
best_response_pair = None
best_captured = {}
for response_pair in self.response_pairs:
captured = response_pair.match(user_utterance, self.knowledge)
if captured is None:
continue
score = response_pair.score(captured, context, self.knowledge)
if best_score < score:
best_score, best_response_pair, best_captured = score, response_pair, captured
response, new_context = best_response_pair.generate(best_captured, context, self.knowledge)
return response, new_context, best_score
|
# -*- coding: utf-8 -*-
class Engine:
def __init__(self,
response_pairs,
knowledge={}):
self.response_pairs = response_pairs
self.knowledge = knowledge
def chat(self, user_utterance, context):
best_score = 0
best_response_pair = None
best_captured = {}
for response_pair in self.response_pairs:
captured = response_pair.match(user_utterance, self.knowledge)
if captured is None:
continue
score = response_pair.score(captured, context, self.knowledge)
if best_score < score:
best_score, best_response_pair, best_captured = score, response_pair, captured
return best_response_pair.generate(best_captured, context, self.knowledge)
|
Add API to reset CxxModuleWrapper's module pointer
Reviewed By: mhorowitz
Differential Revision: D4914335
fbshipit-source-id: f28f57c2e74d590dacfb85d8027747837f768fdc
|
// Copyright 2004-present Facebook. All Rights Reserved.
package com.facebook.react.cxxbridge;
import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.NativeModule;
import com.facebook.soloader.SoLoader;
/**
* A Java Object which represents a cross-platform C++ module
*
* This module implements the NativeModule interface but will never be invoked from Java,
* instead the underlying Cxx module will be extracted by the bridge and called directly.
*/
@DoNotStrip
public class CxxModuleWrapperBase implements NativeModule
{
static {
SoLoader.loadLibrary(CatalystInstanceImpl.REACT_NATIVE_LIB);
}
@DoNotStrip
private HybridData mHybridData;
@Override
public native String getName();
@Override
public void initialize() {
// do nothing
}
@Override
public boolean canOverrideExistingModule() {
return false;
}
@Override
public boolean supportsWebWorkers() {
return false;
}
@Override
public void onCatalystInstanceDestroy() {
mHybridData.resetNative();
}
// For creating a wrapper from C++, or from a derived class.
protected CxxModuleWrapperBase(HybridData hd) {
mHybridData = hd;
}
// Replace the current native module held by this wrapper by a new instance
protected void resetModule(HybridData hd) {
if (hd != mHybridData) {
mHybridData.resetNative();
mHybridData = hd;
}
}
}
|
// Copyright 2004-present Facebook. All Rights Reserved.
package com.facebook.react.cxxbridge;
import java.util.Map;
import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.NativeModule;
import com.facebook.soloader.SoLoader;
/**
* A Java Object which represents a cross-platform C++ module
*
* This module implements the NativeModule interface but will never be invoked from Java,
* instead the underlying Cxx module will be extracted by the bridge and called directly.
*/
@DoNotStrip
public class CxxModuleWrapperBase implements NativeModule
{
static {
SoLoader.loadLibrary(CatalystInstanceImpl.REACT_NATIVE_LIB);
}
@DoNotStrip
private HybridData mHybridData;
@Override
public native String getName();
@Override
public void initialize() {
// do nothing
}
@Override
public boolean canOverrideExistingModule() {
return false;
}
@Override
public boolean supportsWebWorkers() {
return false;
}
@Override
public void onCatalystInstanceDestroy() {
mHybridData.resetNative();
}
// For creating a wrapper from C++, or from a derived class.
protected CxxModuleWrapperBase(HybridData hd) {
mHybridData = hd;
}
}
|
Implement more props for Header
Makes it more flexible to reuse in footer
|
import React from 'react';
import cn from 'classnames';
export default class Header extends React.Component {
render() {
const h1Style = {
margin: 0,
float: 'left'
};
const aStyle = {
float: 'right',
fontSize: '15px',
fontFamily: 'belwe'
};
const isLargeClass = this.props.isLarge && 'large' ? 'top large' : 'small';
return (
<header className={cn('Header', isLargeClass)}>
<div className="margin-0-auto max-width-1200">
<h1 className="fs-25px tt-uppercase f-tovs" style={ h1Style }>theoddvisualstuff</h1>
<a href={this.props.linkSrc} style={ aStyle }>{this.props.linkName}</a>
</div>
</header>
);
}
}
|
import React from 'react';
export default class Header extends React.Component {
render() {
const h1Style = {
margin: 0,
padding: '47px 0 0 47px',
float: 'left'
};
const aStyle = {
float: 'right',
// marginTop: '54px',
marginTop: '60px',
marginRight: '45px',
fontSize: '15px',
fontFamily: 'belwe'
};
return (
<header className="header">
<div className="margin-0-auto max-width-1200">
<h1 className="fs-25px tt-uppercase f-tovs" style={ h1Style }>theoddvisualstuff</h1>
<a href="#home" style={ aStyle }>Terug naar Aarde</a>
</div>
</header>
);
}
}
|
Change how default options were set
It previously ignored the case when ngModuleName was not set and
options was defined. It should now set the default ngModuleName when
needed if options was defined for any reason.
|
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var generator = require('loopback-sdk-angular');
module.exports = function (options) {
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
cb();
return;
}
var app;
try {
app = require(file.path);
// Incase options is undefined.
options = options || { ngModuleName: 'lbServices', apiUrl: undefined };
options.ngModuleName = options.ngModuleName || 'lbServices';
options.apiUrl = options.apiUrl || app.get('restApiRoot') || '/api';
gutil.log('Loaded LoopBack app', gutil.colors.magenta(file.path));
gutil.log('Generating',
gutil.colors.magenta(options.ngModuleName),
'for the API endpoint',
gutil.colors.magenta(options.apiUrl)
);
var script = generator.services(
app,
options.ngModuleName,
options.apiUrl
);
file.contents = new Buffer(script);
gutil.log('Generated Angular services file.');
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-loopback-sdk-angular', err));
}
cb();
});
};
|
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var generator = require('loopback-sdk-angular');
module.exports = function (options) {
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.emit('error', new gutil.PluginError('gulp-loopback-sdk-angular', 'Input file ' + file.path + ' not found.'));
cb();
return;
}
var app;
try {
app = require(file.path);
options = options || { ngModuleName: 'lbServices', apiUrl: undefined };
options.apiUrl = options.apiUrl || app.get('restApiRoot') || '/api';
gutil.log('Loaded LoopBack app', gutil.colors.magenta(file.path));
gutil.log('Generating',
gutil.colors.magenta(options.ngModuleName),
'for the API endpoint',
gutil.colors.magenta(options.apiUrl)
);
var script = generator.services(
app,
options.ngModuleName,
options.apiUrl
);
file.contents = new Buffer(script);
gutil.log('Generated Angular services file.');
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-loopback-sdk-angular', err));
}
cb();
});
};
|
Configure logging handlers before submodule imports
- Fix #474
- Fix #475
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Radim Rehurek <me@radimrehurek.com>
#
# This code is distributed under the terms and conditions
# from the MIT License (MIT).
#
"""
Utilities for streaming to/from several file-like data storages: S3 / HDFS / local
filesystem / compressed files, and many more, using a simple, Pythonic API.
The streaming makes heavy use of generators and pipes, to avoid loading
full file contents into memory, allowing work with arbitrarily large files.
The main functions are:
* `open()`, which opens the given file for reading/writing
* `parse_uri()`
* `s3_iter_bucket()`, which goes over all keys in an S3 bucket in parallel
* `register_compressor()`, which registers callbacks for transparent compressor handling
"""
import logging
from smart_open import version
logger = logging.getLogger(__name__)
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Radim Rehurek <me@radimrehurek.com>
#
# This code is distributed under the terms and conditions
# from the MIT License (MIT).
#
"""
Utilities for streaming to/from several file-like data storages: S3 / HDFS / local
filesystem / compressed files, and many more, using a simple, Pythonic API.
The streaming makes heavy use of generators and pipes, to avoid loading
full file contents into memory, allowing work with arbitrarily large files.
The main functions are:
* `open()`, which opens the given file for reading/writing
* `parse_uri()`
* `s3_iter_bucket()`, which goes over all keys in an S3 bucket in parallel
* `register_compressor()`, which registers callbacks for transparent compressor handling
"""
import logging
from smart_open import version
from .smart_open_lib import open, parse_uri, smart_open, register_compressor
from .s3 import iter_bucket as s3_iter_bucket
__all__ = [
'open',
'parse_uri',
'register_compressor',
's3_iter_bucket',
'smart_open',
]
__version__ = version.__version__
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
|
Check Sender.track assigning for nil
It does not make sense to have Sender.track == nil
|
package webrtc
import (
"fmt"
"github.com/pkg/errors"
)
// RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid.
type RTPTransceiver struct {
Mid string
Sender *RTPSender
Receiver *RTPReceiver
Direction RTPTransceiverDirection
// currentDirection RTPTransceiverDirection
// firedDirection RTPTransceiverDirection
// receptive bool
stopped bool
}
func (t *RTPTransceiver) setSendingTrack(track *Track) error {
if track == nil {
return fmt.Errorf("Track must not be nil")
}
t.Sender.track = track
switch t.Direction {
case RTPTransceiverDirectionRecvonly:
t.Direction = RTPTransceiverDirectionSendrecv
case RTPTransceiverDirectionInactive:
t.Direction = RTPTransceiverDirectionSendonly
default:
return errors.Errorf("Invalid state change in RTPTransceiver.setSending")
}
return nil
}
// Stop irreversibly stops the RTPTransceiver
func (t *RTPTransceiver) Stop() error {
if t.Sender != nil {
if err := t.Sender.Stop(); err != nil {
return err
}
}
if t.Receiver != nil {
if err := t.Receiver.Stop(); err != nil {
return err
}
}
return nil
}
|
package webrtc
import (
"github.com/pkg/errors"
)
// RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid.
type RTPTransceiver struct {
Mid string
Sender *RTPSender
Receiver *RTPReceiver
Direction RTPTransceiverDirection
// currentDirection RTPTransceiverDirection
// firedDirection RTPTransceiverDirection
// receptive bool
stopped bool
}
func (t *RTPTransceiver) setSendingTrack(track *Track) error {
t.Sender.track = track
switch t.Direction {
case RTPTransceiverDirectionRecvonly:
t.Direction = RTPTransceiverDirectionSendrecv
case RTPTransceiverDirectionInactive:
t.Direction = RTPTransceiverDirectionSendonly
default:
return errors.Errorf("Invalid state change in RTPTransceiver.setSending")
}
return nil
}
// Stop irreversibly stops the RTPTransceiver
func (t *RTPTransceiver) Stop() error {
if t.Sender != nil {
if err := t.Sender.Stop(); err != nil {
return err
}
}
if t.Receiver != nil {
if err := t.Receiver.Stop(); err != nil {
return err
}
}
return nil
}
|
Rename postcss plugin name string
|
'use-strict';
const path = require('path');
const postcss = require('postcss');
const cssImport = require('postcss-import');
const atRulesVars = require('postcss-at-rules-variables');
const each = require('postcss-each');
const mixins = require('postcss-mixins');
const nested = require('postcss-nested');
const customProperties = require('postcss-custom-properties');
const conditionals = require('postcss-conditionals');
const customMedia = require('postcss-custom-media');
const calc = require('postcss-calc');
const colorFunction = require('postcss-color-function');
const mediaQueryPacker = require('css-mqpacker');
const autoprefixer = require('autoprefixer');
const mixinsPath = path.join(
path.dirname(require.resolve('@wearegenki/css')),
'src/mixins',
);
module.exports = postcss.plugin('ui-postcss', (opts = {}) => {
const mixinsDir = [opts.mixinsDir] || [];
mixinsDir.push(mixinsPath);
return postcss()
.use(cssImport({ path: opts.importPath || ['src'] }))
.use(atRulesVars)
.use(each)
.use(mixins({ mixinsDir }))
.use(nested)
.use(customProperties)
.use(conditionals)
.use(customMedia)
.use(calc({ warnWhenCannotResolve: opts.verbose }))
.use(colorFunction)
.use(mediaQueryPacker)
.use(autoprefixer({ cascade: false, remove: false, grid: true }));
});
|
'use-strict';
const path = require('path');
const postcss = require('postcss');
const cssImport = require('postcss-import');
const atRulesVars = require('postcss-at-rules-variables');
const each = require('postcss-each');
const mixins = require('postcss-mixins');
const nested = require('postcss-nested');
const customProperties = require('postcss-custom-properties');
const conditionals = require('postcss-conditionals');
const customMedia = require('postcss-custom-media');
const calc = require('postcss-calc');
const colorFunction = require('postcss-color-function');
const mediaQueryPacker = require('css-mqpacker');
const autoprefixer = require('autoprefixer');
const mixinsPath = path.join(
path.dirname(require.resolve('@wearegenki/css')),
'src/mixins',
);
module.exports = postcss.plugin('uiPostcssPreset', (opts = {}) => {
const mixinsDir = [opts.mixinsDir] || [];
mixinsDir.push(mixinsPath);
return postcss()
.use(cssImport({ path: opts.importPath || ['src'] }))
.use(atRulesVars)
.use(each)
.use(mixins({ mixinsDir }))
.use(nested)
.use(customProperties)
.use(conditionals)
.use(customMedia)
.use(calc({ warnWhenCannotResolve: opts.verbose }))
.use(colorFunction)
.use(mediaQueryPacker)
.use(autoprefixer({ cascade: false, remove: false, grid: true }));
});
|
Set cookie protection mode to strong
|
import logging
from logging import config
from flask import Flask
import dateutil
import dateutil.parser
import json
from flask_login import LoginManager
from config import CONFIG_DICT
app = Flask(__name__)
app.config.update(CONFIG_DICT)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'
login_manager.session_protection = "strong"
def format_datetime(value):
return dateutil.parser.parse(value).strftime("%d %B %Y at %H:%M:%S")
def setup_logging(logging_config_file_path):
if CONFIG_DICT['LOGGING']:
try:
with open(logging_config_file_path, 'rt') as file:
config = json.load(file)
logging.config.dictConfig(config)
except IOError as e:
raise(Exception('Failed to load logging configuration', e))
app.jinja_env.filters['datetime'] = format_datetime
setup_logging(app.config['LOGGING_CONFIG_FILE_PATH'])
|
import logging
from logging import config
from flask import Flask
import dateutil
import dateutil.parser
import json
from flask_login import LoginManager
from config import CONFIG_DICT
app = Flask(__name__)
app.config.update(CONFIG_DICT)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'
def format_datetime(value):
return dateutil.parser.parse(value).strftime("%d %B %Y at %H:%M:%S")
def setup_logging(logging_config_file_path):
if CONFIG_DICT['LOGGING']:
try:
with open(logging_config_file_path, 'rt') as file:
config = json.load(file)
logging.config.dictConfig(config)
except IOError as e:
raise(Exception('Failed to load logging configuration', e))
app.jinja_env.filters['datetime'] = format_datetime
setup_logging(app.config['LOGGING_CONFIG_FILE_PATH'])
|
Return 404 if no message so we can poll from cucumber tests
|
from kombu import Connection, Exchange, Queue
from flask import Flask
import os
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
@app.route("/getnextqueuemessage")
#Gets the next message from target queue. Returns the signed JSON.
def get_last_queue_message():
#: By default messages sent to exchanges are persistent (delivery_mode=2),
#: and queues and exchanges are durable.
exchange = Exchange()
connection = Connection(app.config['OUTGOING_QUEUE_HOSTNAME'])
# Create/access a queue bound to the connection.
queue = Queue(app.config['OUTGOING_QUEUE'], exchange, routing_key='#')(connection)
queue.declare()
message = queue.get()
if message:
signature = message.body
message.ack() #acknowledges message, ensuring its removal.
return signature
else:
return "no message", 404
@app.route("/removeallmessages")
#Gets the next message from target queue. Returns the signed JSON.
def remove_all_messages():
while True:
queue_message = get_last_queue_message()
if queue_message == 'no message':
break
return "done", 202
@app.route("/")
def check_status():
return "Everything is OK"
|
from kombu import Connection, Exchange, Queue
from flask import Flask
import os
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
@app.route("/getnextqueuemessage")
#Gets the next message from target queue. Returns the signed JSON.
def get_last_queue_message():
#: By default messages sent to exchanges are persistent (delivery_mode=2),
#: and queues and exchanges are durable.
exchange = Exchange()
connection = Connection(app.config['OUTGOING_QUEUE_HOSTNAME'])
# Create/access a queue bound to the connection.
queue = Queue(app.config['OUTGOING_QUEUE'], exchange, routing_key='#')(connection)
queue.declare()
message = queue.get()
if message:
signature = message.body
message.ack() #acknowledges message, ensuring its removal.
return signature
else:
return "no message"
@app.route("/removeallmessages")
#Gets the next message from target queue. Returns the signed JSON.
def remove_all_messages():
while True:
queue_message = get_last_queue_message()
if queue_message == 'no message':
break
return "done", 202
@app.route("/")
def check_status():
return "Everything is OK"
|
Check that the password parameter when unsetting mode k matches the password that is set
|
from twisted.words.protocols import irc
from txircd.modbase import Mode
class PasswordMode(Mode):
def checkUnset(self, user, target, param):
if param == target.mode["k"]:
return True
return False
def commandPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
channels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for index, chan in channels.enumerate():
if "k" in chan.mode and chan.mode["k"] != keys[index]:
removeChannels.append(chan)
user.sendMessage(irc.ERR_BADCHANNELKEY, chan.name, ":Cannot join channel (Incorrect channel key)")
for chan in removeChannels:
index = channels.index(chan) # We need to do this anyway to eliminate the effects of shifting when removing earlier elements
channels.pop(index)
keys.pop(index)
data["targetchan"] = channels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cuk": PasswordMode()
}
}
def cleanup(self):
self.ircd.removeMode("cuk")
|
from twisted.words.protocols import irc
from txircd.modbase import Mode
class PasswordMode(Mode):
def commandPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
channels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for index, chan in channels.enumerate():
if "k" in chan.mode and chan.mode["k"] != keys[index]:
removeChannels.append(chan)
user.sendMessage(irc.ERR_BADCHANNELKEY, chan.name, ":Cannot join channel (Incorrect channel key)")
for chan in removeChannels:
index = channels.index(chan) # We need to do this anyway to eliminate the effects of shifting when removing earlier elements
channels.pop(index)
keys.pop(index)
data["targetchan"] = channels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cuk": PasswordMode()
}
}
def cleanup(self):
self.ircd.removeMode("cuk")
|
Switch from distutils to distribute
|
#!/usr/bin/env python2.7
from setuptools import setup, find_packages
setup(
name='spreads',
version='0.1',
author='Johannes Baiter',
author_email='johannes.baiter@gmail.com',
#packages=['spreads', 'spreadsplug'],
packages=find_packages(),
scripts=['spread', ],
url='http://github.com/jbaiter/spreads',
license='MIT',
description='Tool to facilitate book digitization with the DIY Book '
'Scanner',
long_description=open('README.rst').read(),
install_requires=[
"Pillow >=2.0.0",
"clint >= 0.3.1",
"pyusb >=1.0.0a3",
],
)
|
#!/usr/bin/env python2.7
from distutils.core import setup
setup(
name='spreads',
version='0.1.0',
author='Johannes Baiter',
author_email='johannes.baiter@gmail.com',
packages=['spreads', 'spreadsplug'],
scripts=['spread', ],
url='http://github.com/jbaiter/spreads',
license='LICENSE.txt',
description='Tool to facilitate book digitization with the DIY Book '
'Scanner',
long_description=open('README.rst').read(),
install_requires=[
"Pillow >=2.0.0",
"clint >= 0.3.1",
"pyusb >=1.0.0a3",
],
)
|
Update CLI based on @sindresorhus feedback
* don't use flagged args for file and selector
* exit properly if error opening file
|
#!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')((process.argv.slice(2)))
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust <filename> <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv._[0];
var selector = argv._[1];
fs.readFile(file, function(err, data) {
if(err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
var res = oust(data, selector);
console.log(res.join("\n"));
});
|
#!/usr/bin/env node
var oust = require('../index');
var pkg = require('../package.json');
var fs = require('fs');
var argv = require('minimist')((process.argv.slice(2)))
var printHelp = function() {
console.log('oust');
console.log(pkg.description);
console.log('');
console.log('Usage:');
console.log(' $ oust --file <filename> --selector <selector>');
};
if(argv.h || argv.help) {
printHelp();
return;
}
if(argv.v || argv.version) {
console.log(pkg.version);
return;
}
var file = argv.f || argv.file;
var selector = argv.s || argv.selector;
fs.readFile(file, function(err, data) {
if(err) {
console.log('Error opening file:', err.code);
return;
}
var res = oust(data, selector);
console.log(res.join("\n"));
});
|
Update doc blocks at class level
|
<?php
namespace SilverStripe\FullTextSearch\Search\Extensions;
use SilverStripe\Core\Extension;
use TractorCow\ClassProxy\Generators\ProxyGenerator;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
/**
* This database connector proxy will allow {@link SearchUpdater::handle_manipulation} to monitor database schema
* changes that may need to be propagated through to search indexes.
*
*/
class ProxyDBExtension extends Extension
{
/**
* @param ProxyGenerator $proxy
*
* Ensure the search index is kept up to date by monitoring SilverStripe database manipulations
*/
public function updateProxy(ProxyGenerator &$proxy)
{
$proxy = $proxy->addMethod('manipulate', function ($args, $next) {
$manipulation = $args[0];
SearchUpdater::handle_manipulation($manipulation);
return $next(...$args);
});
}
}
|
<?php
namespace SilverStripe\FullTextSearch\Search\Extensions;
use SilverStripe\Core\Extension;
use TractorCow\ClassProxy\Generators\ProxyGenerator;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
/**
* Class ProxyDBExtension
* @package SilverStripe\FullTextSearch\Search\Extensions
*
* This database connector proxy will allow {@link SearchUpdater::handle_manipulation} to monitor database schema
* changes that may need to be propagated through to search indexes.
*
*/
class ProxyDBExtension extends Extension
{
/**
* @param ProxyGenerator $proxy
*
* Ensure the search index is kept up to date by monitoring SilverStripe database manipulations
*/
public function updateProxy(ProxyGenerator &$proxy)
{
$proxy = $proxy->addMethod('manipulate', function ($args, $next) {
$manipulation = $args[0];
SearchUpdater::handle_manipulation($manipulation);
return $next(...$args);
});
}
}
|
Fix HasColumn matcher for dataframe with duplicated columns
|
# -*- coding: utf-8 -*-
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
# -*- coding: utf-8 -*-
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return df.filter(regex=self._column_pattern).columns.size > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
Update bundles example after configuration provider refactoring
|
"""Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.Configuration('config')
sqlite = providers.Singleton(sqlite3.connect, config.database.dsn)
s3 = providers.Singleton(
boto3.client, 's3',
aws_access_key_id=config.aws.access_key_id,
aws_secret_access_key=config.aws.secret_access_key)
if __name__ == '__main__':
# Initializing containers
core = Core(config={'database': {'dsn': ':memory:'},
'aws': {'access_key_id': 'KEY',
'secret_access_key': 'SECRET'}})
users = Users(database=core.sqlite)
photos = Photos(database=core.sqlite, file_storage=core.s3)
# Fetching few users
user_repository = users.user_repository()
user1 = user_repository.get(id=1)
user2 = user_repository.get(id=2)
# Making some checks
assert user1.id == 1
assert user2.id == 2
assert user_repository.db is core.sqlite()
|
"""Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.Configuration('config')
sqlite = providers.Singleton(sqlite3.connect, config.database.dsn)
s3 = providers.Singleton(
boto3.client, 's3',
aws_access_key_id=config.aws.access_key_id,
aws_secret_access_key=config.aws.secret_access_key)
if __name__ == '__main__':
# Initializing containers
core = Core()
core.config.update({'database': {'dsn': ':memory:'},
'aws': {'access_key_id': 'KEY',
'secret_access_key': 'SECRET'}})
users = Users(database=core.sqlite)
photos = Photos(database=core.sqlite, file_storage=core.s3)
# Fetching few users
user_repository = users.user_repository()
user1 = user_repository.get(id=1)
user2 = user_repository.get(id=2)
# Making some checks
assert user1.id == 1
assert user2.id == 2
assert user_repository.db is core.sqlite()
|
Allow meals with unknown payer
|
from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')
wbw_id = models.IntegerField(unique=True)
class Participation(models.Model):
name = models.CharField(max_length=200)
wbw_list = models.ForeignKey(Wbw_list)
participant = models.ForeignKey(Participant)
def __str__(self):
return self.name
class Bystander(models.Model):
name = models.CharField(max_length=200)
participant = models.ForeignKey(Participant)
class Meal(models.Model):
price = models.IntegerField(default=0)
date = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)
description = models.CharField(max_length=200, blank=True)
wbw_list = models.ForeignKey(Wbw_list, null=True)
participants = models.ManyToManyField(Participant, blank=True)
bystanders = models.ManyToManyField(Bystander, blank=True)
payer = models.ForeignKey(Participant, null=True, blank=True, related_name='paymeal')
|
from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')
wbw_id = models.IntegerField(unique=True)
class Participation(models.Model):
name = models.CharField(max_length=200)
wbw_list = models.ForeignKey(Wbw_list)
participant = models.ForeignKey(Participant)
def __str__(self):
return self.name
class Bystander(models.Model):
name = models.CharField(max_length=200)
participant = models.ForeignKey(Participant)
class Meal(models.Model):
price = models.IntegerField(default=0)
date = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)
description = models.CharField(max_length=200, blank=True)
wbw_list = models.ForeignKey(Wbw_list, null=True)
participants = models.ManyToManyField(Participant, blank=True)
bystanders = models.ManyToManyField(Bystander, blank=True)
payer = models.ForeignKey(Participant, null=True, related_name='paymeal')
|
Add an optional second parameter to cache, used to conditionaly enable/disable caching
|
<?php
if ( ! function_exists('cache') )
{
function cache($key, $condition = true, Closure $closure)
{
$content = $condition ? Cache::get($key) : false;
if ( ! $content ) {
ob_start();
$closure();
$content = ob_get_contents();
ob_end_clean();
if ($condition) {
Cache::forever($key, $content);
Log::debug('writing cache', [$key]);
}
} else {
Log::debug('reading cache', [$key]);
}
return $content;
}
}
|
<?php
if ( ! function_exists('cache') )
{
function cache($key, Closure $closure)
{
$content = Cache::get($key);
if ( ! $content ) {
ob_start();
$closure();
$content = ob_get_contents();
ob_end_clean();
Cache::forever($key, $content);
Log::debug('writing cache', [$key]);
} else {
Log::debug('reading cache', [$key]);
}
return $content;
}
}
|
Update parameterized test with custom display name
|
/*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CustomNamesParameterizedTest {
@DisplayName("Display name of test container")
@ParameterizedTest(name = "[{index}] first argument=\"{0}\", second argument={1}")
@CsvSource({ "mastering, 1", "parameterized, 2", "tests, 3" })
void testWithCustomDisplayNames(String first, int second) {
System.out.println(
"Testing with parameters: " + first + " and " + second);
}
}
|
/*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CustomNamesParameterizedTest {
@DisplayName("Display name of test container")
@ParameterizedTest(name = "[{index}] first argument=\"{0}\", second argument={1}")
@CsvSource({ "hello, 1", "world, 2", "'hello, world', 3" })
void testWithCustomDisplayNames(String first, int second) {
System.out.println(
"Testing with parameters: " + first + " and " + second);
}
}
|
Update GitHub repos from blancltd to developersociety
|
#!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-paginationlinks',
version='0.1.1',
description='Django Pagination Links',
long_description=readme,
url='https://github.com/developersociety/django-paginationlinks',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
#!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-paginationlinks',
version='0.1.1',
description='Django Pagination Links',
long_description=readme,
url='https://github.com/blancltd/django-paginationlinks',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
Add note about broken theme config loading
Something weird going on here. Now that config loading is fixed it gives
errors. Probably need to understand better how loaders work to solve
this.
|
'use strict';
var path = require('path');
require('es6-promise').polyfill();
require('promise.prototype.finally');
var build = require('./build');
exports.develop = function(config) {
config.themeConfig = parseThemeWebpackConfig(config);
return build.devIndex(config).then(build.devServer.bind(null, config));
};
exports.build = function(config) {
config.themeConfig = parseThemeWebpackConfig(config);
return build(config);
};
function parseThemeWebpackConfig(config) {
if(config && config.theme && config.theme.name) {
try {
// make sure site is in module search paths,
// otherwise possible theme cannot be found
module.paths.unshift(path.join(process.cwd(), 'node_modules'));
return {};
// XXXXX: if default theme has custom configuration, yields
// Error: Cannot find module "theme/Body"
// This has something to do with coffee-loader. If that is disabled
// at theme config, then it stumbles at sass config (might be invalid, didn't check)
//return require(path.basename(config.theme.name));
}
catch(e) {
// XXX: figure out when to show error, when not
//console.error(e);
}
}
return {};
}
|
'use strict';
var path = require('path');
require('es6-promise').polyfill();
require('promise.prototype.finally');
var build = require('./build');
exports.develop = function(config) {
config.themeConfig = parseThemeWebpackConfig(config);
return build.devIndex(config).then(build.devServer.bind(null, config));
};
exports.build = function(config) {
config.themeConfig = parseThemeWebpackConfig(config);
return build(config);
};
function parseThemeWebpackConfig(config) {
if(config && config.theme && config.theme.name) {
try {
// make sure site is in module search paths,
// otherwise possible theme cannot be found
module.paths.unshift(path.join(process.cwd(), 'node_modules'));
return require(path.basename(config.theme.name));
}
catch(e) {
// XXX: figure out when to show error, when not
//console.error(e);
}
}
return {};
}
|
Update form elements to more accurately reflect actual Stripe form
These attributes more closely reflect the actual form injected by Stripe. The additional attributes are also useful for selecting elements in tests
|
class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM / YY" size="6" type="text">
<input name="cvc" placeholder="CVC" size="3" type="text">
`;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
|
class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.innerHTML = `
<input id="stripe-cardnumber" placeholder="cardnumber" size="16" type="text">
<input placeholder="exp-date" size="6" type="text">
<input placeholder="cvc" size="3" type="text">
`;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
|
Increase splash screen delay and finish splash screen activity.
|
package de.fu_berlin.cdv.chasingpictures.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import de.fu_berlin.cdv.chasingpictures.MainActivity;
import de.fu_berlin.cdv.chasingpictures.R;
public class SplashScreen extends Activity {
private static final long SPLASH_DELAY_MILLIS = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
}
@Override
protected void onResume() {
super.onResume();
// Start the main activity after a short delay.
new Handler().postDelayed(
new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
},
SPLASH_DELAY_MILLIS
);
}
}
|
package de.fu_berlin.cdv.chasingpictures.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import de.fu_berlin.cdv.chasingpictures.MainActivity;
import de.fu_berlin.cdv.chasingpictures.R;
public class SplashScreen extends Activity {
private static final long SPLASH_DELAY_MILLIS = 300;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
}
@Override
protected void onResume() {
super.onResume();
// Start the main activity after a short delay.
new Handler().postDelayed(
new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
},
SPLASH_DELAY_MILLIS
);
}
}
|
Clean up dask client in indexing test
|
import pytest
import os
import shutil
import xarray as xr
from cosima_cookbook import database
from dask.distributed import Client
from sqlalchemy import select, func
@pytest.fixture(scope='module')
def client():
client = Client()
yield client
client.close()
def test_broken(client, tmp_path):
db = tmp_path / 'test.db'
database.build_index('test/data/indexing/broken_file', client, str(db))
# make sure the database was created
assert(db.exists())
conn, schema = database.create_database(str(db))
# query ncfiles table
q = select([func.count()]).select_from(schema['ncfiles'])
r = conn.execute(q)
assert(r.first()[0] == 0)
q = select([func.count()]).select_from(schema['ncvars'])
r = conn.execute(q)
assert(r.first()[0] == 0)
def test_single_broken(client, tmp_path):
db = tmp_path / 'test.db'
database.build_index('test/data/indexing/single_broken_file', client, str(db))
# make sure the database was created
assert(db.exists())
conn, schema = database.create_database(str(db))
# query ncfiles table
q = select([func.count()]).select_from(schema['ncfiles'])
r = conn.execute(q)
assert(r.first()[0] == 1)
|
import pytest
import os
import shutil
import xarray as xr
from cosima_cookbook import database
from dask.distributed import Client
from sqlalchemy import select, func
@pytest.fixture(scope='module')
def client():
return Client()
def test_broken(client, tmp_path):
db = tmp_path / 'test.db'
database.build_index('test/data/indexing/broken_file', client, str(db))
# make sure the database was created
assert(db.exists())
conn, schema = database.create_database(str(db))
# query ncfiles table
q = select([func.count()]).select_from(schema['ncfiles'])
r = conn.execute(q)
assert(r.first()[0] == 0)
q = select([func.count()]).select_from(schema['ncvars'])
r = conn.execute(q)
assert(r.first()[0] == 0)
def test_single_broken(client, tmp_path):
db = tmp_path / 'test.db'
database.build_index('test/data/indexing/single_broken_file', client, str(db))
# make sure the database was created
assert(db.exists())
conn, schema = database.create_database(str(db))
# query ncfiles table
q = select([func.count()]).select_from(schema['ncfiles'])
r = conn.execute(q)
assert(r.first()[0] == 1)
|
Modify the logic to get slot transfer entities to return all the entities per org.
The logic is now changed from having only one slot transfer entity per org to multiple
slot transfer entities per org.
--HG--
extra : rebase_source : d5526723d69356f4d076143f4dc537c7eeed74c0
|
#!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic for GSoC slot transfers.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from soc.modules.gsoc.models.slot_transfer import GSoCSlotTransfer
def getSlotTransferEntitiesForOrg(org_entity, limit=1000):
"""Returns the slot transfer entity for the organization.
params:
org_entity: the Organization for which the slot transfer entity must be
fetched
returns:
The slot transfer entity for the given organization
"""
q = GSoCSlotTransfer.all().ancestor(org_entity)
return q.fetch(limit=limit)
|
#!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic for GSoC slot transfers.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from soc.modules.gsoc.models.slot_transfer import GSoCSlotTransfer
def getSlotTransferEntityForOrg(org_entity):
"""Returns the slot transfer entity for the organization.
params:
org_entity: the Organization for which the slot transfer entity must be
fetched
returns:
The slot transfer entity for the given organization
"""
q = GSoCSlotTransfer.all().ancestor(org_entity)
return q.get()
|
Check if function type as well
|
import { applyMiddleware } from 'redux';
import { useRoutes } from 'react-router';
import historyMiddleware from './historyMiddleware';
import { ROUTER_STATE_SELECTOR } from './constants';
export default function reduxReactRouter({
routes,
createHistory,
parseQueryString,
stringifyQuery,
routerStateSelector
}) {
return createStore => (reducer, initialState) => {
let baseCreateHistory;
if (typeof createHistory === 'function') {
baseCreateHistory = createHistory;
} else if (createHistory) {
baseCreateHistory = () => createHistory;
}
const history = useRoutes(baseCreateHistory)({
routes,
parseQueryString,
stringifyQuery
});
[ 'pushState', 'push', 'replaceState', 'replace',
'setState', 'go', 'goBack', 'goForward',
'listen', 'createLocation', 'match' ].forEach(funcName => {
if (!history.hasOwnProperty(funcName) &&
typeof(history[funcName]) === 'function') {
throw new Error(`History API does not support function: ${funcName}`);
}
});
const store =
applyMiddleware(
historyMiddleware(history)
)(createStore)(reducer, initialState);
store.history = history;
store[ROUTER_STATE_SELECTOR] = routerStateSelector;
return store;
};
}
|
import { applyMiddleware } from 'redux';
import { useRoutes } from 'react-router';
import historyMiddleware from './historyMiddleware';
import { ROUTER_STATE_SELECTOR } from './constants';
export default function reduxReactRouter({
routes,
createHistory,
parseQueryString,
stringifyQuery,
routerStateSelector
}) {
return createStore => (reducer, initialState) => {
let baseCreateHistory;
if (typeof createHistory === 'function') {
baseCreateHistory = createHistory;
} else if (createHistory) {
baseCreateHistory = () => createHistory;
}
const history = useRoutes(baseCreateHistory)({
routes,
parseQueryString,
stringifyQuery
});
[ 'pushState', 'push', 'replaceState', 'replace',
'setState', 'go', 'goBack', 'goForward',
'listen', 'createLocation', 'match' ].forEach(funcName => {
if (!history.hasOwnProperty(funcName)) {
throw new Error(`History API does not support function: ${funcName}`);
}
});
const store =
applyMiddleware(
historyMiddleware(history)
)(createStore)(reducer, initialState);
store.history = history;
store[ROUTER_STATE_SELECTOR] = routerStateSelector;
return store;
};
}
|
Add customization for conseil departemental nord
|
'use strict';
angular.module('ddsCommon').factory('CustomizationService', function(lyonMetropoleInseeCodes) {
function determineCustomizationId(testCase, currentPeriod) {
if (testCase.menages &&
testCase.menages._) {
if (testCase.menages._.depcom[currentPeriod].match(/^93/))
return 'D93-SSD';
if (testCase.menages._.depcom[currentPeriod].match(/^75/))
return 'D75-PARIS';
if (testCase.menages._.depcom[currentPeriod].match(/^14/))
return 'D14-CALVADOS';
if (testCase.menages._.depcom[currentPeriod].match(/^59/))
return 'D59-NORD';
if (_.includes(lyonMetropoleInseeCodes, testCase.menages._.depcom[currentPeriod]))
return 'M69-LYON';
}
return undefined;
}
return {
determineCustomizationId: determineCustomizationId,
};
});
|
'use strict';
angular.module('ddsCommon').factory('CustomizationService', function(lyonMetropoleInseeCodes) {
function determineCustomizationId(testCase, currentPeriod) {
if (testCase.menages &&
testCase.menages._) {
if (testCase.menages._.depcom[currentPeriod].match(/^93/))
return 'D93-SSD';
if (testCase.menages._.depcom[currentPeriod].match(/^75/))
return 'D75-PARIS';
if (testCase.menages._.depcom[currentPeriod].match(/^14/))
return 'D14-CALVADOS';
if (_.includes(lyonMetropoleInseeCodes, testCase.menages._.depcom[currentPeriod]))
return 'M69-LYON';
}
return undefined;
}
return {
determineCustomizationId: determineCustomizationId,
};
});
|
Fix problem with freezing flow under debug plus many workers
|
"use strict";
let fetch = require('node-fetch');
let Converter = require("csvtojson");
let Promise = require('bluebird');
/**
* Helps fetch Google Docs data
* @param link URI of CSV file
* @return {Promise<Token>} A promise to the token.
*/
module.exports = function remoteCSVtoJSON (link) {
return fetch(link)
.then(response => response.text())
.then(function (csv) {
let converter = new Converter.Converter({
workerNum: global.isDebugging ? 1 : 4
});
return new Promise(function (resolve, reject) {
return converter.fromString(csv, function (error, json) {
if (error) {
reject(error);
}
resolve(json);
});
});
})
.catch(console.log)
};
|
"use strict";
let fetch = require('node-fetch');
let Converter = require("csvtojson");
let Promise = require('bluebird');
/**
* Helps fetch Google Docs data
* @param link URI of CSV file
* @return {Promise<Token>} A promise to the token.
*/
module.exports = function remoteCSVtoJSON (link) {
return fetch(link)
.then(response => response.text())
.then(function (csv) {
let converter = new Converter.Converter({
workerNum: 4
});
return new Promise(function (resolve, reject) {
return converter.fromString(csv, function (error, json) {
if (error) {
reject(error);
}
resolve(json);
});
});
})
.catch(console.log)
};
|
Allow handle to be passed in to avoid embedded global reference.
|
# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import copy
import bark
from .log import Log
class Logger(Log):
'''Helper for emitting logs.
A logger can be used to preset common information (such as a name) and then
emit :py:class:`~bark.log.Log` records with that information already
present.
'''
def __init__(self, name, _handle=bark.handle, **kw):
'''Initialise logger with identifying *name*.
If you need to override the default handle then pass in a custom
*_handle*
'''
kw['name'] = name
super(Logger, self).__init__(**kw)
self._handle = _handle
def log(self, message, **kw):
'''Emit a :py:class:`~bark.log.Log` record.
A copy of this logger's information is made and then merged with the
passed in *kw* arguments before being emitted.
'''
log = copy.deepcopy(self)
log.update(**kw)
log['message'] = message
self._handle(log)
|
# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import copy
import bark
from .log import Log
class Logger(Log):
'''Helper for emitting logs.
A logger can be used to preset common information (such as a name) and then
emit :py:class:`~bark.log.Log` records with that information already
present.
'''
def __init__(self, name, **kw):
'''Initialise logger with identifying *name*.'''
kw['name'] = name
super(Logger, self).__init__(**kw)
def log(self, message, **kw):
'''Emit a :py:class:`~bark.log.Log` record.
A copy of this logger's information is made and then merged with the
passed in *kw* arguments before being emitted.
'''
log = copy.deepcopy(self)
log.update(**kw)
log['message'] = message
# Call global handle method.
bark.handle(log)
|
Add a simple JUL test.
|
package dk.bitcraft.lc;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class JavaUtilLoggingTest {
@Rule
public LogCollector collector = new LogCollector(Logger.getLogger("test.logger"));
@Test
public void test() {
{
Logger log = Logger.getLogger("test.logger");
log.warning("This is an warning!");
log.warning("This is another warning!");
}
assertThat(collector.getLogs()).hasSize(2);
List<String> logs = collector.getLogs();
assertThat(logs.get(0)).contains("This is an warning!");
assertThat(logs.get(1)).contains("This is another warning!");
List<LogRecord> rawLogs = (List<LogRecord>) collector.getRawLogs();
assertTrue(rawLogs.stream().allMatch(e -> e.getLevel() == Level.WARNING));
}
}
|
package dk.bitcraft.lc;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaUtilLoggingTest {
@Rule
public LogCollector collector = new LogCollector(Logger.getLogger("test.logger"));
@Test
public void test() {
{
Logger log = Logger.getLogger("test.logger");
log.warning("This is an warning!");
log.warning("This is another warning!");
}
assertThat(collector.getLogs()).hasSize(2);
List<String> logs = collector.getLogs();
assertThat(logs.get(0)).contains("This is an warning!");
assertThat(logs.get(1)).contains("This is another warning!");
}
}
|
Fix issue with date format causing order creation to fail
|
'use strict';
app.controller('CheckoutCtrl', function($scope, Basket, Order, AuthenticationService) {
$scope.basket = Basket;
$scope.currentUser = AuthenticationService.currentUser();
$scope.createOrder = function() {
console.log('Building the order...');
var orderItems = [];
angular.forEach($scope.basket.get(), function(item) {
orderItems.push({'menu_id': item.menu, 'menu_item': item.id, 'quantity': item.quantity});
});
var now = new Date();
var pickupTime = new Date(now.setHours(now.getHours() + 1));
var order = {
'order': {
'order_time': now,
'pickup_time': pickupTime
},
'order_items': orderItems
};
console.log('Submitting the order...');
console.log(order);
new Order.create(order, function (newOrder) {
console.log('The following order was created successfully');
console.log(newOrder);
});
};
});
|
'use strict';
app.controller('CheckoutCtrl', function($scope, Basket, Order, AuthenticationService) {
$scope.basket = Basket;
$scope.currentUser = AuthenticationService.currentUser();
var hour = 60 * 60 * 1000; // 1 Hour in ms
$scope.pickupTime = new Date() + (2 * hour);
$scope.createOrder = function() {
console.log('Building the order...');
var orderItems = [];
angular.forEach($scope.basket.get(), function(item) {
orderItems.push({'menu_id': item.menu, 'menu_item': item.id, 'quantity': item.quantity});
});
// var order = null;
var order = {
'order': {
// 'user_id': $scope.currentUser.id,
// 'menu_id': 2,
'order_time': new Date(),
'pickup_time': $scope.pickupTime
},
'order_items': orderItems
};
console.log('Submitting the order...');
console.log(order);
new Order.create(order).then(function (newOrder) {
console.log('The following order was created successfully');
console.log(newOrder);
});
};
});
|
Add test configuration vars: STOMP_HOST + STOMP_PORT
|
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
Update up to changes in es5-ext
|
'use strict';
var slice = Array.prototype.slice
, isFunction = require('es5-ext/lib/Function/is-function')
, curry = require('es5-ext/lib/Function/prototype/curry')
, silent = require('es5-ext/lib/Function/prototype/silent')
, nextTick = require('clock/lib/next-tick')
, deferred = require('../deferred');
require('../base').add('invoke', function (name) {
var d = deferred();
this._base.invoke(name, slice.call(arguments, 1), d.resolve);
return d.promise;
}, function (name, args, resolve) {
var fn;
if (this._failed) {
resolve(this._promise);
return;
}
if (isFunction(name)) {
fn = name;
} else if (!isFunction(this._value[name])) {
resolve(new Error("Cannot invoke '" + name +
"' on given result. It's not a function."));
return;
} else {
fn = this._value[name];
}
nextTick(curry.call(resolve, silent.apply(fn.bind(this._value), args)));
});
|
'use strict';
var slice = Array.prototype.slice
, isFunction = require('es5-ext/lib/Function/is-function')
, curry = require('es5-ext/lib/Function/curry').call
, silent = require('es5-ext/lib/Function/silent').apply
, nextTick = require('clock/lib/next-tick')
, deferred = require('../deferred');
require('../base').add('invoke', function (name) {
var d = deferred();
this._base.invoke(name, slice.call(arguments, 1), d.resolve);
return d.promise;
}, function (name, args, resolve) {
var fn;
if (this._failed) {
resolve(this._promise);
return;
}
if (isFunction(name)) {
fn = name;
} else if (!isFunction(this._value[name])) {
resolve(new Error("Cannot invoke '" + name +
"' on given result. It's not a function."));
return;
} else {
fn = this._value[name];
}
nextTick(curry(resolve, silent(fn.bind(this._value), args)));
});
|
Make sure that 0 doesnt count as empty
|
<?php
namespace Smartive\HandlebarsBundle\Helper;
use Handlebars\Context;
use Handlebars\Helper;
/**
* Base class for Handlebars helpers
*/
abstract class AbstractHelper implements Helper
{
/**
* Evaluates a value in the template and if not found, returns the value itself
*
* @param Context $context Context
* @param string $name Name of the variable or a static value
*
* @return string
*/
protected function getValue(Context $context, $name)
{
$name = trim($name);
if (preg_match('/^(\'|").+(\'|")$/', $name)) {
return $this->cleanStringValue($name);
}
$contextValue = $context->get($name);
return is_null($contextValue) || $contextValue === '' ? $name : $contextValue;
}
/**
* Removes unwanted characters for parsing
*
* @param string $value Value to clean
*
* @return string
*/
protected function cleanStringValue($value)
{
return trim((string) $value, '\'"');
}
}
|
<?php
namespace Smartive\HandlebarsBundle\Helper;
use Handlebars\Context;
use Handlebars\Helper;
/**
* Base class for Handlebars helpers
*/
abstract class AbstractHelper implements Helper
{
/**
* Evaluates a value in the template and if not found, returns the value itself
*
* @param Context $context Context
* @param string $name Name of the variable or a static value
*
* @return string
*/
protected function getValue(Context $context, $name)
{
$name = trim($name);
if (preg_match('/^(\'|").+(\'|")$/', $name)) {
return $this->cleanStringValue($name);
}
return empty($context->get($name)) ? $name : $context->get($name);
}
/**
* Removes unwanted characters for parsing
*
* @param string $value Value to clean
*
* @return string
*/
protected function cleanStringValue($value)
{
return trim((string) $value, '\'"');
}
}
|
Fix react path for commonjs build
|
'use strict';
var path = require('path');
var parse = require('./parse');
var reactRuntimePath;
try {
reactRuntimePath = require.resolve('react');
} catch (ex) {
reactRuntimePath = false;
}
module.exports = compileClient;
function compileClient(str, options){
options = options || { filename: '' };
var react = options.outputFile ? path.relative(path.dirname(options.outputFile), reactRuntimePath) : reactRuntimePath;
if (options.globalReact || !reactRuntimePath) {
return '(function (React) {\n ' +
parse(str, options).split('\n').join('\n ') +
'\n}(React))';
} else {
return '(function (React) {\n ' +
parse(str, options).split('\n').join('\n ') +
'\n}(typeof React !== "undefined" ? React : require("react")))';
}
}
|
'use strict';
var path = require('path');
var parse = require('./parse');
var reactRuntimePath;
try {
reactRuntimePath = require.resolve('react');
} catch (ex) {
reactRuntimePath = false;
}
module.exports = compileClient;
function compileClient(str, options){
options = options || { filename: '' };
var react = options.outputFile ? path.relative(path.dirname(options.outputFile), reactRuntimePath) : reactRuntimePath;
if (options.globalReact || !reactRuntimePath) {
return '(function (React) {\n ' +
parse(str, options).split('\n').join('\n ') +
'\n}(React))';
} else {
return '(function (React) {\n ' +
parse(str, options).split('\n').join('\n ') +
'\n}(typeof React !== "undefined" ? React : require("' + react.replace(/^([^\.])/, './$1').replace(/\\/g, '/') + '")))';
}
}
|
Fix xml tags for ingredients
|
// SPDX-License-Identifier: MIT
package mealplaner.io.xml.model.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RecipeXml {
public final int numberOfPortions;
@XmlElementWrapper(name = "ingredients")
@XmlElement(name = "ingredient")
public final List<QuantitativeIngredientXml> quantitativeIngredients;
public RecipeXml() {
this(1, new ArrayList<>());
}
public RecipeXml(Integer numberOfPortions, List<QuantitativeIngredientXml> quantitativeIngredients) {
this.numberOfPortions = numberOfPortions;
this.quantitativeIngredients = quantitativeIngredients;
}
}
|
// SPDX-License-Identifier: MIT
package mealplaner.io.xml.model.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RecipeXml {
public final int numberOfPortions;
@XmlElementWrapper(name = "meals")
@XmlElement(name = "meal")
public final List<QuantitativeIngredientXml> quantitativeIngredients;
public RecipeXml() {
this(1, new ArrayList<>());
}
public RecipeXml(Integer numberOfPortions, List<QuantitativeIngredientXml> quantitativeIngredients) {
this.numberOfPortions = numberOfPortions;
this.quantitativeIngredients = quantitativeIngredients;
}
}
|
Fix compilation error in mutability
|
package org.genericsystem.mutability;
import java.io.Serializable;
import java.util.List;
import org.genericsystem.defaults.DefaultVertex;
public interface Generic extends DefaultVertex<Generic> {
@Override
default Engine getRoot() {
throw new IllegalStateException();
}
@Override
default Cache getCurrentCache() {
return getRoot().getCurrentCache();
}
@Override
default long getTs() {
return getCurrentCache().unwrap(this).getBirthTs();
}
@Override
default Generic getMeta() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getMeta());
}
@Override
default List<Generic> getSupers() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getSupers());
}
@Override
default List<Generic> getComponents() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getComponents());
}
@Override
default Serializable getValue() {
return getCurrentCache().unwrap(this).getValue();
}
@Override
default long getBirthTs() {
return getCurrentCache().unwrap(this).getBirthTs();
}
}
|
package org.genericsystem.mutability;
import java.io.Serializable;
import java.util.List;
import org.genericsystem.defaults.DefaultVertex;
public interface Generic extends DefaultVertex<Generic> {
@Override
default Engine getRoot() {
throw new IllegalStateException();
}
@Override
default Cache getCurrentCache() {
return getRoot().getCurrentCache();
}
@Override
default long getTs() {
return getCurrentCache().unwrap(this).getBirthTs();
}
@Override
default Generic getMeta() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getMeta());
}
@Override
default List<Generic> getSupers() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getSupers());
}
@Override
default List<Generic> getComponents() {
return getCurrentCache().wrap(getCurrentCache().unwrap(this).getComponents());
}
@Override
default Serializable getValue() {
return getCurrentCache().unwrap(this).getValue();
}
@Override
default long getBirthTs() {
return getCurrentCache().unwrap(this).getBirthTs();
}
@Override
default long[] getOtherTs() {
return getCurrentCache().unwrap(this).getOtherTs();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.