text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add Image to ENTITY_TYPE Enum
Useful for rich text editor inline image support
|
export const BLOCK_TYPE = {
// This is used to represent a normal text block (paragraph).
UNSTYLED: 'unstyled',
HEADER_ONE: 'header-one',
HEADER_TWO: 'header-two',
HEADER_THREE: 'header-three',
HEADER_FOUR: 'header-four',
HEADER_FIVE: 'header-five',
HEADER_SIX: 'header-six',
UNORDERED_LIST_ITEM: 'unordered-list-item',
ORDERED_LIST_ITEM: 'ordered-list-item',
BLOCKQUOTE: 'blockquote',
PULLQUOTE: 'pullquote',
CODE: 'code-block',
ATOMIC: 'atomic',
};
export const ENTITY_TYPE = {
LINK: 'LINK',
IMAGE: 'IMAGE'
};
export const INLINE_STYLE = {
BOLD: 'BOLD',
CODE: 'CODE',
ITALIC: 'ITALIC',
STRIKETHROUGH: 'STRIKETHROUGH',
UNDERLINE: 'UNDERLINE',
};
export default {
BLOCK_TYPE,
ENTITY_TYPE,
INLINE_STYLE,
};
|
export const BLOCK_TYPE = {
// This is used to represent a normal text block (paragraph).
UNSTYLED: 'unstyled',
HEADER_ONE: 'header-one',
HEADER_TWO: 'header-two',
HEADER_THREE: 'header-three',
HEADER_FOUR: 'header-four',
HEADER_FIVE: 'header-five',
HEADER_SIX: 'header-six',
UNORDERED_LIST_ITEM: 'unordered-list-item',
ORDERED_LIST_ITEM: 'ordered-list-item',
BLOCKQUOTE: 'blockquote',
PULLQUOTE: 'pullquote',
CODE: 'code-block',
ATOMIC: 'atomic',
};
export const ENTITY_TYPE = {
LINK: 'LINK',
};
export const INLINE_STYLE = {
BOLD: 'BOLD',
CODE: 'CODE',
ITALIC: 'ITALIC',
STRIKETHROUGH: 'STRIKETHROUGH',
UNDERLINE: 'UNDERLINE',
};
export default {
BLOCK_TYPE,
ENTITY_TYPE,
INLINE_STYLE,
};
|
Change contact field and author field for PyPI.
|
"""
``onecodex``
------------
``onecodex`` provides a command line client for interaction with the
One Codex API.
Links
`````
* `One Codex: <https://www.onecodex.com/>`
* `API Docs: <http://docs.onecodex.com/>`
"""
from setuptools import setup
setup(
name='onecodex',
version='0.0.1',
url='https://www.onecodex.com/',
license='MIT',
author='Reference Genomics, Inc.',
author_email='help@onecodex.com',
description='One Codex Command Line Client',
long_description=__doc__,
packages=['onecodex'],
zip_safe=True,
platforms='any',
install_requires=[
'requests>=2.4.3',
],
test_suite='nose.collector',
entry_points={
'console_scripts': ['onecodex = onecodex.cli:main']
},
)
|
"""
``onecodex``
------------
``onecodex`` provides a command line client for interaction with the
One Codex API.
Links
`````
* `One Codex: <https://www.onecodex.com/>`
* `API Docs: <http://docs.onecodex.com/>`
"""
from setuptools import setup
setup(
name='onecodex',
version='0.0.1',
url='https://www.onecodex.com/',
license='MIT',
author='Nick Boyd Greenfield',
author_email='nick@onecodex.com',
description='One Codex Command Line Client',
long_description=__doc__,
packages=['onecodex'],
zip_safe=True,
platforms='any',
install_requires=[
'requests>=2.4.3',
],
test_suite='nose.collector',
entry_points={
'console_scripts': ['onecodex = onecodex.cli:main']
},
)
|
Enforce name conventions for test-created activities
|
/**
*
*/
package test.issues.strava;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.Arrays;
import java.util.List;
import javastrava.api.v3.model.StravaComment;
import javastrava.api.v3.rest.API;
import javastrava.api.v3.rest.ActivityAPI;
import org.junit.Test;
import test.api.service.impl.util.ActivityServiceUtils;
import test.utils.RateLimitedTestRunner;
import test.utils.TestUtils;
/**
* <p>
* Issue test for issue javastrava-api #67 - tests will PASS if the issue is still a problem
* </p>
*
* @author Dan Shannon
* @see <a href="https://github.com/danshannon/javastravav3api/issues/67>https://github.com/danshannon/javastravav3api/issues/67</a>
*/
public class Issue67 {
@Test
public void testIssue() throws Exception {
RateLimitedTestRunner.run(() -> {
final ActivityAPI api = API.instance(ActivityAPI.class, TestUtils.getValidToken());
final StravaComment comment = ActivityServiceUtils.createPrivateActivityWithComment("Issue67.testIssue()");
final List<StravaComment> comments = Arrays.asList(api.listActivityComments(comment.getActivityId(), null, null, null));
assertNotNull(comments);
assertFalse(comments.isEmpty());
});
}
}
|
/**
*
*/
package test.issues.strava;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.Arrays;
import java.util.List;
import javastrava.api.v3.model.StravaComment;
import javastrava.api.v3.rest.API;
import javastrava.api.v3.rest.ActivityAPI;
import org.junit.Test;
import test.api.service.impl.util.ActivityServiceUtils;
import test.utils.RateLimitedTestRunner;
import test.utils.TestUtils;
/**
* <p>
* Issue test for issue javastrava-api #67 - tests will PASS if the issue is still a problem
* </p>
*
* @author Dan Shannon
* @see <a href="https://github.com/danshannon/javastravav3api/issues/67>https://github.com/danshannon/javastravav3api/issues/67</a>
*/
public class Issue67 {
@Test
public void testIssue() throws Exception {
RateLimitedTestRunner.run(() -> {
final ActivityAPI api = API.instance(ActivityAPI.class, TestUtils.getValidToken());
final StravaComment comment = ActivityServiceUtils.createPrivateActivityWithComment();
final List<StravaComment> comments = Arrays.asList(api.listActivityComments(comment.getActivityId(), null, null, null));
assertNotNull(comments);
assertFalse(comments.isEmpty());
});
}
}
|
Replace let with var for compatibility issue
|
'use strict';
// Bubble sort has worst-case and average complexity both О(n^2),
// where n is the number of items being sorted.
// The significant advantage that bubble sort has over most other implementations,
// even quicksort, but not insertion sort, is that the ability to detect that the
// list is sorted is efficiently built into the algorithm. When the list is
// already sorted (best-case), the complexity of bubble sort is only O(n).
function comparator(a, b) {
return a - b;
}
/**
* Bubble Sort with O(n^2) complexity
* @param {Array} input array
* @param {Function} fn (comparator)
* @returns {Array} bubble sorted array
*/
module.exports = function (arr, fn) {
fn = fn || comparator;
var tmp;
for (var i = 0; i < arr.length; i++) {
for (var j = i; j > 0; j--) {
if (fn(arr[j], arr[j - 1]) < 0) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
}
}
return arr;
};
|
'use strict';
// Bubble sort has worst-case and average complexity both О(n^2),
// where n is the number of items being sorted.
// The significant advantage that bubble sort has over most other implementations,
// even quicksort, but not insertion sort, is that the ability to detect that the
// list is sorted is efficiently built into the algorithm. When the list is
// already sorted (best-case), the complexity of bubble sort is only O(n).
function comparator(a, b) {
return a - b;
}
/**
* Bubble Sort with O(n^2) complexity
* @param {Array} input array
* @param {Function} fn (comparator)
* @returns {Array} bubble sorted array
*/
module.exports = function (arr, fn) {
fn = fn || comparator;
let tmp;
for (let i = 0; i < arr.length; i++) {
for (let j = i; j > 0; j--) {
if (fn(arr[j], arr[j - 1]) < 0) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
}
}
return arr;
};
|
Fix property name for ember-simple-auth
|
import Ember from 'ember';
import DS from 'ember-data';
import ENV from '../config/environment';
function getToken() {
var token;
var session = window.localStorage['ember_simple_auth-session'];
if (session) {
token = JSON.parse(session)['authenticated'];
if ('attributes' in token) {
return token['attributes']['accessToken'];
}
return token;
}
}
export default DS.JSONAPIAdapter.extend({
session: Ember.inject.service(),
host: ENV.osfAPIUrl,
namespace: 'v2',
ajax(url, method, hash) {
hash = hash || {};
hash.crossOrigin = true;
hash.xhrFields = { withCredentials: false };
hash.headers = hash.headers || {};
hash.headers['AUTHORIZATION'] = 'Bearer ' + getToken();
return this._super(url, method, hash);
},
buildURL() {
var base = this._super(...arguments);
return `${base}/`;
}
});
|
import Ember from 'ember';
import DS from 'ember-data';
import ENV from '../config/environment';
function getToken() {
var token;
var session = window.localStorage['ember_simple_auth:session'];
if (session) {
token = JSON.parse(session)['authenticated'];
if ('attributes' in token) {
return token['attributes']['accessToken'];
}
return token;
}
}
export default DS.JSONAPIAdapter.extend({
session: Ember.inject.service(),
host: ENV.osfAPIUrl,
namespace: 'v2',
ajax(url, method, hash) {
hash = hash || {};
hash.crossOrigin = true;
hash.xhrFields = { withCredentials: false };
hash.headers = hash.headers || {};
hash.headers['AUTHORIZATION'] = 'Bearer ' + getToken();
return this._super(url, method, hash);
},
buildURL() {
var base = this._super(...arguments);
return `${base}/`;
}
});
|
Remove TYPE_FREE and TYPE_PRO as we no longer need them
|
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (https://www.boxbilling.org)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
final class Box_Version
{
const VERSION = '0.0.1';
/**
* Compare the specified BoxBilling version string $version
* with the current Box_Version::VERSION of BoxBilling.
*
* @param string $version A version string (e.g. "0.7.1").
* @return integer -1 if the $version is older,
* 0 if they are the same,
* and +1 if $version is newer.
*
*/
public static function compareVersion($version)
{
return version_compare(strtolower($version), strtolower(self::VERSION));
}
}
|
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (https://www.boxbilling.org)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
final class Box_Version
{
const VERSION = '0.0.1';
const TYPE_FREE = 'free';
const TYPE_PRO = 'pro';
/**
* Compare the specified BoxBilling version string $version
* with the current Box_Version::VERSION of BoxBilling.
*
* @param string $version A version string (e.g. "0.7.1").
* @return integer -1 if the $version is older,
* 0 if they are the same,
* and +1 if $version is newer.
*
*/
public static function compareVersion($version)
{
return version_compare(strtolower($version), strtolower(self::VERSION));
}
}
|
Resolve class based transform deprecation
ember-source 3.27+: Using class based template compilation plugins is deprecated, please update to the functional style
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelectorParam(param) {
return param.type === 'PathExpression'
&& TEST_SELECTOR_PREFIX.test(param.original);
}
module.exports = function(env) {
let b = env.syntax.builders;
let transform = (node) => {
if ('sexpr' in node) {
node = node.sexpr;
}
let testSelectorParams = [];
let otherParams = [];
node.params.forEach(function(param) {
if (isTestSelectorParam(param)) {
testSelectorParams.push(param);
} else {
otherParams.push(param);
}
});
node.params = otherParams;
testSelectorParams.forEach(function(param) {
let pair = b.pair(param.original, b.boolean(true));
node.hash.pairs.push(pair);
});
};
return {
name: 'TransformTestSelectorParamsToHashPairs',
visitor: {
MustacheStatement: transform,
BlockStatement: transform,
},
};
};
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function TransformTestSelectorParamsToHashPairs() {
this.syntax = null;
}
function isTestSelectorParam(param) {
return param.type === 'PathExpression'
&& TEST_SELECTOR_PREFIX.test(param.original);
}
TransformTestSelectorParamsToHashPairs.prototype.transform = function(ast) {
let b = this.syntax.builders;
let walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (node.type === 'MustacheStatement' || node.type === 'BlockStatement') {
if ('sexpr' in node) {
node = node.sexpr;
}
let testSelectorParams = [];
let otherParams = [];
node.params.forEach(function(param) {
if (isTestSelectorParam(param)) {
testSelectorParams.push(param);
} else {
otherParams.push(param);
}
});
node.params = otherParams;
testSelectorParams.forEach(function(param) {
let pair = b.pair(param.original, b.boolean(true));
node.hash.pairs.push(pair);
});
}
});
return ast;
};
module.exports = TransformTestSelectorParamsToHashPairs;
|
Make the files server only
|
Package.describe({
name: 'capsulecat:model-factories',
version: '1.0.0',
summary: 'Easily generate data for your models using factories',
git: 'https://github.com/CapsuleCat/MeteorModelFactories',
documentation: 'README.md'
});
function includeFiles(api) {
api.use('ecmascript');
api.use('underscore');
api.imply('aldeed:collection2');
api.addFiles('src/faker.min.js', ['server']);
api.addFiles('src/factory.js', ['server']);
}
Package.onUse(function(api) {
api.versionsFrom('1.2.1');
includeFiles(api);
api.export(['$factory']);
});
Package.onTest(function(api) {
api.use('sanjo:jasmine@0.20.3');
api.use('velocity:console-reporter');
includeFiles(api);
api.addFiles('tests/factory-spec.js', ['server']);
});
|
Package.describe({
name: 'capsulecat:model-factories',
version: '1.0.0',
summary: 'Easily generate data for your models using factories',
git: 'https://github.com/CapsuleCat/MeteorModelFactories',
documentation: 'README.md'
});
function includeFiles(api) {
api.use('ecmascript');
api.use('underscore');
api.imply('aldeed:collection2');
api.addFiles('src/faker.min.js');
api.addFiles('src/factory.js');
}
Package.onUse(function(api) {
api.versionsFrom('1.2.1');
includeFiles(api);
api.export(['$factory']);
});
Package.onTest(function(api) {
api.use('sanjo:jasmine@0.20.3');
api.use('velocity:console-reporter');
includeFiles(api);
api.addFiles('tests/factory-spec.js', ['server', 'client']);
});
|
Set correct email config for salesforce sync.
BB-1530
|
try:
from .secrets import *
except ImportError:
import sys
sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.')
from .base import *
#
# We need this specific override because having the salesforce app and bluebottle_salesforce
# enabled causes tests to fail in our other apps with this error:
#
# AttributeError: _original_allowed_hosts
#
# There seems to be some strange database interactions / side-effects when running with SaleforceModels that have
# Meta: managed = False set with the salesforce info configured in DATABASES.
# TODO: Investigate this issue to see if we can put the Saleforce apps back into base.py.
#
#
# Put the salesforce sync environment specific overrides below.
#
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS += (
'salesforce',
'apps.bluebottle_salesforce',
)
# Send email for real
EMAIL_BACKEND = 'bluebottle.bluebottle_utils.email_backend.DKIMBackend'
|
try:
from .secrets import *
except ImportError:
import sys
sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.')
from .base import *
#
# We need this specific override because having the salesforce app and bluebottle_salesforce
# enabled causes tests to fail in our other apps with this error:
#
# AttributeError: _original_allowed_hosts
#
# There seems to be some strange database interactions / side-effects when running with SaleforceModels that have
# Meta: managed = False set with the salesforce info configured in DATABASES.
# TODO: Investigate this issue to see if we can put the Saleforce apps back into base.py.
#
#
# Put the salesforce sync environment specific overrides below.
#
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS += (
'salesforce',
'apps.bluebottle_salesforce',
)
# Send email for real
EMAIL_BACKEND = 'apps.bluebottle_utils.email_backend.DKIMBackend'
|
fix/webFetch-encoding: Add content-encoding headers for webfetch response. Set 'chunked'
|
import logger from 'logger';
import { getAppObj } from '../network';
const safeRoute = {
method : 'GET',
path : '/safe/{link*}',
handler : async ( request, reply ) =>
{
try
{
const link = `safe://${request.params.link}`;
const app = getAppObj();
logger.verbose( `Handling SAFE req: ${link}` );
if ( !app )
{
return reply( 'SAFE not connected yet' );
}
const data = await app.webFetch( link );
return reply( data.body )
.type( data.headers['Content-Type'] )
.header( 'Content-Encoding', 'chunked');
}
catch ( e )
{
logger.error( e );
return reply( e.message || e );
}
}
}
export default safeRoute;
|
import logger from 'logger';
import { getAppObj } from '../network';
const safeRoute = {
method : 'GET',
path : '/safe/{link*}',
handler : async ( request, reply ) =>
{
try
{
const link = `safe://${request.params.link}`;
const app = getAppObj();
logger.verbose( `Handling SAFE req: ${link}` );
if ( !app )
{
return reply( 'SAFE not connected yet' );
}
const data = await app.webFetch( link );
return reply( data.body ).type( data.headers['Content-Type'] );
}
catch ( e )
{
logger.error( e );
return reply( e.message || e );
}
}
}
export default safeRoute;
|
Fix the deleter that was never tested.
|
'use strict';
const Promise = require('bluebird');
const rmdir = Promise.promisify(require('rimraf'));
const db = require('../shared/db');
module.exports = function() {
getOldFolders().then(deleteFolders).done();
};
function getOldFolders() {
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'get_old_folders',
text: "select path from source_folder where created < ( now() - interval '24 hours' )",
values: []
}).get(0).get('rows');
});
}
function deleteFolders(folders) {
return deleteFolderEntries(folders).then(deleteFilesystemFolders);
}
function deleteFolderEntries(folders) {
return Promise.map(folders, deleteFolderEntry);
}
function deleteFolderEntry(folder) {
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'delete_folder',
text: 'delete from source_folder where path = $1',
values: [folder.path]
});
}).then(function() {
return folder.path;
});
}
function deleteFilesystemFolders(folders) {
return folders.map(function(f) {
rmdir(f, {});
});
}
|
'use strict';
const Promise = require('bluebird');
const rmdir = Promise.promisify(require('rimraf'));
const db = require('../shared/db');
module.exports = function() {
getOldFolders().then(deleteFolders).done();
};
function getOldFolders() {
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'get_old_folders',
text: "select path from source_folder where created < ( now() - interval '24 hours' )",
values: []
}).get('rows');
});
}
function deleteFolders(folders) {
return deleteFolderEntries(folders).then(deleteFilesystemFolders);
}
function deleteFolderEntries(folders) {
return folders.map(deleteFolderEntry);
}
function deleteFolderEntry(folder) {
return Promise.using(db(), function(client) {
return client.queryAsync({
name: 'delete_folder',
text: 'delete from source_folder where path = $1',
values: [folder]
});
});
}
function deleteFilesystemFolders(folders) {
return folders.map(rmdir);
}
|
Add getters for visitor/visit properties.
|
package com.woopra.java.sdk;
import java.util.HashMap;
public class WoopraVisitor {
public static String EMAIL = "email";
public static String UNIQUE_ID = "uniqueId";
protected HashMap<String, Object> properties = new HashMap<String, Object>();
private String ipAddress = "";
private String cookieValue = "";
private String userAgent = "";
public WoopraVisitor(String identifier, String value) {
if (identifier.equals(WoopraVisitor.EMAIL)) {
properties.put(WoopraVisitor.EMAIL, value);
this.cookieValue = String.valueOf(Math.abs(value.hashCode()));
} else if (identifier.equals(WoopraVisitor.UNIQUE_ID)) {
this.cookieValue = value;
}
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public void setProperty(String key, Object value) {
this.properties.put(key, value);
}
public String toString() {
return this.properties.toString();
}
public String getCookieValue() {
return this.cookieValue;
}
public String getIpAddress() {
return this.ipAddress;
}
public String getUserAgent() {
return this.userAgent;
}
}
|
package com.woopra.java.sdk;
import java.util.HashMap;
public class WoopraVisitor {
public static String EMAIL = "email";
public static String UNIQUE_ID = "uniqueId";
protected HashMap<String, Object> properties = new HashMap<String, Object>();
private String ipAddress = "";
private String cookieValue = "";
private String userAgent = "";
public WoopraVisitor(String identifier, String value) {
if (identifier.equals(WoopraVisitor.EMAIL)) {
properties.put(WoopraVisitor.EMAIL, value);
this.cookieValue = String.valueOf(Math.abs(value.hashCode()));
} else if (identifier.equals(WoopraVisitor.UNIQUE_ID)) {
this.cookieValue = value;
}
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public void setProperty(String key, Object value) {
this.properties.put(key, value);
}
public String toString() {
return this.properties.toString();
}
}
|
Enforce image on backend users images to be actual images
|
<?php
namespace Nodes\Backend\Models\User\Validation;
use Nodes\Validation\AbstractValidator;
/**
* Class UserValidation.
*/
class UserValidator extends AbstractValidator
{
/**
* Validation rules.
*
* @var array
*/
protected $rules = [
'create' => [
'name' => ['required'],
'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
'password' => ['required_without:id', 'min:6', 'confirmed'],
'user_role' => ['required', 'exists:backend_roles,slug'],
'image' => ['mimes:jpeg,png']
],
'update-password' => [
'password' => ['required_without:id', 'min:6', 'confirmed'],
'image' => ['mimes:jpeg,png']
],
];
}
|
<?php
namespace Nodes\Backend\Models\User\Validation;
use Nodes\Validation\AbstractValidator;
/**
* Class UserValidation.
*/
class UserValidator extends AbstractValidator
{
/**
* Validation rules.
*
* @var array
*/
protected $rules = [
'create' => [
'name' => ['required'],
'email' => ['required', 'email', 'unique:backend_users,email,{:id}', 'max:190'],
'password' => ['required_without:id', 'min:6', 'confirmed'],
'user_role' => ['required', 'exists:backend_roles,slug'],
],
'update-password' => [
'password' => ['required_without:id', 'min:6', 'confirmed'],
],
];
}
|
Use new options for dummy/docs app
|
/*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
babel: {
includePolyfill: false
},
SemanticUI: {
paths: {
fonts: 'assets/themes/default/assets/fonts',
}
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
// Import Highlight.js
app.import(app.bowerDirectory + "/highlightjs/highlight.pack.min.js");
app.import(app.bowerDirectory + "/highlightjs/styles/github-gist.css");
app.import(app.bowerDirectory + "/highlightjs/styles/hybrid.css");
return app.toTree();
};
|
/*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
babel: {
includePolyfill: false
}
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
app.import('bower_components/semantic-ui/dist/semantic.css');
app.import('bower_components/semantic-ui/dist/semantic.js');
// Import Highlight.js
app.import(app.bowerDirectory + "/highlightjs/highlight.pack.min.js");
app.import(app.bowerDirectory + "/highlightjs/styles/github-gist.css");
app.import(app.bowerDirectory + "/highlightjs/styles/hybrid.css");
return app.toTree();
};
|
Swap hitzer inverse test to use np.testing
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
|
Replace NullOutputStream with inline implementation
Using `NullOutputStream` in `FluxProgrammTest` introduced a depdency on
Apache Commons IO which can easily be avoided.
|
/*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* 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.culturegraph.mf.flux;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.culturegraph.mf.flux.parser.FluxProgramm;
import org.junit.Test;
/**
* Tests {@link FluxProgramm}
*
* @author markus geipel
*
*/
public final class FluxProgrammTest {
@Test
public void testCommandRegistration() {
// all commands must properly load to print the help
FluxProgramm.printHelp(discardOutput());
}
private PrintStream discardOutput() {
return new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// Do not write any output.
}
});
}
}
|
/*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* 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.culturegraph.mf.flux;
import java.io.PrintStream;
import org.apache.commons.io.output.NullOutputStream;
import org.culturegraph.mf.flux.parser.FluxProgramm;
import org.junit.Test;
/**
* Tests {@link FluxProgramm}
*
* @author markus geipel
*
*/
public final class FluxProgrammTest {
@Test
public void testCommandRegistration() {
// all commands must properly load to print the help
FluxProgramm.printHelp(new PrintStream(new NullOutputStream()));
}
}
|
Send authorization tokens in `fetch`
|
import { inject as service } from '@ember/service';
import fetch from 'fetch';
import Route from '@ember/routing/route';
import ResetScrollPositionMixin from 'frontend/mixins/reset-scroll-position';
export default Route.extend(ResetScrollPositionMixin, {
intl: service(),
session: service(),
queryParams: {
specificToUser: {
refreshModel: true
}
},
model(params) {
const host = this.store.adapterFor('summarized-statistic').get('host');
let url = new URL(`${host}/chart_data/similarities.json`);
let headers = {};
if (this.get('session.isAuthenticated') && params.specificToUser){
url.searchParams.append('specific_to_user', params.specificToUser);
headers['Authorization'] = `Bearer ${this.get('session.data.authenticated.idToken')}`;
}
return fetch(url, {headers: headers}).then(function(response) {
return response.json();
});
},
actions: {
toggleSpecificToUser(currentValue){
const switchedValue = currentValue != "true";
this.transitionTo({ queryParams: { specific_to_user: switchedValue }});
}
}
}
);
|
import { inject as service } from '@ember/service';
import fetch from 'fetch';
import Route from '@ember/routing/route';
import ResetScrollPositionMixin from 'frontend/mixins/reset-scroll-position';
export default Route.extend(ResetScrollPositionMixin, {
intl: service(),
session: service(),
queryParams: {
specificToUser: {
refreshModel: true
}
},
model(params) {
const host = this.store.adapterFor('summarized-statistic').get('host');
let url = new URL(`${host}/chart_data/similarities.json`);
if (params.specificToUser){
url.searchParams.append('specific_to_user', params.specificToUser);
}
return fetch(url).then(function(response) {
return response.json();
});
},
actions: {
toggleSpecificToUser(currentValue){
const switchedValue = currentValue != "true";
this.transitionTo({ queryParams: { specific_to_user: switchedValue }});
}
}
}
);
|
Clean JSON object creation code
|
var express = require('express');
var router = express.Router();
var funfacts = [
'Ants stretch when they wake up in the morning.',
'The state of Florida is bigger than England.',
'Some bamboo plants can grow almost a meter in just one day.',
'Olympic gold medals are actually made mostly of silver.',
'On average, it takes 66 days to form a new habit.',
'You are born with 300 bones; by the time you are an adult you will have 206.',
'Ostriches can run faster than horses.',
'Mammoths still walked the earth when the Great Pyramid was being built.',
'It takes about 8 minutes for light from the Sun to reach Earth.',
'Some penguins can leap 2-3 meters out of the water.'
];
// 1.0.X Routes
router.get('/v1.0/fact/random', function(req, res, next) {
var factIndex = Math.floor(Math.random() * funfacts.length);
var fact = {
text: funfacts[factIndex]
};
res.json(fact);
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
var funfacts = [
'Ants stretch when they wake up in the morning.',
'The state of Florida is bigger than England.',
'Some bamboo plants can grow almost a meter in just one day.',
'Olympic gold medals are actually made mostly of silver.',
'On average, it takes 66 days to form a new habit.',
'You are born with 300 bones; by the time you are an adult you will have 206.',
'Ostriches can run faster than horses.',
'Mammoths still walked the earth when the Great Pyramid was being built.',
'It takes about 8 minutes for light from the Sun to reach Earth.',
'Some penguins can leap 2-3 meters out of the water.'
];
// 1.0.X Routes
router.get('/v1.0/fact/random', function(req, res, next) {
var factIndex = Math.floor(Math.random() * funfacts.length);
var factText = funfacts[factIndex];
var fact = {
text: factText
};
res.json(fact);
});
module.exports = router;
|
Fix teardown of resize handler in content management screen
refs #5659 ([comment](https://github.com/TryGhost/Ghost/issues/5659#issuecomment-137114898))
- cleans up resize handler on willDestroy hook of gh-content-view-container
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
_resizeListener: null,
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this._resizeListener = Ember.run.bind(this, this.calculatePreviewIsHidden);
this.get('resizeService').on('debouncedDidResize', this._resizeListener);
this.calculatePreviewIsHidden();
},
willDestroy: function () {
this.get('resizeService').off('debouncedDidResize', this._resizeListener);
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['gh-view', 'content-view-container'],
previewIsHidden: false,
resizeService: Ember.inject.service(),
calculatePreviewIsHidden: function () {
if (this.$('.content-preview').length) {
this.set('previewIsHidden', !this.$('.content-preview').is(':visible'));
}
},
didInsertElement: function () {
this._super(...arguments);
this.calculatePreviewIsHidden();
this.get('resizeService').on('debouncedDidResize',
Ember.run.bind(this, this.calculatePreviewIsHidden));
}
});
|
Fix no header test for csv formatter
|
import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Formatter()
def test_add_args(self):
new_parser = self.formatter.add_args(self.parser)
self.assertEqual(new_parser, self.parser)
args = new_parser.parse_args(['--with_header'])
self.assertTrue(args.with_header)
args = new_parser.parse_args([])
self.assertFalse(args.with_header)
def test_marshall_no_header(self):
new_parser = self.formatter.add_args(self.parser)
args = new_parser.parse_args([])
result = self.formatter.marshall(args, self.data)
expect = "a,1\r\nb,2\r\nc,3\r\n"
self.assertEqual(result, expect)
def test_marshall_with_header(self):
new_parser = self.formatter.add_args(self.parser)
args = new_parser.parse_args(['--with_header'])
result = self.formatter.marshall(args, self.data)
expect = "char,order\r\na,1\r\nb,2\r\nc,3\r\n"
self.assertEqual(result, expect)
|
import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Formatter()
def test_add_args(self):
new_parser = self.formatter.add_args(self.parser)
self.assertEqual(new_parser, self.parser)
args = new_parser.parse_args(['--with_header'])
self.assertTrue(args.with_header)
args = new_parser.parse_args([])
self.assertFalse(args.with_header)
def test_marshall_no_header(self):
new_parser = self.formatter.add_args(self.parser)
args = new_parser.parse_args([])
result = self.formatter.marshall(args, self.data)
expect = "a,1\r\nb,2\r\nc,3\r\n"
def test_marshall_with_header(self):
new_parser = self.formatter.add_args(self.parser)
args = new_parser.parse_args(['--with_header'])
result = self.formatter.marshall(args, self.data)
expect = "char,order\r\na,1\r\nb,2\r\nc,3\r\n"
self.assertEqual(result, expect)
|
Create response for request and create env var for twilio account.
|
var express = require('express');
var router = express.Router();
var app = express();
router.get('/sendSMS', function(req, res, next){
var number = req.query['number'];
var body_message = req.query['message'];
var client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
client.sendSms({
to: number,
from: '+48799449177',
body: body_message
}, function(error, message) {
if (!error) {
console.log('Success! The SID for this SMS message is:');
console.log(message.sid);
console.log('Message sent on:');
console.log(message.dateCreated);
res.status(202).send(true);
} else {
console.log('Oops! There was an error.'+ error.message);
res.status(500).send(error.message);
}
});
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
var app = express();
router.get('/sendSMS', function(req, res, next){
var number = req.query['number'];
var body_message = req.query['message'];
var client = require('twilio')('AC525c4929b17f0023e6067967a16232f0', '7a1cfcc80b4adc7634cf037b3dbcd930');
client.sendSms({
to: number,
from: '+48799449177',
body: body_message
}, function(error, message) {
if (!error) {
console.log('Success! The SID for this SMS message is:');
console.log(message.sid);
console.log('Message sent on:');
console.log(message.dateCreated);
} else {
console.log('Oops! There was an error.'+ error.message);
}
});
});
module.exports = router;
|
Format mismatch, can not use historic node name
|
package main
import "crypto"
import "strings"
// Checksum algos
import (
_ "crypto/md5"
_ "crypto/sha1"
_ "crypto/sha256"
_ "crypto/sha512"
)
// Man, why don't people allow their table to be exported...
var checksumLookupTable = map[string]crypto.Hash{
"md5": crypto.MD5,
"sha1": crypto.SHA1,
"sha256": crypto.SHA256,
"sha512": crypto.SHA512,
}
var checksumAlgos = map[string]crypto.Hash{}
func filterChecksumAlgos() {
i := strings.Split(checksums, ",")
var j = map[string]crypto.Hash{}
for _, checksum := range i {
if checksumLookupTable[checksum].Available() == false {
Error.Fatalln("Unsupported checksum algorithm: " + checksum)
}
j[checksum] = checksumLookupTable[checksum]
}
checksumLookupTable = j
}
|
package main
import "crypto"
import "strings"
// Checksum algos
import (
_ "crypto/md5"
_ "crypto/sha1"
_ "crypto/sha256"
_ "crypto/sha512"
)
// Man, why don't people allow their table to be exported...
var checksumLookupTable = map[string]crypto.Hash{
"md5": crypto.MD5,
"sha1": crypto.SHA1,
"sha256": crypto.SHA256,
"sha256sum": crypto.SHA256,
"sha512": crypto.SHA512,
}
var checksumAlgos = map[string]crypto.Hash{}
func filterChecksumAlgos() {
i := strings.Split(checksums, ",")
var j = map[string]crypto.Hash{}
for _, checksum := range i {
if checksumLookupTable[checksum].Available() == false {
Error.Fatalln("Unsupported checksum algorithm: " + checksum)
}
j[checksum] = checksumLookupTable[checksum]
}
checksumLookupTable = j
}
|
Make the test mod take the version from the API.
|
package gigaherz.graph.api;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
public static final String MODID = "GraphLib";
public static final String VERSION = Constants.API_VERSION;
@SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
public static Proxy proxy;
public static BlockRegistered networkTest;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
networkTest = new BlockNetworkTest("blockNetworkTest");
GameRegistry.register(networkTest);
GameRegistry.register(networkTest.createItemBlock());
GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");
proxy.preInit();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
proxy.init();
FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
}
}
|
package gigaherz.graph.api;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
public static final String MODID = "GraphLib";
public static final String VERSION = "1.0";
@SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
public static Proxy proxy;
public static BlockRegistered networkTest;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
networkTest = new BlockNetworkTest("blockNetworkTest");
GameRegistry.register(networkTest);
GameRegistry.register(networkTest.createItemBlock());
GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");
proxy.preInit();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
proxy.init();
FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
}
}
|
Customize Messenger widget - remove useless param
|
KylinApp.service('MessageService', function () {
var options = {
extraClasses: 'messenger-fixed messenger-on-top messenger-on-right',
theme: 'air'
};
this.sendMsg = function (msg, type, actions, sticky) {
var data = {
message: msg,
type: angular.isDefined(type) ? type : 'info',
actions: actions,
showCloseButton: true
};
// Whether sticky the message, otherwise it will hide after a period.
if (angular.isDefined(sticky) && sticky === true) {
data.hideAfter = false;
}
Messenger(options).post(data);
}
});
|
KylinApp.service('MessageService', function (GraphBuilder) {
var options = {
extraClasses: 'messenger-fixed messenger-on-top messenger-on-right',
theme: 'air'
};
this.sendMsg = function (msg, type, actions, sticky) {
var data = {
message: msg,
type: angular.isDefined(type) ? type : 'info',
actions: actions,
showCloseButton: true
};
// Whether sticky the message, otherwise it will hide after a period.
if (angular.isDefined(sticky) && sticky === true) {
data.hideAfter = false;
}
Messenger(options).post(data);
}
});
|
Add missing header file to the list of sources
|
try:
from setuptools import setup
from setuptools.extension import Extension
except ImportError:
from distutils.core import setup, Extension
def main():
module = Extension('rrdtool',
sources=['rrdtoolmodule.h', 'rrdtoolmodule.c'],
include_dirs=['/usr/local/include'],
library_dirs=['/usr/local/lib'],
libraries=['rrd'])
kwargs = dict(
name='rrdtool',
version='0.1.7',
description='Python bindings for rrdtool',
keywords=['rrdtool'],
author='Christian Kroeger, Hye-Shik Chang',
author_email='commx@commx.ws',
license='LGPL',
url='https://github.com/commx/python-rrdtool',
ext_modules=[module],
test_suite="tests"
)
setup(**kwargs)
if __name__ == '__main__':
main()
|
try:
from setuptools import setup
from setuptools.extension import Extension
except ImportError:
from distutils.core import setup, Extension
def main():
module = Extension('rrdtool',
sources=['rrdtoolmodule.c'],
include_dirs=['/usr/local/include'],
library_dirs=['/usr/local/lib'],
libraries=['rrd'])
kwargs = dict(
name='rrdtool',
version='0.1.7',
description='Python bindings for rrdtool',
keywords=['rrdtool'],
author='Christian Kroeger, Hye-Shik Chang',
author_email='commx@commx.ws',
license='LGPL',
url='https://github.com/commx/python-rrdtool',
ext_modules=[module],
test_suite="tests"
)
setup(**kwargs)
if __name__ == '__main__':
main()
|
Fix many ESLint errors (STRIPES-100)
|
// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React from 'react';
import List from '@folio/stripes-components/lib/List';
import TextField from '@folio/stripes-components/lib/TextField';
import Icon from '@folio/stripes-components/lib/Icon';
import css from './ListDropdown.css';
function ListDropdown(props) {
const handleItemClick = item => props.onClickItem(item);
const handleSearchChange = e => props.onChangeSearch(e);
const permissionDDFormatter = item => (
<li key={item.permissionName} >
<button type="button" className={css.itemControl} onClick={() => { handleItemClick(item); }}>
{!item.displayName ? item.permissionName : item.displayName}
</button>
</li>
);
return (
<div>
<TextField
noBorder
placeholder="Search"
startControl={<Icon icon="search" />}
onChange={handleSearchChange}
/>
<List
itemFormatter={permissionDDFormatter}
items={props.items}
listClass={css.ListDropdown}
/>
</div>
);
}
ListDropdown.propTypes = {
onChangeSearch: React.PropTypes.func.isRequired,
items: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
};
export default ListDropdown;
|
import React from 'react';
import css from './ListDropdown.css';
import List from '@folio/stripes-components/lib/List';
import TextField from '@folio/stripes-components/lib/TextField';
import Button from '@folio/stripes-components/lib/Button';
import Icon from '@folio/stripes-components/lib/Icon';
function ListDropdown(props){
const handleItemClick = (item) => props.onClickItem(item);
const handleSearchChange = (e) => props.onChangeSearch(e);
const permissionDDFormatter = (item) => (
<li key={item.permissionName} >
<button type="button" className={css.itemControl} onClick={() => {handleItemClick(item)}}>
{!item.displayName?item.permissionName:item.displayName}
</button>
</li>
);
return(
<div>
<TextField
noBorder
placeholder="Search"
startControl={<Icon icon="search"/>}
onChange={handleSearchChange}
/>
<List
itemFormatter={permissionDDFormatter}
items={props.items}
listClass={css.ListDropdown}
/>
</div>
);
}
export default ListDropdown;
|
Remove unneeded error parameter for login form
|
var angular = require('angular');
angular.module('LoginComp', ['AuthSvc']).component('loginComponent', {
templateUrl: '/views/shimapan/login-form.html',
controller: ['$scope', '$timeout', 'AuthService', function ($scope, $timeout, AuthService) {
$scope.login = function () {
AuthService.login({
username: $scope.username,
password: $scope.password
}).catch(function() {
$scope.error = true;
$timeout(function() {
$scope.error = false;
},820);
});
};
}]
});
|
var angular = require('angular');
angular.module('LoginComp', ['AuthSvc']).component('loginComponent', {
templateUrl: '/views/shimapan/login-form.html',
controller: ['$scope', '$timeout', 'AuthService', function ($scope, $timeout, AuthService) {
$scope.login = function () {
AuthService.login({
username: $scope.username,
password: $scope.password
}).catch(function(err) {
$scope.error = true;
$timeout(function() {
$scope.error = false;
},820);
});
};
}]
});
|
Make server module requirements explicit
|
Donations.App = Space.Application.define('Donations.App', {
configuration: {
appId: 'Donations.App'
},
requiredModules: [
'Space.messaging',
'Space.accounts',
'Space.accountsUi',
'Space.eventSourcing',
'Donations.domain'
],
singletons: [
// APIS
'Donations.OrgRegistrationApi',
'Donations.OrgApi',
'Donations.AppealsApi',
// PROJECTIONS
'Donations.OrgRegistrationsProjection',
'Donations.OrgProjection',
'Donations.LocationsProjection',
'Donations.AppealsProjection',
'Donations.OpenAppealsProjection',
'Donations.Publications'
],
onInitialize() {
this.injector.map('Donations.Organizations').asStaticValue();
this.injector.map('Donations.Appeals').asStaticValue();
this.injector.map('Donations.OpenAppeals').asStaticValue();
this.injector.map('Donations.Locations').asStaticValue();
},
onReset() {
this.injector.get('Donations.Organizations').remove({});
this.injector.get('Donations.Appeals').remove({});
this.injector.get('Donations.OpenAppeals').remove({});
this.injector.get('Donations.Locations').remove({});
}
});
|
Donations.App = Space.Application.define('Donations.App', {
configuration: {
appId: 'Donations.App'
},
requiredModules: [
'Space.accounts',
'Space.accountsUi',
'Donations.domain'
],
singletons: [
// APIS
'Donations.OrgRegistrationApi',
'Donations.OrgApi',
'Donations.AppealsApi',
// PROJECTIONS
'Donations.OrgRegistrationsProjection',
'Donations.OrgProjection',
'Donations.LocationsProjection',
'Donations.AppealsProjection',
'Donations.OpenAppealsProjection',
'Donations.Publications'
],
onInitialize() {
this.injector.map('Donations.Organizations').asStaticValue();
this.injector.map('Donations.Appeals').asStaticValue();
this.injector.map('Donations.OpenAppeals').asStaticValue();
this.injector.map('Donations.Locations').asStaticValue();
},
onReset() {
this.injector.get('Donations.Organizations').remove({});
this.injector.get('Donations.Appeals').remove({});
this.injector.get('Donations.OpenAppeals').remove({});
this.injector.get('Donations.Locations').remove({});
}
});
|
Fix error with data being passed to redirect method
This fixes a bug where the title was being passed to the wrong
method which caused the redirect to error.
|
const router = require('express').Router()
const { getProjectDetails } = require('./shared.middleware')
const {
populateDetailsFormMiddleware,
investmentDetailsFormPostMiddleware,
} = require('./form.middleware')
function createGetHandler (req, res) {
if (!res.locals.equityCompany) {
return res.redirect('/investment/start')
}
return res.render('investment/create', {
title: 'Add investment project',
})
}
function createPostHandler (req, res) {
if (res.locals.form.errors) {
return res.render('investment/create', {
title: 'Add investment project',
})
}
return res.redirect(`/investment/${res.locals.resultId}`)
}
router.param('id', getProjectDetails)
router.get('/create', populateDetailsFormMiddleware, createGetHandler)
router.post('/create', populateDetailsFormMiddleware, investmentDetailsFormPostMiddleware, createPostHandler)
module.exports = {
router,
createGetHandler,
createPostHandler,
}
|
const router = require('express').Router()
const { getProjectDetails } = require('./shared.middleware')
const {
populateDetailsFormMiddleware,
investmentDetailsFormPostMiddleware,
} = require('./form.middleware')
function createGetHandler (req, res) {
if (!res.locals.equityCompany) {
return res.redirect('/investment/start')
}
return res.render('investment/create', {
title: 'Add investment project',
})
}
function createPostHandler (req, res) {
if (res.locals.form.errors) {
return res.render('investment/create')
}
return res.redirect(`/investment/${res.locals.resultId}`, {
title: 'Add investment project',
})
}
router.param('id', getProjectDetails)
router.get('/create', populateDetailsFormMiddleware, createGetHandler)
router.post('/create', populateDetailsFormMiddleware, investmentDetailsFormPostMiddleware, createPostHandler)
module.exports = {
router,
createGetHandler,
createPostHandler,
}
|
Make test print meta strings
|
package com.io7m.jcanephora;
import java.io.IOException;
import javax.media.opengl.GLContext;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.io7m.jaux.Constraints.ConstraintError;
public class GLMetaJOGL30Test
{
private GLContext context;
@Before public void setUp()
throws Exception
{
this.context = JOGL30.createOffscreenDisplay(640, 480);
}
@After public void tearDown()
throws Exception
{
JOGL30.destroyDisplay(this.context);
}
@Test public void testMetaStrings()
throws GLException,
IOException,
ConstraintError
{
final GLInterface gl = GLInterfaceJOGL30Util.getGL(this.context);
final String vn = gl.metaGetVendor();
final String vr = gl.metaGetVersion();
final String r = gl.metaGetRenderer();
Assert.assertNotNull(vn);
Assert.assertNotNull(vr);
Assert.assertNotNull(r);
System.out.println("Vendor : " + vn);
System.out.println("Version : " + vr);
System.out.println("Renderer : " + r);
}
}
|
package com.io7m.jcanephora;
import java.io.IOException;
import javax.media.opengl.GLContext;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.io7m.jaux.Constraints.ConstraintError;
public class GLMetaJOGL30Test
{
private GLContext context;
@Before public void setUp()
throws Exception
{
this.context = JOGL30.createOffscreenDisplay(640, 480);
}
@After public void tearDown()
throws Exception
{
JOGL30.destroyDisplay(this.context);
}
@Test public void testMetaStrings()
throws GLException,
IOException,
ConstraintError
{
final GLInterface gl = GLInterfaceJOGL30Util.getGL(this.context);
final String vn = gl.metaGetVendor();
final String vr = gl.metaGetVersion();
final String r = gl.metaGetRenderer();
Assert.assertNotNull(vn);
Assert.assertNotNull(vr);
Assert.assertNotNull(r);
}
}
|
Replace readRegexp() with next() in Holder
|
const AstNode = require('./ast-node');
class Holder extends AstNode {
type() {
return 'holder';
}
/**
* @param {ParseContext} context
* @return {boolean}
*/
read(context) {
const config = context.config();
const tm = context.lookaheadTextManager();
try {
tm.next(config.openDelimiter());
tm.whitespace();
tm.next('$');
return true;
} catch (e) {
return false;
}
}
/**
* @param {ParseContext} context
* @return {AstNodeParseResult}
*/
parse(context) {
const config = context.config();
const tm = context.sourceTextManager();
tm.next(config.openDelimiter());
tm.whitespace();
const keySection = context.parse('var');
const filterSection = context.parse('filter_chain');
tm.whitespace();
tm.next(config.closeDelimiter());
return {
type: this.type(),
keys: keySection.keys,
filters: filterSection.filters,
};
}
}
module.exports = Holder;
|
const AstNode = require('./ast-node');
class Holder extends AstNode {
type() {
return 'holder';
}
/**
* @param {ParseContext} context
* @return {boolean}
*/
read(context) {
const config = context.config();
const tm = context.lookaheadTextManager();
try {
tm.next(config.openDelimiter());
tm.whitespace();
tm.readRegexp(/^\$/, true);
return true;
} catch (e) {
return false;
}
}
/**
* @param {ParseContext} context
* @return {AstNodeParseResult}
*/
parse(context) {
const config = context.config();
const tm = context.sourceTextManager();
tm.next(config.openDelimiter());
tm.whitespace();
const keySection = context.parse('var');
const filterSection = context.parse('filter_chain');
tm.whitespace();
tm.next(config.closeDelimiter());
return {
type: this.type(),
keys: keySection.keys,
filters: filterSection.filters,
};
}
}
module.exports = Holder;
|
Fix wrong config includes in kit package
|
"""Adhocracy extension."""
from pyramid.config import Configurator
from adhocracy_core import root_factory
def includeme(config):
"""Setup adhocracy extension.
The kit package should be exactly like the spd package but with different
root permissions and default translations for the emails.
"""
# copied from adhocracy_spd (without resources and translations)
config.include('adhocracy_core')
config.commit()
config.include('adhocracy_spd.sheets')
config.include('adhocracy_spd.workflows')
config.include('adhocracy_spd.evolution')
# add translations
config.add_translation_dirs('adhocracy_core:locale/')
# copoied from adhocracy_spd.resources resources
config.include('adhocracy_spd.resources.digital_leben')
# include kit resource types
config.include('.resources')
def main(global_config, **settings):
""" Return a Pyramid WSGI application. """
config = Configurator(settings=settings, root_factory=root_factory)
includeme(config)
return config.make_wsgi_app()
|
"""Adhocracy extension."""
from pyramid.config import Configurator
from adhocracy_core import root_factory
def includeme(config):
"""Setup adhocracy extension.
The kit package should be exactly like the spd package but with different
root permissions and default translations for the emails.
"""
# copied from adhocracy_spd (without resources and translations)
config.include('adhocracy_core')
config.commit()
config.include('.sheets')
config.include('.workflows')
config.include('.evolution')
# add translations
config.add_translation_dirs('adhocracy_core:locale/')
# copoied from adhocracy_spd.resources resources
config.include('adhocracy-spd.resources.digital_leben')
# include kit resource types
config.include('.resources')
def main(global_config, **settings):
""" Return a Pyramid WSGI application. """
config = Configurator(settings=settings, root_factory=root_factory)
includeme(config)
return config.make_wsgi_app()
|
Fix populateByService and make it functional
|
import fp from 'lodash/fp';
import { plural } from 'pluralize';
const populateList = (list, idField) => (data) => {
return fp.map((doc) => {
let item = data.find((item) => {
return String(doc[idField]) === String(item.id);
});
return item;
})(list);
};
const populateByService = (app, idField, typeField, options) => (list) => {
let types = fp.groupBy(typeField, list);
return Promise.all(
Object.keys(types).map((type) => {
let entries = types[type];
return app.service(plural(type)).find(Object.assign({
query: {
_id: { $in: fp.map(idField, entries) },
}
}, options));
})
).then((results) => {
return fp.flow(
options.provider? fp.flow(fp.map('data'), fp.flatten) : fp.flatten,
populateList(list, idField),
fp.compact
)(results);
});
};
export default { populateList, populateByService };
|
import { flatten, groupBy, map, omit } from 'lodash';
import { plural } from 'pluralize';
export function populateByService(app, documents, idField, typeField, options) {
let types = groupBy(documents, typeField);
return Promise.all(
Object.keys(types).map((type) => {
let entries = types[type];
return app.service(plural(type)).find(Object.assign({
query: {
_id: { $in: map(entries, idField) },
}
}, options));
})
).then((results) => {
results = options.provider? flatten(map(results, 'data')) : flatten(results);
documents = map(documents, (doc) => {
return Object.assign({ _id: doc.id }, doc, results.find((item) => {
return String(doc[idField]) === String(item.id);
}));
});
return documents;
});
}
|
Create SweetScroll instance after updated current page order
|
// @flow
import { PureComponent } from 'react'
import scrollParent from 'scrollparent'
import SweetScroll from 'sweet-scroll'
import type { Children } from 'react'
import Wrapper from './Wrapper'
type Props = {
width: number,
currentPageOrder: number,
children?: ?Children,
}
export default class Scroller extends PureComponent<void, Props, void> {
static scrollOptions = {
duration: 500,
// easing: 'easeOutExpo',
easing: 'easeOutQuint',
verticalScroll: true,
horizontalScroll: false,
// quickMode: true,
}
// for lint
props: Props
el: HTMLElement
componentDidUpdate ({ currentPageOrder: prevCurrentPageOrder }: Props) {
const { currentPageOrder, width } = this.props
if (currentPageOrder !== prevCurrentPageOrder) {
// NOTE: 16px: spacing between pages
// FIXME: adjust size params automatically
const scroller = new SweetScroll(Scroller.scrollOptions, scrollParent(this.el))
scroller.toTop(currentPageOrder * (768 * (width / 1024) + 16))
}
}
render () {
return (
<Wrapper innerRef={(el) => { this.el = el }}>
{ this.props.children }
</Wrapper>
)
}
}
|
// @flow
import { PureComponent } from 'react'
import scrollParent from 'scrollparent'
import SweetScroll from 'sweet-scroll'
import type { Children } from 'react'
import Wrapper from './Wrapper'
type Props = {
width: number,
currentPageOrder: number,
children?: ?Children,
}
export default class Scroller extends PureComponent<void, Props, void> {
static scrollOptions = {
duration: 500,
// easing: 'easeOutExpo',
easing: 'easeOutQuint',
verticalScroll: true,
horizontalScroll: false,
// quickMode: true,
}
// for lint
props: Props
scroller: SweetScroll
componentDidUpdate ({ currentPageOrder: prevCurrentPageOrder }: Props) {
const { currentPageOrder, width } = this.props
if (currentPageOrder !== prevCurrentPageOrder) {
// NOTE: 16px: spacing between pages
// FIXME: adjust size params automatically
this.scroller.toTop(currentPageOrder * (768 * (width / 1024) + 16))
}
}
render () {
return (
<Wrapper
innerRef={(el) => {
this.scroller = new SweetScroll(Scroller.scrollOptions, scrollParent(el))
}}
>
{ this.props.children }
</Wrapper>
)
}
}
|
Fix CircleCI artifacts env path
|
const fs = require('fs')
const glob = require('glob')
const outputDirectory = [process.env.$CIRCLE_ARTIFACTS, 'snapshots']
.filter(x => x)
.join('/')
const createDir = dir => {
const splitPath = dir.split('/')
splitPath.reduce((path, subPath) => {
if (!fs.existsSync(path)) {
console.log(`Create directory at ${path}.`);
fs.mkdirSync(path)
}
return `${path}/${subPath}`
})
}
glob('src/__snapshots__/*.snap', {}, (er, files) => {
files.forEach(fileName => {
const newName = fileName
.replace(/__snapshots__\//g, '')
.replace('src/', `${outputDirectory}/`)
console.log(`Move file ${fileName} to ${newName}.`);
createDir(newName)
fs.renameSync(fileName, newName)
})
glob('src/__snapshots__', {}, (er, files) => {
files.forEach(fileName => {
fs.rmdirSync(fileName)
})
})
})
|
const fs = require('fs')
const glob = require('glob')
const outputDirectory = [process.env.CIRCLE_ARTIFACTS, 'snapshots']
.filter(x => x)
.join('/')
const createDir = dir => {
const splitPath = dir.split('/')
splitPath.reduce((path, subPath) => {
if (!fs.existsSync(path)) {
console.log(`Create directory at ${path}.`);
fs.mkdirSync(path)
}
return `${path}/${subPath}`
})
}
glob('src/__snapshots__/*.snap', {}, (er, files) => {
files.forEach(fileName => {
const newName = fileName
.replace(/__snapshots__\//g, '')
.replace('src/', `${outputDirectory}/`)
console.log(`Move file ${fileName} to ${newName}.`);
createDir(newName)
fs.renameSync(fileName, newName)
})
glob('src/__snapshots__', {}, (er, files) => {
files.forEach(fileName => {
fs.rmdirSync(fileName)
})
})
})
|
Add decoding of the recieved data
|
<?php
/**
* Main entry point
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
const ROOT_PATH = __DIR__;
require_once __DIR__ . '/../app/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/', function (Request $request) use ($app, $notificationHandler) {
$notificationHandler->handleHipayNotification(urldecode($request->request->get('xml')));
return new Response(null, 204);
});
$app->error(function (Exception $e) use ($app, $notificationHandler) {
$notificationHandler->handleException($e);
return new Response($e->getMessage());
});
$app->get('/', function () {
return 'Hello World';
});
$app->run();
|
<?php
/**
* Main entry point
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
const ROOT_PATH = __DIR__;
require_once __DIR__ . '/../app/bootstrap.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app->post('/', function (Request $request) use ($app, $notificationHandler) {
$notificationHandler->handleHipayNotification($request->getContent());
return new Response(null, 204);
});
$app->error(function (Exception $e) use ($app, $notificationHandler) {
$notificationHandler->handleException($e);
return new Response($e->getMessage());
});
$app->get('/', function () {
return 'Hello World';
});
$app->run();
|
Make signature of test auth source match that of class it extends
|
<?php
namespace SimpleSAML\Test\Auth;
use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;
/**
* Tests for SimpleSAML_Auth_Source
*/
class SourceTest extends ClearStateTestCase
{
public function testParseAuthSource()
{
$class = new \ReflectionClass('SimpleSAML_Auth_Source');
$method = $class->getMethod('parseAuthSource');
$method->setAccessible(true);
// test direct instantiation of the auth source object
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
// test instantiation via an auth source factory
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
}
}
class TestAuthSource extends \SimpleSAML_Auth_Source
{
public function authenticate(array &$state)
{
}
}
class TestAuthSourceFactory implements SourceFactory
{
public function create(array $info, array $config)
{
return new TestAuthSource($info, $config);
}
}
|
<?php
namespace SimpleSAML\Test\Auth;
use SimpleSAML\Auth\SourceFactory;
use SimpleSAML\Test\Utils\ClearStateTestCase;
/**
* Tests for SimpleSAML_Auth_Source
*/
class SourceTest extends ClearStateTestCase
{
public function testParseAuthSource()
{
$class = new \ReflectionClass('SimpleSAML_Auth_Source');
$method = $class->getMethod('parseAuthSource');
$method->setAccessible(true);
// test direct instantiation of the auth source object
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSource']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
// test instantiation via an auth source factory
$authSource = $method->invokeArgs(null, ['test', ['SimpleSAML\Test\Auth\TestAuthSourceFactory']]);
$this->assertInstanceOf('SimpleSAML\Test\Auth\TestAuthSource', $authSource);
}
}
class TestAuthSource extends \SimpleSAML_Auth_Source
{
public function authenticate(&$state)
{
}
}
class TestAuthSourceFactory implements SourceFactory
{
public function create(array $info, array $config)
{
return new TestAuthSource($info, $config);
}
}
|
Expand figure when window is resized
|
from PyQt4 import QtGui,QtCore
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def sizeHint(self):
w, h = self.get_width_height()
return QtCore.QSize(w,h)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self.canvas)
|
from PyQt4 import QtGui
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec
class MplCanvas(FigureCanvas):
def __init__(self):
self.fig = Figure()
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def resizeEvent(self, event):
FigureCanvas.resizeEvent(self, event)
class MplWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.canvas.setParent(self)
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
|
Add compare method from com.thaiopensource.relaxng.output.common.
|
package com.thaiopensource.xml.util;
public final class Name {
final private String namespaceUri;
final private String localName;
final private int hc;
public Name(String namespaceUri, String localName) {
this.namespaceUri = namespaceUri;
this.localName = localName;
this.hc = namespaceUri.hashCode() ^ localName.hashCode();
}
public String getNamespaceUri() {
return namespaceUri;
}
public String getLocalName() {
return localName;
}
public boolean equals(Object obj) {
if (!(obj instanceof Name))
return false;
Name other = (Name)obj;
return (this.hc == other.hc
&& this.namespaceUri.equals(other.namespaceUri)
&& this.localName.equals(other.localName));
}
public int hashCode() {
return hc;
}
// We include this, but don't derive from Comparator<Name> to avoid a dependency on Java 5.
static public int compare(Name n1, Name n2) {
int ret = n1.namespaceUri.compareTo(n2.namespaceUri);
if (ret != 0)
return ret;
return n1.localName.compareTo(n2.localName);
}
}
|
package com.thaiopensource.xml.util;
public final class Name {
final private String namespaceUri;
final private String localName;
final private int hc;
public Name(String namespaceUri, String localName) {
this.namespaceUri = namespaceUri;
this.localName = localName;
this.hc = namespaceUri.hashCode() ^ localName.hashCode();
}
public String getNamespaceUri() {
return namespaceUri;
}
public String getLocalName() {
return localName;
}
public boolean equals(Object obj) {
if (!(obj instanceof Name))
return false;
Name other = (Name)obj;
return (this.hc == other.hc
&& this.namespaceUri.equals(other.namespaceUri)
&& this.localName.equals(other.localName));
}
public int hashCode() {
return hc;
}
}
|
Clean one last new line.
|
<?php
namespace TypiCMS\Modules\Core\Http\Controllers;
use Illuminate\Routing\Controller;
abstract class BaseApiController extends Controller
{
/**
* Array of endpoints that do not require authorization.
*/
protected $publicEndpoints = [];
protected $repository;
public function __construct($repository = null)
{
$this->middleware('api', ['except' => $this->$publicEndpoints]);
$this->repository = $repository;
}
/**
* List resources.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$models = $this->repository->all([], true);
return response()->json($models, 200);
}
/**
* Update the specified resource in storage.
*
* @param $model
*
* @return \Illuminate\Http\JsonResponse
*/
public function show($model)
{
return response()->json($model, 200);
}
/**
* Update the specified resource in storage.
*
* @param $model
*
* @return \Illuminate\Http\JsonResponse
*/
public function edit($model)
{
return response()->json($model, 200);
}
}
|
<?php
namespace TypiCMS\Modules\Core\Http\Controllers;
use Illuminate\Routing\Controller;
abstract class BaseApiController extends Controller
{
/**
* Array of endpoints that do not require authorization.
*/
protected $publicEndpoints = [];
protected $repository;
public function __construct($repository = null)
{
$this->middleware('api', ['except' => $this->$publicEndpoints]);
$this->repository = $repository;
}
/**
* List resources.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$models = $this->repository->all([], true);
return response()->json($models, 200);
}
/**
* Update the specified resource in storage.
*
* @param $model
*
* @return \Illuminate\Http\JsonResponse
*/
public function show($model)
{
return response()->json($model, 200);
}
/**
* Update the specified resource in storage.
*
* @param $model
*
* @return \Illuminate\Http\JsonResponse
*/
public function edit($model)
{
return response()->json($model, 200);
}
}
|
Make photos and videos accessible
|
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
url(r'^google/', include('djangoogle.urls')),
url(r'^project/', include('project.projects.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^jsi18n/(?P<packages>\S+?)/$',
'django.views.i18n.javascript_catalog'),
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'),
url(r'^$', 'project.views.index'),
# Media serving
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True},
name='media',
),
)
|
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', admin.site.urls),
url(r'^publication/', include('project.publications.urls')),
#url(r'^google/', include('project.google.urls')),
url(r'^project/', include('project.projects.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^jsi18n/(?P<packages>\S+?)/$',
'django.views.i18n.javascript_catalog'),
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog'),
url(r'^$', 'project.views.index'),
# Media serving
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes': True},
name='media',
),
)
|
Fix docstring and class name
|
#
# Copyright (c) 2006, 2007 Canonical
#
# Written by Gustavo Niemeyer <gustavo@niemeyer.net>
#
# This file is part of Storm Object Relational Mapper.
#
# Storm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Storm 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""ZStorm-aware schema manager."""
import transaction
from storm.schema import Schema
class ZCommitter(object):
"""A L{Schema} committer that uses Zope's transaction manager."""
def commit(self):
transaction.commit()
def rollback(self):
transaction.abort()
class ZSchema(Schema):
"""Convenience for creating L{Schema}s that use a L{ZCommitter}."""
def __init__(self, creates, drops, deletes, patch_package):
committer = ZCommitter()
super(ZSchema, self).__init__(creates, drops, deletes, patch_package,
committer)
|
#
# Copyright (c) 2006, 2007 Canonical
#
# Written by Gustavo Niemeyer <gustavo@niemeyer.net>
#
# This file is part of Storm Object Relational Mapper.
#
# Storm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Storm 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""ZStorm-aware schema manager."""
import transaction
from storm.schema import Schema
class ZStormCommitter(object):
"""A L{Schema} committer that uses Zope's transaction manager."""
def commit(self):
transaction.commit()
def rollback(self):
transaction.abort()
class ZSchema(Schema):
"""Convenience for creating L{Schema}s that use a L{ZStormCommitter}."""
def __init__(self, creates, drops, deletes, patch_package):
committer = ZStormCommitter()
super(ZSchema, self).__init__(creates, drops, deletes, patch_package,
committer)
|
Update RequestVote step 1 test data
|
package raft
import (
"reflect"
"testing"
)
// 1. Reply false if term < currentTerm (#5.1)
// Note: test based on Figure 7; server is leader line; peer is case (a)
func TestCM_RpcRV_TermLessThanCurrentTerm(t *testing.T) {
f := func(setup func(t *testing.T) (mcm *managedConsensusModule, mrs *mockRpcSender)) {
mcm, _ := setup(t)
serverTerm := mcm.pcm.persistentState.GetCurrentTerm()
requestVote := &RpcRequestVote{7, 9, 6}
reply := mcm.pcm.rpc("s2", requestVote)
expectedRpc := &RpcRequestVoteReply{serverTerm, false}
if !reflect.DeepEqual(reply, expectedRpc) {
t.Fatal(reply)
}
}
f(testSetupMCM_Follower_Figure7LeaderLine)
f(testSetupMCM_Candidate_Figure7LeaderLine)
f(testSetupMCM_Leader_Figure7LeaderLine)
}
|
package raft
import (
"reflect"
"testing"
)
func makeRVWithTerm(term TermNo) *RpcRequestVote {
return &RpcRequestVote{term, 0, 0}
}
// 1. Reply false if term < currentTerm (#5.1)
// Note: this test assumes server in sync with the Figure 7 leader
func TestCM_RpcRV_TermLessThanCurrentTerm(t *testing.T) {
f := func(setup func(t *testing.T) (mcm *managedConsensusModule, mrs *mockRpcSender)) {
mcm, _ := setup(t)
serverTerm := mcm.pcm.persistentState.GetCurrentTerm()
requestVote := makeRVWithTerm(serverTerm - 1)
reply := mcm.pcm.rpc("s2", requestVote)
expectedRpc := &RpcRequestVoteReply{serverTerm, false}
if !reflect.DeepEqual(reply, expectedRpc) {
t.Fatal(reply)
}
}
f(testSetupMCM_Follower_Figure7LeaderLine)
f(testSetupMCM_Candidate_Figure7LeaderLine)
f(testSetupMCM_Leader_Figure7LeaderLine)
}
|
Make the default duration of the transition in the 'setSmooth' method of
SmoothHelper a property.
|
Dashboard.SmoothHelper = Ember.Mixin.create({
_smoothHelperInterval: 10,
_smoothHelperDuration: 1000,
_smoothHelperProperties: function() {
return {};
}.property(),
setSmooth: function(property, value, duration) {
var p = this.get('_smoothHelperProperties');
var d = typeof duration !== 'undefined' ? duration : this.get('_smoothHelperDuration');
if (p[property] && p[property].intervalCall) {
clearInterval(p[property].intervalCall);
}
p[property] = {
initialValue: this.get(property),
targetValue: value,
currentX: 0,
step: Math.PI / (d / this.get('_smoothHelperInterval') * 2)
};
var that = this;
p[property].intervalCall = setInterval(function() {
if (p[property].currentX >= Math.PI / 2)
clearInterval(p[property].intervalCall);
else {
that.set(property, p[property].initialValue + (p[property].targetValue - p[property].initialValue) * Math.sin(p[property].currentX));
p[property].currentX = p[property].currentX + p[property].step;
}
}, this.get('_smoothHelperInterval'));
}
});
|
Dashboard.SmoothHelper = Ember.Mixin.create({
_smoothHelperInterval: 10,
_smoothHelperProperties: function() {
return {};
}.property(),
setSmooth: function(property, value, duration) {
var p = this.get('_smoothHelperProperties');
var d = typeof duration !== 'undefined' ? duration : 1000;
if (p[property] && p[property].intervalCall) {
clearInterval(p[property].intervalCall);
}
p[property] = {
initialValue: this.get(property),
targetValue: value,
currentX: 0,
step: Math.PI / (d / this.get('_smoothHelperInterval') * 2)
};
var that = this;
p[property].intervalCall = setInterval(function() {
if (p[property].currentX >= Math.PI / 2)
clearInterval(p[property].intervalCall);
else {
that.set(property, p[property].initialValue + (p[property].targetValue - p[property].initialValue) * Math.sin(p[property].currentX));
p[property].currentX = p[property].currentX + p[property].step;
}
}, this.get('_smoothHelperInterval'));
}
});
|
Fix map tiles (thanks Colin)
|
define(['leaflet'],
function (leaflet) {
/**
* @constructor
*/
function MapView(mapDivId)
{
this.map = leaflet.map(mapDivId);
leaflet.tileLayer(
'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}',
{
id: 'mapbox/streets-v11',
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
accessToken: 'pk.eyJ1IjoiYnJld21vb2siLCJhIjoiY2lqdWxoam42MGY4bXRzbTh2OXIzZDM1aCJ9.3Y4fgDB4imI3usjQWobQDA'
}
).addTo(this.map);
}
return MapView;
});
|
define(['leaflet'],
function (leaflet) {
/**
* @constructor
*/
function MapView(mapDivId)
{
this.map = leaflet.map(mapDivId);
leaflet.tileLayer(
'https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png32?access_token={accessToken}',
{
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
accessToken: 'pk.eyJ1IjoiYnJld21vb2siLCJhIjoiY2lqdWxoam42MGY4bXRzbTh2OXIzZDM1aCJ9.3Y4fgDB4imI3usjQWobQDA'
}
).addTo(this.map);
}
return MapView;
});
|
Use implicit paths to predefined conf files
|
"use strict";
angular.module('arethusa.core').constant('MAIN_ROUTE', {
controller: 'MainCtrl',
template: '<div ng-include="template"></div>',
resolve: {
loadConfiguration: function($q, $http, $route, configurator) {
var params = $route.current.params;
var confPath = './static/configs/';
var confUrl;
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
confUrl = confPath + params.conf + '.json';
} else if (params.conf_file) {
confUrl = params.conf_file;
} else {
confUrl = confPath + 'default.json';
}
return $http({
method: 'GET',
url: confUrl,
}).then(function(result) {
configurator.configuration = result.data;
});
}
}
});
|
"use strict";
angular.module('arethusa.core').constant('MAIN_ROUTE', {
controller: 'MainCtrl',
template: '<div ng-include="template"></div>',
resolve: {
loadConfiguration: function($q, $http, $route, configurator) {
var files = {
default: './static/configs/default.json',
staging: './static/configs/staging.json'
};
var params = $route.current.params;
var confUrl;
// Fall back to default and wrong paths to conf files
// need to be handled separately eventually
if (params.conf) {
confUrl = files[params.conf] || files.default;
} else if (params.conf_file) {
confUrl = params.conf_file;
} else {
confUrl = files.default;
}
return $http({
method: 'GET',
url: confUrl,
}).then(function(result) {
configurator.configuration = result.data;
});
}
}
});
|
Add roles "body:wrapper", "toolbar:wrapper", "page:wrapper"
|
const GitBook = require('gitbook-core');
const { React } = GitBook;
const Page = require('./Page');
const Toolbar = require('./Toolbar');
const Body = React.createClass({
propTypes: {
page: GitBook.PropTypes.Page,
readme: GitBook.PropTypes.Readme
},
render() {
const { page, readme } = this.props;
return (
<GitBook.InjectedComponent matching={{ role: 'body:wrapper' }}>
<div className="Body page-wrapper">
<GitBook.InjectedComponent matching={{ role: 'toolbar:wrapper' }}>
<Toolbar title={page.title} readme={readme} />
</GitBook.InjectedComponent>
<GitBook.InjectedComponent matching={{ role: 'page:wrapper' }}>
<Page page={page} />
</GitBook.InjectedComponent>
</div>
</GitBook.InjectedComponent>
);
}
});
module.exports = Body;
|
const GitBook = require('gitbook-core');
const { React } = GitBook;
const Page = require('./Page');
const Toolbar = require('./Toolbar');
const Body = React.createClass({
propTypes: {
page: GitBook.PropTypes.Page,
readme: GitBook.PropTypes.Readme
},
render() {
const { page, readme } = this.props;
return (
<div className="Body page-wrapper">
<Toolbar title={page.title} readme={readme} />
<Page page={page} />
</div>
);
}
});
module.exports = Body;
|
Simplify and make it a bit easier to read output
|
<?php
/* All code covered by the BSD license located at http://silverstripe.org/bsd-license/ */
namespace Marketo\CliTools;
use Composer\Script\Event;
/**
* Task for applying patch files from a folder to a source trunk
*
* Assumes that the patches were created relative to the root folder of the application, and
* can be applied using patch -p0
*
* @author Marcus Nyeholt <marcus@silverstripe.com.au>
*/
class ApplyPatches {
const DEFAULT_DIR = 'mysite/patches';
public static function run(Event $event) {
$patchDir = isset($_ENV['marketo_patch_dir']) ? $_ENV['marketo_patch_dir'] : getcwd() . DIRECTORY_SEPARATOR . static::DEFAULT_DIR;
$patches = glob($patchDir . '/*.patch');
if (count($patches)) {
foreach ($patches as $patchFile) {
$file = escapeshellarg($patchFile);
$event->getIO()->writeError("<info>Applying patches from $file </info>", TRUE);
passthru("patch -r - -p0 --no-backup-if-mismatch -i " . $file);
}
}
}
}
|
<?php
/* All code covered by the BSD license located at http://silverstripe.org/bsd-license/ */
namespace Marketo\CliTools;
use Composer\Script\Event;
/**
* Task for applying patch files from a folder to a source trunk
*
* Assumes that the patches were created relative to the root folder of the application, and
* can be applied using patch -p0
*
* @author Marcus Nyeholt <marcus@silverstripe.com.au>
*/
class ApplyPatches {
const DEFAULT_DIR = 'mysite/patches';
public static function run(Event $event) {
$patchDir = isset($_ENV['marketo_patch_dir']) ? $_ENV['marketo_patch_dir'] : getcwd() . DIRECTORY_SEPARATOR . static::DEFAULT_DIR;
$patches = glob($patchDir . '/*.patch');
if (count($patches)) {
foreach ($patches as $patchFile) {
$file = escapeshellarg($patchFile);
$event->getIO()->writeError('<info>Applying patches from ' . $file . ' </info>', false);
$exec = "patch -r - -p0 --no-backup-if-mismatch -i " . $file;
$output = `$exec`;
$event->getIO()->writeError('<info>' . $output . '</info>', false);
}
}
}
}
|
Fix a wrong config in sample application.
|
package org.mym.prettylog;
import android.app.Application;
import org.mym.plog.PLog;
import org.mym.plog.config.PLogConfig;
/**
* <p>
* This class shows how to init PLog Library.
* </p>
* Created by muyangmin on 9/1/16.
*
* @author muyangmin
* @since V1.3.0
*/
public class PLogApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
PLog.init(new PLogConfig.Builder()
// .emptyMsgLevel(Log.INFO)
.forceConcatGlobalTag(true)
.keepInnerClass(true)
.keepLineNumber(true)
.useAutoTag(true)
.maxLengthPerLine(160)
.build());
}
}
|
package org.mym.prettylog;
import android.app.Application;
import org.mym.plog.PLog;
import org.mym.plog.config.PLogConfig;
/**
* <p>
* This class shows how to init PLog Library.
* </p>
* Created by muyangmin on 9/1/16.
*
* @author muyangmin
* @since V3.94
*/
public class PLogApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
PLog.init(new PLogConfig.Builder()
.globalTag(null)
// .emptyMsgLevel(Log.INFO)
.forceConcatGlobalTag(true)
.keepInnerClass(true)
.keepLineNumber(true)
.useAutoTag(true)
.maxLengthPerLine(160)
.build());
}
}
|
Refactor API endpoint to match naming convention in server/config/routes.js
|
angular.module( 'moviematch.services', [] )
.factory( 'Auth', function( ) {} )
.factory( 'Session', function( ) {} )
.factory( 'Match', function( $http ) {
return {
sendVote: function( sessionID, userID, movieID, vote ) {
return $http.post( // returns a promise; if you want to make use of a callback simply use .then on the return value.
'/api/votes', // expect this endpoint to take a json object
// with sessionID and userID
// OR sessionuserID
// AND movieID
// AND vote (boolean true/false where true is yes and false is no)
{ sessionID: sessionID, userID: userID, movieID: movieID, vote: vote })
.then( function( response ) { // if the promise is resolved
return response;
},
function( err ) { // if the promise is rejected
console.error( err );
} );
}
}
} );
|
angular.module( 'moviematch.services', [] )
.factory( 'Auth', function( ) {} )
.factory( 'Session', function( ) {} )
.factory( 'Match', function( $http ) {
return {
sendVote: function( sessionID, userID, movieID, vote ) {
return $http.post( // returns a promise; if you want to make use of a callback simply use .then on the return value.
'/api/votes/recordvote', // expect this endpoint to take a json object
// with sessionID and userID
// OR sessionuserID
// AND movieID
// AND vote (boolean true/false where true is yes and false is no)
{ sessionID: sessionID, userID: userID, movieID: movieID, vote: vote })
.then( function( response ) { // if the promise is resolved
return response;
},
function( err ) { // if the promise is rejected
console.error( err );
} );
}
}
} );
|
Remove initialize() from duration mapper
|
/**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.coffig.mapper;
import org.seedstack.coffig.TreeNode;
import org.seedstack.coffig.node.ValueNode;
import org.seedstack.coffig.spi.ConfigurationMapper;
import java.lang.reflect.Type;
import java.time.Duration;
public class DurationMapper implements ConfigurationMapper {
@Override
public boolean canHandle(Type type) {
return type instanceof Class && Duration.class.isAssignableFrom((Class<?>) type);
}
@Override
public Object map(TreeNode treeNode, Type type) {
return Duration.parse(treeNode.value());
}
@Override
public TreeNode unmap(Object object, Type type) {
return new ValueNode(object.toString());
}
}
|
/**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.coffig.mapper;
import org.seedstack.coffig.Coffig;
import org.seedstack.coffig.TreeNode;
import org.seedstack.coffig.node.ValueNode;
import org.seedstack.coffig.spi.ConfigurationMapper;
import java.lang.reflect.Type;
import java.time.Duration;
public class DurationMapper implements ConfigurationMapper {
private Coffig coffig;
@Override
public void initialize(Coffig coffig) {
this.coffig = coffig;
}
@Override
public boolean canHandle(Type type) {
return type instanceof Class && Duration.class.isAssignableFrom((Class<?>) type);
}
@Override
public Object map(TreeNode treeNode, Type type) {
return Duration.parse(treeNode.value());
}
@Override
public TreeNode unmap(Object object, Type type) {
return new ValueNode(object.toString());
}
}
|
Fix handling projectTemplate with no name
|
import Ember from 'ember';
import C from 'ui/utils/constants';
export default Ember.Route.extend({
catalog: Ember.inject.service(),
allServices: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
catalogInfo: this.get('catalog').fetchTemplates({templateBase: C.EXTERNAL_ID.KIND_INFRA, category: C.EXTERNAL_ID.KIND_ALL}),
serviceChoices: this.get('allServices').choices(),
}).then((hash) => {
let existing = this.modelFor('settings.projects').projectTemplates;
let def = existing.find((tpl) => (tpl.get('name')||'').toLowerCase() === C.PROJECT_TEMPLATE.DEFAULT);
if ( def ) {
let tpl = def.cloneForNew();
tpl.isPublic = false;
tpl.name = '';
tpl.description = '';
hash.projectTemplate = tpl;
} else {
hash.projectTemplate = this.get('userStore').createRecord({
type: 'projectTemplate',
stacks: [],
isPublic: false,
});
}
hash.originalProjectTemplate = hash.projectTemplate;
return hash;
});
}
});
|
import Ember from 'ember';
import C from 'ui/utils/constants';
export default Ember.Route.extend({
catalog: Ember.inject.service(),
allServices: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
catalogInfo: this.get('catalog').fetchTemplates({templateBase: C.EXTERNAL_ID.KIND_INFRA, category: C.EXTERNAL_ID.KIND_ALL}),
serviceChoices: this.get('allServices').choices(),
}).then((hash) => {
let existing = this.modelFor('settings.projects').projectTemplates;
let def = existing.find((tpl) => tpl.get('name').toLowerCase() === C.PROJECT_TEMPLATE.DEFAULT);
if ( def ) {
let tpl = def.cloneForNew();
tpl.isPublic = false;
tpl.name = '';
tpl.description = '';
hash.projectTemplate = tpl;
} else {
hash.projectTemplate = this.get('userStore').createRecord({
type: 'projectTemplate',
stacks: [],
isPublic: false,
});
}
hash.originalProjectTemplate = hash.projectTemplate;
return hash;
});
}
});
|
Add typing module as dependencies
for python versions older than 3.5
|
from setuptools import setup, find_packages
import os.path
import re
import sys
package_name = 'sqlalchemy_dict'
py_version = sys.version_info[:2]
# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)
dependencies = [
'sqlalchemy'
]
if py_version < (3, 5):
dependencies.append('typing')
setup(
name=package_name,
version=package_version,
author='Mahdi Ghane.g',
description='sqlalchemy extension for interacting models with python dictionary.',
long_description=open('README.rst').read(),
url='https://github.com/meyt/sqlalchemy-dict',
packages=find_packages(),
install_requires=dependencies,
license='MIT License',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
]
)
|
from setuptools import setup, find_packages
import os.path
import re
package_name = 'sqlalchemy_dict'
# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)
dependencies = [
'sqlalchemy'
]
setup(
name=package_name,
version=package_version,
author='Mahdi Ghane.g',
description='sqlalchemy extension for interacting models with python dictionary.',
long_description=open('README.rst').read(),
url='https://github.com/meyt/sqlalchemy-dict',
packages=find_packages(),
install_requires=dependencies,
license='MIT License',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
]
)
|
Extend the container interface from app.
|
<?php namespace Illuminate\Contracts\Foundation;
use Illuminate\Contracts\Container\Container;
interface Application extends Container {
/**
* Register a service provider with the application.
*
* @param \Illuminate\Support\ServiceProvider|string $provider
* @param array $options
* @param bool $force
* @return \Illuminate\Support\ServiceProvider
*/
public function register($provider, $options = array(), $force = false);
/**
* Register a deferred provider and service.
*
* @param string $provider
* @param string $service
* @return void
*/
public function registerDeferredProvider($provider, $service = null);
/**
* Boot the application's service providers.
*
* @return void
*/
public function boot();
/**
* Register a new boot listener.
*
* @param mixed $callback
* @return void
*/
public function booting($callback);
/**
* Register a new "booted" listener.
*
* @param mixed $callback
* @return void
*/
public function booted($callback);
}
|
<?php namespace Illuminate\Contracts\Foundation;
interface Application {
/**
* Register a service provider with the application.
*
* @param \Illuminate\Support\ServiceProvider|string $provider
* @param array $options
* @param bool $force
* @return \Illuminate\Support\ServiceProvider
*/
public function register($provider, $options = array(), $force = false);
/**
* Register a deferred provider and service.
*
* @param string $provider
* @param string $service
* @return void
*/
public function registerDeferredProvider($provider, $service = null);
/**
* Boot the application's service providers.
*
* @return void
*/
public function boot();
/**
* Register a new boot listener.
*
* @param mixed $callback
* @return void
*/
public function booting($callback);
/**
* Register a new "booted" listener.
*
* @param mixed $callback
* @return void
*/
public function booted($callback);
}
|
Correct the expected exception to be EmptyPhpSourceCode
|
<?php
namespace BetterReflectionTest\SourceLocator;
use BetterReflection\Identifier\Identifier;
use BetterReflection\Identifier\IdentifierType;
use BetterReflection\SourceLocator\StringSourceLocator;
use BetterReflection\SourceLocator\Exception\EmptyPhpSourceCode;
/**
* @covers \BetterReflection\SourceLocator\StringSourceLocator
*/
class StringSourceLocatorTest extends \PHPUnit_Framework_TestCase
{
public function testInvokableLoadsSource()
{
$sourceCode = '<?php echo "Hello world!";';
$locator = new StringSourceLocator($sourceCode);
$locatedSource = $locator->__invoke(new Identifier(
'does not matter what the class name is',
new IdentifierType(IdentifierType::IDENTIFIER_CLASS)
));
$this->assertSame($sourceCode, $locatedSource->getSource());
$this->assertNull($locatedSource->getFileName());
}
public function testConstructorThrowsExceptionIfEmptyStringGiven()
{
$this->setExpectedException(EmptyPhpSourceCode::class);
new StringSourceLocator('');
}
}
|
<?php
namespace BetterReflectionTest\SourceLocator;
use BetterReflection\Identifier\Identifier;
use BetterReflection\Identifier\IdentifierType;
use BetterReflection\SourceLocator\StringSourceLocator;
use InvalidArgumentException;
/**
* @covers \BetterReflection\SourceLocator\StringSourceLocator
*/
class StringSourceLocatorTest extends \PHPUnit_Framework_TestCase
{
public function testInvokableLoadsSource()
{
$sourceCode = '<?php echo "Hello world!";';
$locator = new StringSourceLocator($sourceCode);
$locatedSource = $locator->__invoke(new Identifier(
'does not matter what the class name is',
new IdentifierType(IdentifierType::IDENTIFIER_CLASS)
));
$this->assertSame($sourceCode, $locatedSource->getSource());
$this->assertNull($locatedSource->getFileName());
}
public function testConstructorThrowsExceptionIfEmptyStringGiven()
{
$this->setExpectedException(InvalidArgumentException::class);
new StringSourceLocator('');
}
}
|
Add `float` to always convert list
|
/**
* Consider:
*
* .a {
* margin: 0 5px 0 0;
* }
*
* .a {
* margin: 0;
* }
*
* Would be converted to:
*
* html[dir='ltr'] .a {
* margin: 0 5px 0 0;
* }
*
* html[dir='rtl'] .a {
* margin: 0 0 0 5px;
* }
*
* .a {
* margin: 0;
* }
*
* As the "html[dir] .a" will have more specificity,
* "margin: 0" will be ignored. That's why we must
* convert the following properties *always*, regardless
* of the value.
*
*
*/
module.exports = [
'background',
'background-position',
'background-position-x',
'border',
'border-color',
'border-radius',
'border-style',
'border-width',
'border-top',
'border-right',
'border-bottom',
'border-left',
'box-shadow',
'float',
'margin',
'padding',
'text-shadow',
'text-align',
'transform',
'transform-origin'
].join('|');
|
/**
* Consider:
*
* .a {
* margin: 0 5px 0 0;
* }
*
* .a {
* margin: 0;
* }
*
* Would be converted to:
*
* html[dir='ltr'] .a {
* margin: 0 5px 0 0;
* }
*
* html[dir='rtl'] .a {
* margin: 0 0 0 5px;
* }
*
* .a {
* margin: 0;
* }
*
* As the "html[dir] .a" will have more specificity,
* "margin: 0" will be ignored. That's why we must
* convert the following properties *always*, regardless
* of the value.
*
*
*/
module.exports = [
'background',
'background-position',
'background-position-x',
'border',
'border-color',
'border-radius',
'border-style',
'border-width',
'border-top',
'border-right',
'border-bottom',
'border-left',
'box-shadow',
'margin',
'padding',
'text-shadow',
'text-align',
'transform',
'transform-origin'
].join('|');
|
[chore] Add bower.json and package.json to jshint checks
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js', '*.json'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client/lib/dest/libs.min.js': ['client/lib/angular.js', 'client/lib/angular-ui-router.js']
}
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
};
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
options: {
ignores: [
// (TODO: add lib files here)
]
}
},
uglify: {
my_target: {
files: {
'client/lib/dest/libs.min.js': ['client/lib/angular.js', 'client/lib/angular-ui-router.js']
}
}
},
// TODO: add uglify, concat, cssmin tasks
watch: {
files: ['client/app/*.js', 'server/**/*.js', 'database/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
};
|
Update Closure LANGUAGE_IN flag to match tsc's target.
|
/**
* @license
* Copyright (c) 2020 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be
* found at http://polymer.github.io/AUTHORS.txt The complete set of
* contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
* distributed by Google as part of the polymer project is also subject to an
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
const compilerPackage = require('google-closure-compiler');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const closureCompiler = compilerPackage.gulp();
gulp.task('default', () => {
return gulp.src('./src/**/*.js', {base: './'})
.pipe(sourcemaps.init())
.pipe(closureCompiler({
compilation_level: 'ADVANCED',
warning_level: 'VERBOSE',
language_in: 'ECMASCRIPT_2019',
language_out: 'ECMASCRIPT5_STRICT',
dependency_mode: 'STRICT',
entry_point: ['/src/formdata-event'],
js_output_file: 'formdata-event.min.js',
output_wrapper: '(function(){\n%output%\n}).call(self);',
assume_function_wrapper: true,
rewrite_polyfills: false,
}))
.pipe(sourcemaps.write('/'))
.pipe(gulp.dest('./'));
});
|
/**
* @license
* Copyright (c) 2020 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be
* found at http://polymer.github.io/AUTHORS.txt The complete set of
* contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
* distributed by Google as part of the polymer project is also subject to an
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
const compilerPackage = require('google-closure-compiler');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const closureCompiler = compilerPackage.gulp();
gulp.task('default', () => {
return gulp.src('./src/**/*.js', {base: './'})
.pipe(sourcemaps.init())
.pipe(closureCompiler({
compilation_level: 'ADVANCED',
warning_level: 'VERBOSE',
language_in: 'ECMASCRIPT6_STRICT',
language_out: 'ECMASCRIPT5_STRICT',
dependency_mode: 'STRICT',
entry_point: ['/src/formdata-event'],
js_output_file: 'formdata-event.min.js',
output_wrapper: '(function(){\n%output%\n}).call(self);',
assume_function_wrapper: true,
rewrite_polyfills: false,
}))
.pipe(sourcemaps.write('/'))
.pipe(gulp.dest('./'));
});
|
Correct variables, and have it add to number given in get request.
|
<html>
<head>
<title>Number Counter</title>
</head>
<body>
<?php
$date = $_GET['date'];
if (!isset($num)) die("Give me a number boo");
if ($num < 0) die ("Yo, digits are not valid, bro...");
$num = $numend;
echo "<h2>Counting towards ".$num.":"."</h2>";
for ($num=$numend; $numend>=0; $numend++)
{
echo $numend."<br>";
}
print "<br><br>";
echo "<h2>Counting backwards from ".$numend.":"."</h2>";
print "<br>";
for ($num=$numend; $num>=$numstart; $num--)
{
echo $num."<br>";
}
?>
<br>
</body>
</html>
|
<html>
<head>
<title>Number Counter</title>
</head>
<body>
<?php
$date = $_GET['date'];
if (!isset($num)) die("Give me a number boo");
if ($num < 0) die ("Yo, digits are not valid, bro...");
$num = $numend;
echo "<h2>Counting towards ".$date.":"."</h2>";
for ($num=$numend; $numend>=0; $numend++)
{
echo $numend."<br>";
}
print "<br><br>";
echo "<h2>Counting backwards from ".$numend.":"."</h2>";
print "<br>";
for ($num=$numend; $num>=$numstart; $num--)
{
echo $num."<br>";
}
?>
<br>
</body>
</html>
|
Change package name in loadmodule call
Not much reason to do this. It just happened.
|
# -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file_path):
"""
Load problem file as a module.
:param file: The full path to the problem file
returns a module represented by the problem file
"""
# Create a new module to hold the seed variable so
# the loaded module can reference the seed variable
if sys.version_info[0] == 2:
import imp
problem_module = imp.load_source('prob_mod_pkg',file_path)
if sys.version_info[0] == 3:
import importlib.machinery
problem_module = importlib.machinery \
.SourceFileLoader('prob_mod_pkg',file_path) \
.load_module()
try:
problem_module.answers
except AttributeError:
raise AttributeError('Problem file has no \'answers\' attribute')
return problem_module
|
# -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file):
"""
Load problem file as a module.
:param file: The full path to the problem file
returns a module represented by the problem file
"""
# Create a new module to hold the seed variable so
# the loaded module can reference the seed variable
if sys.version_info[0] == 2:
import imp
problem_module = imp.load_source('prob_module',file)
if sys.version_info[0] == 3:
import importlib.machinery
problem_module = importlib.machinery \
.SourceFileLoader("prob_module",file) \
.load_module()
try:
problem_module.answers
except AttributeError:
raise AttributeError('Problem file has no \'answers\' attribute')
return problem_module
|
Add 'reverse' argument to get_enum_as_dict.
|
# Copyright 2013 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'get_enum_as_dict'
]
def get_enum_as_dict(cls, reverse=False, friendly_names=False):
"""
Convert an "enum" class to a dict key is the enum name and value is an enum
value.
"""
result = {}
for key, value in cls.__dict__.items():
if key.startswith('__'):
continue
if key[0] != key[0].upper():
continue
name = key
if friendly_names:
name = name.replace('_', ' ').lower().title()
if reverse:
result[value] = name
else:
result[name] = value
return result
|
# Copyright 2013 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
'get_enum_as_dict'
]
def get_enum_as_dict(cls, friendly_names=False):
"""
Convert an "enum" class to a dict key is the enum name and value is an enum
value.
"""
result = {}
for key, value in cls.__dict__.items():
if key.startswith('__'):
continue
if key[0] != key[0].upper():
continue
name = key
if friendly_names:
name = name.replace('_', ' ').lower().title()
result[name] = value
return result
|
Add autofocus to login form
|
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>SSBO Ticketing - Login</title>
<meta name="description" content="SSBO Ticketing System Login" />
<meta name="author" content="Marius Runde" />
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.png" />
</head>
<body>
<header>
<h1>SSBO Ticketing - Login</h1>
</header>
<form name="control_form" action="index.php" method="post">
<input name="user" type="text" value="" placeholder="Nutzername eingeben..." autofocus /><br/>
<input name="pass" type="password" value="" placeholder="Passwort eingeben..." /><br/>
<button type="submit">Anmelden</button>
</form>
<footer>
<p>
© Copyright 2014 by Marius Runde
</p>
</footer>
</body>
</html>
|
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>SSBO Ticketing - Login</title>
<meta name="description" content="SSBO Ticketing System Login" />
<meta name="author" content="Marius Runde" />
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.png" />
</head>
<body>
<header>
<h1>SSBO Ticketing - Login</h1>
</header>
<form name="control_form" action="index.php" method="post">
<input name="user" type="text" value="" placeholder="Nutzername eingeben..." /><br/>
<input name="pass" type="password" value="" placeholder="Passwort eingeben..." /><br/>
<button type="submit">Anmelden</button>
</form>
<footer>
<p>
© Copyright 2014 by Marius Runde
</p>
</footer>
</body>
</html>
|
Add text for mobile devices
|
import React, {PropTypes} from 'react';
import LeftSidebar from "./views/leftsidebar/LeftSidebar";
import {appComponents} from "./ConfigMap";
import AppController from "./controller/AppController";
class App extends React.Component {
render(){
return (
<div className="app-wrapper ">
<div className="row visible-lg-block">
<div className="row full-height">
<div className="col-lg-3 leftsidebar ">
<LeftSidebar config={appComponents.leftSideBarComponent} />
</div>
<div className="col-lg-9 full-height view-container ">
<div className="container-fluid ">
{this.props.children}
</div>
</div>
</div>
</div>
<div className="row hidden-lg">
<div className="col-lg-12">
<div className="jumbotron text-center">
Apologies. <br />The App isnt Mobile or Tablet Friendly as of now!<br />
We are in progress to make it work on the same. <br / >
Please use Laptop or a Desktop device to use the Story Generator
</div>
</div>
</div>
</div>
);
}
}
App.propTypes = {
children: PropTypes.object.isRequired
};
export default App;
|
import React, {PropTypes} from 'react';
import LeftSidebar from "./views/leftsidebar/LeftSidebar";
import {appComponents} from "./ConfigMap";
import AppController from "./controller/AppController";
class App extends React.Component {
render(){
return (
<div className="app-wrapper ">
<div className="row full-height">
<div className="col-lg-3 leftsidebar ">
<LeftSidebar config={appComponents.leftSideBarComponent} />
</div>
<div className="col-lg-9 full-height view-container ">
<div className="container-fluid ">
{this.props.children}
</div>
</div>
</div>
</div>
);
}
}
App.propTypes = {
children: PropTypes.object.isRequired
};
export default App;
|
Refactor to use shorthand req res
|
var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
res.send( sessions );
})
},
addSession: function( req, res, next ) {
var sessionName = req.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
res.status = 201;
res.end();
} )
},
getSessionByName: function( req, res, next ) {
var sessionName = req.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
res.json( session );
}, function( err ) {
helpers.errorHandler( err, req, res, next );
});
}
};
|
var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
response.send( sessions );
})
},
addSession: function( req, res, next ) {
var sessionName = request.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
response.status = 201;
response.end();
} )
},
getSessionByName: function( req, res, next ) {
var sessionName = request.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
response.json( session );
}, function( err ) {
helpers.errorHandler( err, request, response, next );
});
}
};
|
views: Use url_for for base redirection
|
from flask import redirect, url_for
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notifications import notifications_blueprint
from skylines.views.ranking import ranking_blueprint
from skylines.views.statistics import statistics_blueprint
from skylines.views.upload import upload_blueprint
from skylines.views.users import users_blueprint
app.register_blueprint(about_blueprint, url_prefix='/about')
app.register_blueprint(api_blueprint, url_prefix='/api')
app.register_blueprint(flights_blueprint, url_prefix='/flights')
app.register_blueprint(notifications_blueprint, url_prefix='/notifications')
app.register_blueprint(ranking_blueprint, url_prefix='/ranking')
app.register_blueprint(statistics_blueprint, url_prefix='/statistics')
app.register_blueprint(upload_blueprint, url_prefix='/flights/upload')
app.register_blueprint(users_blueprint, url_prefix='/users')
@app.route('/')
def index():
return redirect(url_for('flights.latest'))
|
from flask import redirect
from skylines import app
import skylines.views.i18n
import skylines.views.login
import skylines.views.search
from skylines.views.about import about_blueprint
from skylines.views.api import api_blueprint
from skylines.views.flights import flights_blueprint
from skylines.views.notifications import notifications_blueprint
from skylines.views.ranking import ranking_blueprint
from skylines.views.statistics import statistics_blueprint
from skylines.views.upload import upload_blueprint
from skylines.views.users import users_blueprint
app.register_blueprint(about_blueprint, url_prefix='/about')
app.register_blueprint(api_blueprint, url_prefix='/api')
app.register_blueprint(flights_blueprint, url_prefix='/flights')
app.register_blueprint(notifications_blueprint, url_prefix='/notifications')
app.register_blueprint(ranking_blueprint, url_prefix='/ranking')
app.register_blueprint(statistics_blueprint, url_prefix='/statistics')
app.register_blueprint(upload_blueprint, url_prefix='/flights/upload')
app.register_blueprint(users_blueprint, url_prefix='/users')
@app.route('/')
def index():
return redirect('/flights/latest')
|
Use ioutil.ReadFile instead of os.Openfile with O_CREATE.
No need to create an empty file if meta data key is not found.
|
package plugin
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
type metaDataStore struct {
dir string
installTarget *installTarget
}
var errDisaleMetaDataStore = errors.New("MetaData disabled. could not detect owner/repo")
func newMetaDataStore(pluginDir string, target *installTarget) (*metaDataStore, error) {
owner, repo, err := target.getOwnerAndRepo()
if err != nil {
return nil, errDisaleMetaDataStore
}
dir := filepath.Join(pluginDir, "meta", owner, repo)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
return &metaDataStore{
dir: dir,
installTarget: target,
}, nil
}
func (m *metaDataStore) load(key string) (string, error) {
b, err := ioutil.ReadFile(filepath.Join(m.dir, key))
if os.IsNotExist(err) {
return "", nil
} else if err != nil {
return "", err
}
return string(b), nil
}
func (m *metaDataStore) store(key, value string) error {
return ioutil.WriteFile(
filepath.Join(m.dir, key),
[]byte(value),
0644,
)
}
|
package plugin
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
type metaDataStore struct {
dir string
installTarget *installTarget
}
var errDisaleMetaDataStore = errors.New("MetaData disabled. could not detect owner/repo")
func newMetaDataStore(pluginDir string, target *installTarget) (*metaDataStore, error) {
owner, repo, err := target.getOwnerAndRepo()
if err != nil {
return nil, errDisaleMetaDataStore
}
dir := filepath.Join(pluginDir, "meta", owner, repo)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
return &metaDataStore{
dir: dir,
installTarget: target,
}, nil
}
func (m *metaDataStore) load(key string) (string, error) {
f, err := os.OpenFile(
filepath.Join(m.dir, key),
os.O_RDONLY|os.O_CREATE,
0644,
)
if err != nil {
return "", err
}
defer f.Close()
b, err := ioutil.ReadAll(f)
return string(b), err
}
func (m *metaDataStore) store(key, value string) error {
return ioutil.WriteFile(
filepath.Join(m.dir, key),
[]byte(value),
0644,
)
}
|
Fix printf format bug: use %v for structs
|
package translator
import (
"github.com/Shopify/go-lua"
"github.com/fsouza/go-dockerclient"
"reflect"
"testing"
)
func TestUnknownPropertiesConfig(t *testing.T) {
source := `x = {blah = 5}`
expected := docker.Config{}
state := lua.NewState()
if err := lua.DoString(state, source); err != nil {
t.Errorf("Error executing string: %s", err)
}
state.Global("x")
if actual := ParseImageConfigFromLuaTable(state); !reflect.DeepEqual(actual, expected) {
t.Errorf("Wasn't unchanged: %v != %v", actual, expected)
}
}
func TestUnknownPropertiesHostConfig(t *testing.T) {
source := `x = {blah = 5}`
expected := docker.HostConfig{}
state := lua.NewState()
if err := lua.DoString(state, source); err != nil {
t.Errorf("Error executing string: %s", err)
}
state.Global("x")
if actual := ParseHostConfigFromLuaTable(state); !reflect.DeepEqual(actual, expected) {
t.Errorf("Wasn't unchanged: %v != %v", actual, expected)
}
}
|
package translator
import (
"github.com/Shopify/go-lua"
"github.com/fsouza/go-dockerclient"
"reflect"
"testing"
)
func TestUnknownPropertiesConfig(t *testing.T) {
source := `x = {blah = 5}`
expected := docker.Config{}
state := lua.NewState()
if err := lua.DoString(state, source); err != nil {
t.Errorf("Error executing string: %s", err)
}
state.Global("x")
if actual := ParseImageConfigFromLuaTable(state); !reflect.DeepEqual(actual, expected) {
t.Errorf("Wasn't unchanged: %s != %s", actual, expected)
}
}
func TestUnknownPropertiesHostConfig(t *testing.T) {
source := `x = {blah = 5}`
expected := docker.HostConfig{}
state := lua.NewState()
if err := lua.DoString(state, source); err != nil {
t.Errorf("Error executing string: %s", err)
}
state.Global("x")
if actual := ParseHostConfigFromLuaTable(state); !reflect.DeepEqual(actual, expected) {
t.Errorf("Wasn't unchanged: %s != %s", actual, expected)
}
}
|
Append HISTORY to long description on PyPI
|
from setuptools import setup
def fread(fn):
return open(fn, 'rb').read().decode('utf-8')
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=fread('README.rst') + '\n\n' + fread('HISTORY.rst'),
author='Ryan Hiebert',
author_email='ryan@ryanhiebert.com',
url='https://github.com/ryanhiebert/tox-travis',
license='MIT',
version='0.1',
py_modules=['tox_travis'],
entry_points={
'tox': ['travis = tox_travis'],
},
install_requires=['tox>=2.0'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
from setuptools import setup
setup(
name='tox-travis',
description='Seamless integration of Tox into Travis CI',
long_description=open('README.rst', 'rb').read().decode('utf-8'),
author='Ryan Hiebert',
author_email='ryan@ryanhiebert.com',
url='https://github.com/ryanhiebert/tox-travis',
license='MIT',
version='0.1',
py_modules=['tox_travis'],
entry_points={
'tox': ['travis = tox_travis'],
},
install_requires=['tox>=2.0'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Update control alignment (was relying in platform-specific margins)
|
// Hello page
//
exports.View =
{
title: "Hello World",
elements:
[
{ control: "text", value: "Enter your name:", font: { size: 12, bold: true } },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "First name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
{ control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "firstName" },
] },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "Last name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
{ control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "lastName" },
] },
{ control: "text", value: "Hello {firstName} {lastName}", fontsize: 12 },
]
}
exports.InitializeViewModel = function(context, session)
{
var viewModel =
{
firstName: "Planet",
lastName: "Earth",
}
return viewModel;
}
|
// Hello page
//
exports.View =
{
title: "Hello World",
elements:
[
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "First name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
{ control: "edit", fontsize: 12, width: 200, binding: "firstName" },
] },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "Last name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
{ control: "edit", fontsize: 12, width: 200, binding: "lastName" },
] },
{ control: "text", value: "Hello {firstName} {lastName}", fontsize: 12 },
]
}
exports.InitializeViewModel = function(context, session)
{
var viewModel =
{
firstName: "Planet",
lastName: "Earth",
}
return viewModel;
}
|
[lite] Update benchmark app to try to load flex first if available to support the case when we build the flex version.
PiperOrigin-RevId: 370787699
Change-Id: I6fb52db0c50a3a2fafb7d698960f6ae57cdce8df
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.lite.benchmark;
/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
static {
// Try loading flex first if available. If not load regular tflite shared library.
try {
System.loadLibrary("tensorflowlite_benchmark_plus_flex");
} catch (UnsatisfiedLinkError e) {
System.loadLibrary("tensorflowlite_benchmark");
}
}
// Executes a standard TensorFlow Lite benchmark according to the provided args.
//
// Note that {@code args} will be split by the native execution code.
public static void run(String args) {
nativeRun(args);
}
private static native void nativeRun(String args);
}
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.lite.benchmark;
/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
static {
System.loadLibrary("tensorflowlite_benchmark");
}
// Executes a standard TensorFlow Lite benchmark according to the provided args.
//
// Note that {@code args} will be split by the native execution code.
public static void run(String args) {
nativeRun(args);
}
private static native void nativeRun(String args);
}
|
Fix types in util tests
|
// Copyright 2016 Albert Nigmatzianov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package util
import (
"bytes"
"testing"
)
var (
sizeInt int = 15351
sizeBytes = []byte{0, 0, 0x77, 0x77}
)
func TestParseSize(t *testing.T) {
size, err := ParseSize(sizeBytes)
if err != nil {
t.Error(err)
}
if size != int64(sizeInt) {
t.Errorf("Expected: %v, got: %v", sizeInt, size)
}
}
func TestFormSize(t *testing.T) {
size, err := FormSize(sizeInt)
if err != nil {
t.Error(err)
}
if !bytes.Equal(sizeBytes, size) {
t.Errorf("Expected: %v, got: %v", sizeBytes, size)
}
}
|
// Copyright 2016 Albert Nigmatzianov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package util
import (
"bytes"
"testing"
)
var (
sizeInt int64 = 15351
sizeBytes = []byte{0, 0, 0x77, 0x77}
)
func TestParseSize(t *testing.T) {
size, err := ParseSize(sizeBytes)
if err != nil {
t.Error(err)
}
if size != sizeInt {
t.Errorf("Expected: %v, got: %v", sizeInt, size)
}
}
func TestFormSize(t *testing.T) {
size, err := FormSize(sizeInt)
if err != nil {
t.Error(err)
}
if !bytes.Equal(sizeBytes, size) {
t.Errorf("Expected: %v, got: %v", sizeBytes, size)
}
}
|
Send stream responses to the OutputStream, to handle binary formats
|
/**
* Copyright 2008 Matthew Hillsdon
*
* 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 net.hillsdon.reviki.web.handlers;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import net.hillsdon.reviki.web.common.View;
/**
* Render a stream with a given content type.
*
* @author msw
*/
public class StreamView implements View {
private final String _mimeType;
private final InputStream _contents;
/**
* @param mimeType The content type of the page (eg, "application/xml").
* @param contents Source of the response body.
*/
public StreamView(final String mimeType, final InputStream contents) {
_mimeType = mimeType;
_contents = contents;
}
public void render(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
response.setContentType(_mimeType);
IOUtils.copy(_contents, response.getOutputStream());
}
}
|
/**
* Copyright 2008 Matthew Hillsdon
*
* 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 net.hillsdon.reviki.web.handlers;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import net.hillsdon.reviki.web.common.View;
/**
* Render a stream with a given content type.
*
* @author msw
*/
public class StreamView implements View {
private final String _mimeType;
private final InputStream _contents;
/**
* @param mimeType The content type of the page (eg, "application/xml").
* @param contents Source of the response body.
*/
public StreamView(final String mimeType, final InputStream contents) {
_mimeType = mimeType;
_contents = contents;
}
public void render(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
response.setContentType(_mimeType);
IOUtils.copy(_contents, response.getWriter());
}
}
|
Change to [ and ]
|
var shouldAddEventListener;
// define a handler
function doc_keyUp(e) {
// this would test if keyCode 219 ([) or keyCode 221 (]) was pressed
if (e.keyCode == 219) {
console.log("Keyboard for like triggered.");
document.querySelector("#top-level-buttons > ytd-toggle-button-renderer:nth-child(1) > a").click();
} else if (e.keyCode == 221) {
console.log("Keyboard for dislike triggered.");
document.querySelector("#top-level-buttons > ytd-toggle-button-renderer:nth-child(2) > a").click();
}
}
// register the handler
if ((shouldAddEventListener == null ? true : shouldAddEventListener)) {
shouldAddEventListener = false;
console.log("Adding YouTube like keyboard shortcut event listener...")
document.addEventListener('keyup', doc_keyUp, false);
}
|
var shouldAddEventListener;
// define a handler
function doc_keyUp(e) {
// this would test if keyCode 85 (u) or keyCode 73 (i) was pressed
if (e.keyCode == 85) {
console.log("Keyboard for like triggered.");
document.querySelector("#top-level-buttons > ytd-toggle-button-renderer:nth-child(1) > a").click();
} else if (e.keyCode == 73) {
console.log("Keyboard for dislike triggered.");
document.querySelector("#top-level-buttons > ytd-toggle-button-renderer:nth-child(2) > a").click();
}
}
// register the handler
if ((shouldAddEventListener == null ? true : shouldAddEventListener)) {
shouldAddEventListener = false;
console.log("Adding YouTube like keyboard shortcut event listener...")
document.addEventListener('keyup', doc_keyUp, false);
}
|
Update loadConfig to allow duplicates
|
/* jshint node:true */
'use strict';
module.exports = function (grunt) {
var config = {
pkg: grunt.file.readJSON('package.json'),
srcDir: 'src',
destDir: 'dist',
tempDir: 'tmp',
};
// load plugins
require('load-grunt-tasks')(grunt);
// load task definitions
grunt.loadTasks('tasks');
// Utility function to load plugin settings into config
function loadConfig(config,path) {
require('glob').sync('*', {cwd: path}).forEach(function(option) {
var key = option.replace(/\.js$/,'');
// If key already exists, extend it. It is your responsibility to avoid naming collisions
config[key] = config[key] || {};
grunt.util._.extend(config[key], require(path + option)(config));
});
// technically not required
return config;
}
// Merge that object with what with whatever we have here
loadConfig(config,'./tasks/options/');
// pass the config to grunt
grunt.initConfig(config);
};
|
/* jshint node:true */
'use strict';
module.exports = function (grunt) {
var config = {
pkg: grunt.file.readJSON('package.json'),
srcDir: 'src',
destDir: 'dist',
tempDir: 'tmp',
};
// load plugins
require('load-grunt-tasks')(grunt);
// load task definitions
grunt.loadTasks('tasks');
// Utility function to load plugin configurations into an object
function loadConfig(path) {
var object = {};
require('glob').sync('*', {cwd: path}).forEach(function(option) {
object[option.replace(/\.js$/,'')] = require(path + option)(config);
});
return object;
}
// Merge that object with what with whatever we have here
grunt.util._.extend(config, loadConfig('./tasks/options/'));
// pass the config to grunt
grunt.initConfig(config);
};
|
Correct the view of capturist dashboard
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exists for the current user (capturist).
"""
user_id = request.user.id
estudios = Estudio.objects.filter(status=Estudio.RECHAZADO, capturista_id=user_id)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the button to add a new socio-economic study.
Also shows the edit and see feedback buttons to each socio-economic study
shown in the list if this exists for the current user (capturist).
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
Improve comment abotu Tachyons in counter-clodable-styled.js
|
// This is a modification of the previous example which adds some styling using the Tachyons CSS library.
// Tachyons predefines many classes which do common CSS tasks.
// You can add these classes to your div using the Mithril ".cssClass" notation after the HTML tag name.
// If there is no leading tag name before the CSS classes, Mithril assumes it is a "div".
// You can click on the Tachyons.css link near the top of this page later to learn more about Tachyons.
// The "Tachyons" part of the link goesto the Tachyons website to get an overview of what is possible.
// The ".css" part of the link goes to the the CSS source file for Tachyons where you can look up class names.
// Using Tachyons plus occasional inline styles makes it possible to do styled UIs with only JavaScript coding.
var div = document.createElement("div")
var state = {
count: 0,
inc: function() {state.count++}
}
var Counter = {
view: function() {
return m("div.ba.ma3.pa3.bg-light-purple",
m("button.fr", {onclick: function () { m.mount(div, null); document.body.removeChild(div) } }, "X"),
m("div.ma2.f3", {onclick: state.inc}, state.count)
)
}
}
document.body.appendChild(div)
m.mount(div, Counter)
|
// This is a modification of the previous example which adds some styling using the Tachyons CSS library.
// Tachyons predefines many classes which do common CSS tasks.
// You can add these classes to your div using the Mithril ".cssClass" notation after the HTML tag name.
// If there is no leading tag name before the CSS classes, Mithril assumes it is a "div".
// You can click on the Tachyons.js link near the top of this page later to learn more about Tachyons.
var div = document.createElement("div")
var state = {
count: 0,
inc: function() {state.count++}
}
var Counter = {
view: function() {
return m("div.ba.ma3.pa3.bg-light-purple",
m("button.fr", {onclick: function () { m.mount(div, null); document.body.removeChild(div) } }, "X"),
m("div.ma2.f3", {onclick: state.inc}, state.count)
)
}
}
document.body.appendChild(div)
m.mount(div, Counter)
|
Prepare for next dev cycle
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.16.dev",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.15",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
|
Fix implementation for SpiderMonkey (firefox)
|
function render(world) {
var rendering = '';
for (var y = world.boundaries()['y']['min']; y <= world.boundaries()['y']['max']; y++) {
for (var x = world.boundaries()['x']['min']; x <= world.boundaries()['x']['max']; x++) {
var cell = world.cell_at(x, y);
rendering += (cell ? cell.to_char() : ' ').replace(' ', ' ');
}
rendering += "<br />"
}
return rendering;
}
$(document).ready(function() {
var world = new World;
for (var x = 0; x <= 150; x++) {
for (var y = 0; y <= 40; y++) {
world.add_cell(x, y, (Math.random() > 0.2));
}
}
var body = $('body');
body.html(render(world));
setInterval(function() {
var tick_start = new Date();
world._tick();
var tick_finish = new Date();
var tick_time = ((tick_finish-tick_start)/1000).toFixed(3);
var render_start = new Date();
var rendered = render(world);
var render_finish = new Date();
var render_time = ((render_finish-render_start)/1000).toFixed(3);
var output = "#"+world.tick;
output += " - World tick took "+tick_time;
output += " - Rendering took "+render_time;
output += "<br />"+rendered;
body.html(output);
}, 0);
});
|
function render(world) {
var rendering = '';
for (var y = world.boundaries()['y']['min']; y <= world.boundaries()['y']['max']; y++) {
for (var x = world.boundaries()['x']['min']; x <= world.boundaries()['x']['max']; x++) {
var cell = world.cell_at(x, y);
rendering += (cell ? cell.to_char() : ' ').replace(' ', ' ');
}
rendering += "<br />"
}
return rendering;
}
$(document).ready(function() {
var world = new World;
for (var x = 0; x <= 150; x++) {
for (var y = 0; y <= 40; y++) {
world.add_cell(x, y, (Math.random() > 0.2));
}
}
var body = $('body');
body.html(render(world));
setInterval(function() {
var tick_start = new Date();
world._tick();
var tick_finish = new Date();
var tick_time = ((tick_finish-tick_start)/1000).toFixed(3);
var render_start = new Date();
var rendered = render(world);
var render_finish = new Date();
var render_time = ((render_finish-render_start)/1000).toFixed(3);
var output = "#"+world.tick;
output += " - World tick took "+tick_time;
output += " - Rendering took "+render_time;
output += "<br />"+rendered;
body.html(output);
});
});
|
Remove dots from generic types
|
const DocumentedItem = require('./item');
class DocumentedVarType extends DocumentedItem {
registerMetaInfo(data) {
this.directData = data;
}
serialize() {
const names = [];
for(const name of this.directData.names) names.push(this.constructor.splitVarName(name));
if(!this.directData.description && !this.directData.nullable) return names;
return {
types: names,
description: this.directData.description,
nullable: this.directData.nullable
};
}
static splitVarName(str) {
if(str === '*') return ['*'];
str = str.replace(/\./g, '');
const matches = str.match(/([\w*]+)([^\w*]+)/g);
const output = [];
if(matches) {
for(const match of matches) {
const groups = match.match(/([\w*]+)([^\w*]+)/);
output.push([groups[1], groups[2]]);
}
} else {
output.push([str.match(/([\w*]+)/g)[0]]);
}
return output;
}
}
/*
{
"names":[
"String"
]
}
*/
module.exports = DocumentedVarType;
|
const DocumentedItem = require('./item');
class DocumentedVarType extends DocumentedItem {
registerMetaInfo(data) {
this.directData = data;
}
serialize() {
const names = [];
for(const name of this.directData.names) names.push(this.constructor.splitVarName(name));
if(!this.directData.description && !this.directData.nullable) return names;
return {
types: names,
description: this.directData.description,
nullable: this.directData.nullable
};
}
static splitVarName(str) {
if(str === '*') return ['*'];
const matches = str.match(/([\w*]+)([^\w*]+)/g);
const output = [];
if(matches) {
for(const match of matches) {
const groups = match.match(/([\w*]+)([^\w*]+)/);
output.push([groups[1], groups[2]]);
}
} else {
output.push([str.match(/([\w*]+)/g)[0]]);
}
return output;
}
}
/*
{
"names":[
"String"
]
}
*/
module.exports = DocumentedVarType;
|
Fix docs and label and use more intuitive function name
|
'use strict';
/*!
* Dependencies
*/
var debug = require('debug')('ooyala:closedCaptions')
/**
* Upload Closed Caption file for video asset
*
* @param {String} asset id
* @param {Buffer} caption file contents
* @return {Promise} promise
*/
exports.uploadVideoClosedCaptions = function(id, file) {
var rej = (
this.validate(id, 'String', 'id')
|| this.validate(file, 'Uint8Array', 'file')
)
if (rej) return rej
debug('[uploadVideoClosedCaptions] id=`%s`', id)
return this
.put({
route: `/v2/assets/${id}/closed_captions`
, options: {
body: file
}
})
.then(function(resp) {
debug('[uploadVideoClosedCaptions] done: id=`%s` resp=`%j`', id, resp.body)
return resp.body
})
}
|
'use strict';
/*!
* Dependencies
*/
var debug = require('debug')('ooyala:thumbnails')
/**
* TODO: There is a size limit on what can be sent, no idea what that limit
* actually is. If found, add it here for validation
*
* Upload thumbnail image as the custom image for the video.
* This does not automatically set the video to use this image
* though, must call the `setVideoToUploadedThumbnail` method
*
* @param {String} asset id
* @param {Buffer} caption file contents
* @return {Promise} promise
*/
exports.uploadVideoCCFile = function(id, file) {
var rej = (
this.validate(id, 'String', 'id')
|| this.validate(file, 'Uint8Array', 'file')
)
if (rej) return rej
debug('[uploadVideoCCFile] id=`%s`', id)
return this
.put({
route: `/v2/assets/${id}/closed_captions`
, options: {
body: file
}
})
.then(function(resp) {
debug('[uploadVideoCCFile] done: id=`%s` resp=`%j`', id, resp.body)
return resp.body
})
}
|
Fix date range in worklog_period
|
from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1900, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
|
from datetime import date
from django.db.models import Max, Min
def worklog_period(obj):
activity_period = obj.worklogentries.aggregate(Max('date'), Min('date'))
article_period = obj.articleentries.aggregate(Max('date'), Min('date'))
min_date = date(1, 1, 1)
max_date = date(3000, 1, 1)
if not (activity_period['date__min'] or article_period['date__min']):
return (min_date, max_date)
start = min(activity_period['date__min'] or max_date, article_period['date__min'] or max_date)
end = max(activity_period['date__max'] or min_date, article_period['date__max'] or min_date)
return (start, end)
def worklog_period_string(obj):
start, end = worklog_period(obj)
return u'%s - %s' % (start.strftime('%d.%m.%Y'), end.strftime('%d.%m.%Y'))
|
Fix function names being lost in binding
|
'use strict';
const { reduceAsync, identity } = require('../utilities');
const { rpcHandlers } = require('../rpc');
// Reducer function that takes the schema as input and output,
// and iterate over rpc-specific reduce functions
const rpcReducer = function ({ schema, processors, postProcess = identity }) {
return reduceAsync(
processors,
(schemaA, func) => func(schemaA),
schema,
(schemaA, schemaB) => postProcess({ ...schemaA, ...schemaB }),
);
};
// Apply rpc-specific compile-time logic
const rpcSchema = function ({ schema }) {
const processors = getProcessors({ name: 'compileSchema' });
return rpcReducer({ schema, processors });
};
// Apply rpc-specific startup logic
const rpcStartServer = function ({ schema }) {
const processors = getProcessors({ name: 'startServer' });
return rpcReducer({ schema, processors, postProcess: rpcStartServerProcess });
};
const getProcessors = function ({ name }) {
return Object.values(rpcHandlers)
.map(rpcHandler => rpcHandler[name])
.filter(handler => handler);
};
const rpcStartServerProcess = schema => ({ schema });
module.exports = {
rpcSchema,
rpcStartServer,
};
|
'use strict';
const { reduceAsync, identity } = require('../utilities');
const { rpcHandlers } = require('../rpc');
// Returns a reducer function that takes the schema as input and output,
// and iterate over rpc-specific reduce functions
const getRpcReducer = function (name, postProcess) {
const processors = getProcessors({ name });
return rpcReducer.bind(null, { processors, postProcess });
};
const getProcessors = function ({ name }) {
return Object.values(rpcHandlers)
.map(rpcHandler => rpcHandler[name])
.filter(handler => handler);
};
const rpcReducer = function (
{ processors, postProcess = identity },
{ schema },
) {
return reduceAsync(
processors,
(schemaA, func) => func(schemaA),
schema,
(schemaA, schemaB) => postProcess({ ...schemaA, ...schemaB }),
);
};
// Apply rpc-specific compile-time logic
const rpcSchema = getRpcReducer('compileSchema');
// Apply rpc-specific startup logic
const rpcStartServer = getRpcReducer('startServer', schema => ({ schema }));
module.exports = {
rpcSchema,
rpcStartServer,
};
|
Load test Randomizer lazily to avoid confliction in prod runtime.
|
package cfvbaibai.cardfantasy.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cfvbaibai.cardfantasy.Randomizer;
import cfvbaibai.cardfantasy.StaticRandomizer;
import cfvbaibai.cardfantasy.engine.GameEngine;
import cfvbaibai.cardfantasy.game.DeckBuilder;
import cfvbaibai.cardfantasy.game.DeckStartupInfo;
@RunWith(Suite.class)
@SuiteClasses({
RacialBufferTest.class, AttackBuffTest.class, SpecialStatusTest.class,
DelayTest.class
})
public class FeatureValidationTests {
public static FeatureTestContext prepare(int playerALevel, int playerBLevel, String ... cards) {
GameEngine engine = TestGameBuilder.buildEmptyGameForTest(50, 50);
DeckStartupInfo dsi = DeckBuilder.build(cards);
FeatureTestContext context = new FeatureTestContext();
context.setEngine(engine);
context.setDsi(dsi);
return context;
}
private static StaticRandomizer random;
public static StaticRandomizer getRandom() {
if (random == null) {
random = new StaticRandomizer();
Randomizer.registerRandomizer(random);
}
return random;
}
}
|
package cfvbaibai.cardfantasy.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import cfvbaibai.cardfantasy.Randomizer;
import cfvbaibai.cardfantasy.StaticRandomizer;
import cfvbaibai.cardfantasy.engine.GameEngine;
import cfvbaibai.cardfantasy.game.DeckBuilder;
import cfvbaibai.cardfantasy.game.DeckStartupInfo;
@RunWith(Suite.class)
@SuiteClasses({
RacialBufferTest.class, AttackBuffTest.class, SpecialStatusTest.class,
DelayTest.class
})
public class FeatureValidationTests {
public static FeatureTestContext prepare(int playerALevel, int playerBLevel, String ... cards) {
GameEngine engine = TestGameBuilder.buildEmptyGameForTest(50, 50);
DeckStartupInfo dsi = DeckBuilder.build(cards);
FeatureTestContext context = new FeatureTestContext();
context.setEngine(engine);
context.setDsi(dsi);
return context;
}
private static StaticRandomizer random;
public static StaticRandomizer getRandom() {
return random;
}
static {
random = new StaticRandomizer();
Randomizer.registerRandomizer(random);
}
}
|
Fix pretty print not ignoring shardID
|
const pino = require('pino')
const serializers = require('./serializers.js')
const getConfig = require('../../config.js').get
function createLogger (shardID) {
const config = getConfig()
const prettyPrint = {
translateTime: 'yyyy-mm-dd HH:MM:ss',
messageFormat: '[{shardID}] \x1b[0m{msg}',
ignore: 'hostname,shardID'
}
const pinoConfig = {
base: {
shardID: String(shardID)
},
customLevels: {
owner: 35
},
prettyPrint,
serializers: {
guild: serializers.guild,
channel: serializers.channel,
role: serializers.channel,
user: serializers.user,
message: serializers.message,
error: pino.stdSerializers.err
},
enabled: process.env.NODE_ENV !== 'test'
}
let destination
if (pinoConfig.enabled) {
destination = config.log.destination || undefined
pinoConfig.level = config.log.level
pinoConfig.prettyPrint = !destination ? prettyPrint : false
}
return pino(pinoConfig, pino.destination(destination))
}
module.exports = createLogger
|
const pino = require('pino')
const serializers = require('./serializers.js')
const getConfig = require('../../config.js').get
function createLogger (shardID) {
const config = getConfig()
const prettyPrint = {
translateTime: 'yyyy-mm-dd HH:MM:ss',
messageFormat: '[{shardID}] \x1b[0m{msg}',
ignore: 'hostname,shardID'
}
const pinoConfig = {
base: {
shardID: String(shardID)
},
customLevels: {
owner: 35
},
prettyPrint,
serializers: {
guild: serializers.guild,
channel: serializers.channel,
role: serializers.channel,
user: serializers.user,
message: serializers.message,
error: pino.stdSerializers.err
},
enabled: process.env.NODE_ENV !== 'test'
}
let destination
if (pinoConfig.enabled) {
destination = config.log.destination || undefined
pinoConfig.level = config.log.level
pinoConfig.prettyPrint = !destination
}
return pino(pinoConfig, pino.destination(destination))
}
module.exports = createLogger
|
Fix CS regarding nullable arguments
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Extractor;
use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
/**
* @author David Maicher <mail@dmaicher.de>
*
* @experimental in 4.3
*/
final class ObjectPropertyListExtractor implements ObjectPropertyListExtractorInterface
{
private $propertyListExtractor;
private $objectClassResolver;
public function __construct(PropertyListExtractorInterface $propertyListExtractor, callable $objectClassResolver = null)
{
$this->propertyListExtractor = $propertyListExtractor;
$this->objectClassResolver = $objectClassResolver;
}
/**
* {@inheritdoc}
*/
public function getProperties($object, array $context = []): ?array
{
$class = $this->objectClassResolver ? ($this->objectClassResolver)($object) : \get_class($object);
return $this->propertyListExtractor->getProperties($class, $context);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Extractor;
use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
/**
* @author David Maicher <mail@dmaicher.de>
*
* @experimental in 4.3
*/
final class ObjectPropertyListExtractor implements ObjectPropertyListExtractorInterface
{
private $propertyListExtractor;
private $objectClassResolver;
public function __construct(PropertyListExtractorInterface $propertyListExtractor, ?callable $objectClassResolver = null)
{
$this->propertyListExtractor = $propertyListExtractor;
$this->objectClassResolver = $objectClassResolver;
}
/**
* {@inheritdoc}
*/
public function getProperties($object, array $context = []): ?array
{
$class = $this->objectClassResolver ? ($this->objectClassResolver)($object) : \get_class($object);
return $this->propertyListExtractor->getProperties($class, $context);
}
}
|
Patch by Russel Owen: if we have command line arguments zap pyc files
in the directories given.
|
#!/usr/local/bin/python
"""Recursively zap all .pyc files"""
import os
import sys
# set doit true to actually delete files
# set doit false to just print what would be deleted
doit = 1
def main():
if not sys.argv[1:]:
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
|
# Zap .pyc files
import os
import sys
doit = 1
def main():
if os.name == 'mac':
import macfs
fss, ok = macfs.GetDirectory('Directory to zap pyc files in')
if not ok:
sys.exit(0)
dir = fss.as_pathname()
zappyc(dir)
else:
if not sys.argv[1:]:
print 'Usage: zappyc dir ...'
sys.exit(1)
for dir in sys.argv[1:]:
zappyc(dir)
def zappyc(dir):
os.path.walk(dir, walker, None)
def walker(dummy, top, names):
for name in names:
if name[-4:] == '.pyc':
path = os.path.join(top, name)
print 'Zapping', path
if doit:
os.unlink(path)
if __name__ == '__main__':
main()
|
Return the original function value for static methods, too
|
var is = require('core-util-is') // added in Node 0.12
/**
* Instrument an object or class so that anytime a method is invoked, it gets
* logged to the console.
*
* @param {function} constructor
*/
module.exports = function (constructor) {
Object.keys(constructor).forEach(function (methodName) {
if (!is.isFunction(constructor[methodName])) {
return
}
var originalMethod = constructor[methodName]
constructor[methodName] = function () {
var args = Array.prototype.slice.call(arguments)
console.log('Called: ' + methodName + '(' + args + ')')
return originalMethod.apply(null, args)
}
})
var proto = constructor.prototype
if (proto !== undefined) {
Object.keys(proto).forEach(function (methodName) {
var propDesc = Object.getOwnPropertyDescriptor(proto, methodName)
if (!propDesc.configurable || ('get' in propDesc) || ('set' in propDesc) ||
!is.isFunction(proto[methodName])) {
return
}
var originalMethod = proto[methodName]
proto[methodName] = function () {
var args = Array.prototype.slice.call(arguments)
console.log('Called: ' + methodName + '(' + args + ')')
return originalMethod.apply(this, args)
}
})
}
}
|
var is = require('core-util-is') // added in Node 0.12
/**
* Instrument an object or class so that anytime a method is invoked, it gets
* logged to the console.
*
* @param {function} constructor
*/
module.exports = function (constructor) {
Object.keys(constructor).forEach(function (methodName) {
if (!is.isFunction(constructor[methodName])) {
return
}
var originalMethod = constructor[methodName]
constructor[methodName] = function () {
var args = Array.prototype.slice.call(arguments)
console.log('Called: ' + methodName + '(' + args + ')')
originalMethod.apply(null, args)
}
})
var proto = constructor.prototype
if (proto !== undefined) {
Object.keys(proto).forEach(function (methodName) {
var propDesc = Object.getOwnPropertyDescriptor(proto, methodName)
if (!propDesc.configurable || ('get' in propDesc) || ('set' in propDesc) ||
!is.isFunction(proto[methodName])) {
return
}
var originalMethod = proto[methodName]
proto[methodName] = function () {
var args = Array.prototype.slice.call(arguments)
console.log('Called: ' + methodName + '(' + args + ')')
return originalMethod.apply(this, args)
}
})
}
}
|
Add error message if an id is not found in TaskStatus (should never happen)
|
package slave
import (
"fmt"
"github.com/aaronang/cong-the-ripper/lib"
)
func (s *Slave) addTask(task lib.Task) {
taskStatus := lib.TaskStatus{
Id: task.ID,
JobId: task.JobID,
Status: lib.Running,
Progress: task.Start,
}
s.heartbeat.TaskStatus = append(s.heartbeat.TaskStatus, taskStatus)
}
func (s *Slave) password_found(Id int, password string) {
fmt.Println("Found password: " + password)
ts := s.taskStatusWithId(Id)
if ts != nil {
ts.Status = lib.PasswordFound
ts.Password = password
} else {
fmt.Println("ERROR:", "Id not found in Taskstatus")
}
}
func (s *Slave) password_not_found(Id int) {
fmt.Println("Password not found")
ts := s.taskStatusWithId(Id)
if ts != nil {
ts.Status = lib.PasswordNotFound
} else {
fmt.Println("ERROR:", "Id not found in Taskstatus")
}
}
func (s *Slave) taskStatusWithId(Id int) *lib.TaskStatus {
for i, ts := range s.heartbeat.TaskStatus {
if ts.Id == Id {
return &s.heartbeat.TaskStatus[i]
}
}
return nil
}
|
package slave
import (
"fmt"
"github.com/aaronang/cong-the-ripper/lib"
)
func (s *Slave) addTask(task lib.Task) {
taskStatus := lib.TaskStatus{
Id: task.ID,
JobId: task.JobID,
Status: lib.Running,
Progress: task.Start,
}
s.heartbeat.TaskStatus = append(s.heartbeat.TaskStatus, taskStatus)
}
func (s *Slave) password_found(Id int, password string) {
fmt.Println("Found password: " + password)
ts := s.taskStatusWithId(Id)
if ts != nil {
ts.Status = lib.PasswordFound
ts.Password = password
}
}
func (s *Slave) password_not_found(Id int) {
fmt.Println("Password not found")
ts := s.taskStatusWithId(Id)
if ts != nil {
ts.Status = lib.PasswordNotFound
}
}
func (s *Slave) taskStatusWithId(Id int) *lib.TaskStatus {
for i, ts := range s.heartbeat.TaskStatus {
if ts.Id == Id {
return &s.heartbeat.TaskStatus[i]
}
}
return nil
}
|
Update proj4js from 2.4.4 to 2.5.0
|
/*******************************************************************************
* Copyright 2014, 2018 gwt-ol3
*
* 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 proj4;
import com.github.desjardins.gwt.junit.client.BaseTestCase;
/**
*
* @author Tino Desjardins
*
*/
public abstract class GwtProj4BaseTestCase extends BaseTestCase {
public GwtProj4BaseTestCase() {
super("https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js", "proj4.GwtProj4Test", 10000);
}
}
|
/*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* 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 proj4;
import com.github.desjardins.gwt.junit.client.BaseTestCase;
/**
*
* @author Tino Desjardins
*
*/
public abstract class GwtProj4BaseTestCase extends BaseTestCase {
public GwtProj4BaseTestCase() {
super("https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js", "proj4.GwtProj4Test", 10000);
}
}
|
Refactor the title into a getter method
|
import cuid from 'cuid';
import {database, auth} from '@/config/firebase';
export default function (post = {}) {
// Properties
this.id = post.id || cuid();
this.created = post.created || Date.now();
this.lastEdited = post.lastEdited || null;
this.lastSaved = post.lastSaved || null;
this.lastPublished = post.lastPublished || null;
this.author = post.author || auth.currentUser.uid;
this.published = post.published || false;
this.markdown = post.markdown || '';
this.images = post.images || [];
// Constants
const ref = database.ref(`/posts/${this.id}`);
/**
* Save the post to firebase
*/
this.set = () => {
this.lastSaved = Date.now();
return ref.set(JSON.parse(JSON.stringify(this))).then(snapshot => {
return snapshot;
});
};
/**
* Get the post title, first line starting with a single #
*/
Object.defineProperty(this, 'title', {
get() {
const title = this.markdown.match(/^# .+/gm);
return title ? title[0].replace('# ', '') : '';
},
});
}
|
import cuid from 'cuid';
import {database, auth} from '@/config/firebase';
export default function (post = {}) {
// Properties
this.id = post.id || cuid();
this.title = post.title || '';
this.created = post.created || Date.now();
this.lastEdited = post.lastEdited || null;
this.lastSaved = post.lastSaved || null;
this.lastPublished = post.lastPublished || null;
this.author = post.author || auth.currentUser.uid;
this.published = post.published || false;
this.markdown = post.markdown || '';
this.images = post.images || [];
const ref = database.ref(`/posts/${this.id}`);
// Methods
this.set = () => {
this.lastSaved = Date.now();
return ref.set(JSON.parse(JSON.stringify(this))).then(snapshot => {
return snapshot;
});
};
}
|
Add name to custom filter
|
<?php
/*
* Copyright 2016 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Filter\Rule;
use Coast\Filter\Rule;
class Custom extends Rule
{
protected $_func = [];
public function __construct(callable $func, $name = null)
{
$this->func($func);
$this->name($name);
}
public function func($func = null)
{
if (func_num_args() > 0) {
$this->_func = $func;
return $this;
}
return $this->_func;
}
protected function _filter($value)
{
$func = $this->_func;
return $func($value, $this);
}
}
|
<?php
/*
* Copyright 2016 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Filter\Rule;
use Coast\Filter\Rule;
class Custom extends Rule
{
protected $_func = [];
public function __construct(callable $func, $name = null)
{
$this->func($func);
}
public function func($func = null)
{
if (func_num_args() > 0) {
$this->_func = $func;
return $this;
}
return $this->_func;
}
protected function _filter($value)
{
$func = $this->_func;
return $func($value, $this);
}
}
|
Add bridge between Entry and User(which will be created on the next commit)
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance."""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
Make tests more resilient by using a better selector
|
module.exports = {
// get zero () { return browser.element('button*=0)'); },
get zero () { return browser.element('button*=0'); },
get one () { return browser.element('button*=1'); },
get two () { return browser.element('button*=2'); },
get three () { return browser.element('button*=3'); },
get four () { return browser.element('button*=4'); },
get five () { return browser.element('button*=5'); },
get six () { return browser.element('button*=6'); },
get seven () { return browser.element('button*=7'); },
get eight () { return browser.element('button*=8'); },
get nine () { return browser.element('button*=9'); },
get period () { return browser.element('button*=.'); },
get dividedBy () { return browser.element('button*=÷'); },
get times () { return browser.element('button*=×'); },
get minus () { return browser.element('button*=-'); },
get plus () { return browser.element('button*=+'); },
get equals () { return browser.element('button*=='); },
get responsePaneText () { return browser.getText('#response-pane'); },
}
|
module.exports = {
get zero () { return browser.element('.digits:nth-child(1)'); },
get one () { return browser.element('.digits:nth-child(2)'); },
get two () { return browser.element('.digits:nth-child(3)'); },
get three () { return browser.element('.digits:nth-child(4)'); },
get four () { return browser.element('.digits:nth-child(5)'); },
get five () { return browser.element('.digits:nth-child(6)'); },
get six () { return browser.element('.digits:nth-child(7)'); },
get seven () { return browser.element('.digits:nth-child(8)'); },
get eight () { return browser.element('.digits:nth-child(9)'); },
get nine () { return browser.element('.digits:nth-child(10)'); },
get period () { return browser.element('.digits:nth-child(11)'); },
get dividedBy () { return browser.element('.operations:nth-child(1)'); },
get times () { return browser.element('.operations:nth-child(2)'); },
get minus () { return browser.element('.operations:nth-child(3)'); },
get plus () { return browser.element('.operations:nth-child(4)'); },
get equals () { return browser.element('.operations:nth-child(5)'); },
get responsePaneText () { return browser.getText('#response-pane'); },
}
|
Set desired qt version explicitly in run_quince.py
|
#!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
# Use PyQt5 by default
import os
os.environ["QT_API"] = 'pyqt5'
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import *
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--measFile', type=str, help='Measurement Library File')
parser.add_argument('-s', '--sweepFile', type=str, help='Sweep Library File')
parser.add_argument('-i', '--instrFile', type=str, help='Instrument Library File')
args = parser.parse_args()
print(args.instrFile)
app = QApplication([])
window = NodeWindow()
window.load_pyqlab(measFile=args.measFile, sweepFile=args.sweepFile, instrFile=args.instrFile)
app.aboutToQuit.connect(window.cleanup)
window.show()
sys.exit(app.exec_())
|
#!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import *
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--measFile', type=str, help='Measurement Library File')
parser.add_argument('-s', '--sweepFile', type=str, help='Sweep Library File')
parser.add_argument('-i', '--instrFile', type=str, help='Instrument Library File')
args = parser.parse_args()
print(args.instrFile)
app = QApplication([])
window = NodeWindow()
window.load_pyqlab(measFile=args.measFile, sweepFile=args.sweepFile, instrFile=args.instrFile)
app.aboutToQuit.connect(window.cleanup)
window.show()
sys.exit(app.exec_())
|
Comment out old demos for now.
|
/// <reference path="../typings/angularjs/angular.d.ts"/>
angular.module('MyModule', ['ngRoute']);
angular.module('MyModule').config(function ($routeProvider) {
$routeProvider.when("/main", {
controller: "maincontroller",
templateUrl: "app/views/main.html"
});
// $routeProvider.when("/collisions", {
// controller: "collisioncontroller",
// templateUrl: "app/views/shapes.html"
// });
//
// $routeProvider.when("/velocity", {
// controller: "velocitycontroller",
// templateUrl: "app/views/shapes.html"
// });
$routeProvider.when("/ballpit", {
controller: "ballpitcontroller",
templateUrl: "app/views/ballpit.html"
});
$routeProvider.when("/facing", {
controller: "facingcontroller",
templateUrl: "app/views/facing.html"
});
$routeProvider.when("/follow", {
controller: "followcontroller",
templateUrl: "app/views/follow.html"
});
$routeProvider.when("/flock", {
controller: "flockcontroller",
templateUrl: "app/views/flock.html"
});
$routeProvider.otherwise({ redirectTo: "/follow" });
});
|
/// <reference path="../typings/angularjs/angular.d.ts"/>
angular.module('MyModule', ['ngRoute']);
angular.module('MyModule').config(function ($routeProvider) {
$routeProvider.when("/main", {
controller: "maincontroller",
templateUrl: "app/views/main.html"
});
$routeProvider.when("/collisions", {
controller: "collisioncontroller",
templateUrl: "app/views/shapes.html"
});
$routeProvider.when("/velocity", {
controller: "velocitycontroller",
templateUrl: "app/views/shapes.html"
});
$routeProvider.when("/ballpit", {
controller: "ballpitcontroller",
templateUrl: "app/views/ballpit.html"
});
$routeProvider.when("/facing", {
controller: "facingcontroller",
templateUrl: "app/views/facing.html"
});
$routeProvider.when("/follow", {
controller: "followcontroller",
templateUrl: "app/views/follow.html"
});
$routeProvider.when("/flock", {
controller: "flockcontroller",
templateUrl: "app/views/flock.html"
});
$routeProvider.otherwise({ redirectTo: "/follow" });
});
|
[schema] Validate that type name is a string
|
import leven from 'leven'
import humanize from 'humanize-list'
import {error, HELP_IDS} from '../createValidationResult'
const quote = str => `"${str}"`
export function validateTypeName(typeName: string, visitorContext) {
const possibleTypeNames = visitorContext.getTypeNames()
if (!typeName) {
return [
error(`Type is missing a type. Valid types are: ${humanize(possibleTypeNames)}`,
HELP_IDS.TYPE_MISSING_TYPE)
]
}
if (typeof typeName !== 'string') {
return [
error(`Type has an invalid "type"-property - should be a string. Valid types are: ${humanize(possibleTypeNames)}`,
HELP_IDS.TYPE_MISSING_TYPE)
]
}
const isValid = possibleTypeNames.includes(typeName)
if (!isValid) {
const suggestions = possibleTypeNames
.map(possibleTypeName => {
if (!possibleTypeName || !typeName) {
}
return [leven(typeName, possibleTypeName), possibleTypeName]
})
.filter(([distance]) => distance < 3)
.map(([_, name]) => name)
const suggestion = suggestions.length > 0 ? ` Did you mean ${humanize(suggestions.map(quote), {conjunction: 'or'})}?` : ''
return [
error(
`Unknown type: ${typeName}.${suggestion} Valid types are: ${humanize(possibleTypeNames)}`
)
]
}
return []
}
|
import leven from 'leven'
import humanize from 'humanize-list'
import {error, HELP_IDS} from '../createValidationResult'
const quote = str => `"${str}"`
export function validateTypeName(typeName: string, visitorContext) {
const possibleTypeNames = visitorContext.getTypeNames()
if (!typeName) {
return [
error(`Type is missing a type. Valid types are: ${humanize(possibleTypeNames)}`,
HELP_IDS.TYPE_MISSING_TYPE)
]
}
const isValid = possibleTypeNames.includes(typeName)
if (!isValid) {
const suggestions = possibleTypeNames
.map(possibleTypeName => {
if (!possibleTypeName || !typeName) {
}
return [leven(typeName, possibleTypeName), possibleTypeName]
})
.filter(([distance]) => distance < 3)
.map(([_, name]) => name)
const suggestion = suggestions.length > 0 ? ` Did you mean ${humanize(suggestions.map(quote), {conjunction: 'or'})}?` : ''
return [
error(
`Unknown type: ${typeName}.${suggestion} Valid types are: ${humanize(possibleTypeNames)}`
)
]
}
return []
}
|
Fix buildpack typo to buildpacks
|
exports.topics = [
{ name: 'apps', description: 'manage apps' },
{ name: 'info', hidden: true, },
{ name: 'maintenance', description: 'manage maintenance mode for an app' },
{ name: 'stack', description: 'manage the stack for an app' },
{ name: 'buildpacks', description: 'manage the buildpacks for an app' },
];
exports.commands = [
require('./commands/apps/info').apps,
require('./commands/apps/info').root,
require('./commands/maintenance/index'),
require('./commands/maintenance/off'),
require('./commands/maintenance/on'),
require('./commands/stack'),
require('./commands/stack/set'),
require('./commands/buildpacks'),
require('./commands/buildpacks/add.js'),
require('./commands/buildpacks/set.js'),
require('./commands/buildpacks/clear.js'),
require('./commands/buildpacks/remove.js'),
];
|
exports.topics = [
{ name: 'apps', description: 'manage apps' },
{ name: 'info', hidden: true, },
{ name: 'maintenance', description: 'manage maintenance mode for an app' },
{ name: 'stack', description: 'manage the stack for an app' },
{ name: 'buildpacks', description: 'manage the buildpack for an app' },
];
exports.commands = [
require('./commands/apps/info').apps,
require('./commands/apps/info').root,
require('./commands/maintenance/index'),
require('./commands/maintenance/off'),
require('./commands/maintenance/on'),
require('./commands/stack'),
require('./commands/stack/set'),
require('./commands/buildpacks'),
require('./commands/buildpacks/add.js'),
require('./commands/buildpacks/set.js'),
require('./commands/buildpacks/clear.js'),
require('./commands/buildpacks/remove.js'),
];
|
Make sure we use an accessor rather than a private var for overriding
|
package ca.uhnresearch.pughlab.tracker.restlets;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Status;
import org.restlet.routing.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultingFilter extends Filter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private String defaultPath = "/index.html";
public DefaultingFilter(Context context, Restlet next) {
super(context, next);
}
@Override
protected int doHandle (Request request, Response response) {
logger.debug("doHandle FILTER: " + request.getResourceRef().getPath());
int result = super.doHandle(request, response);
if (response.getStatus().equals(Status.CLIENT_ERROR_NOT_FOUND)) {
response.setStatus(Status.SUCCESS_OK);
String path = request.getResourceRef().getPath();
if (! getDefaultPath().equals(path)) {
request.getResourceRef().setPath(getDefaultPath());
result = super.doHandle(request, response);
}
}
return result;
}
/**
* @return the defaultPath
*/
public String getDefaultPath() {
return defaultPath;
}
/**
* @param rewrites the defaultPath to set
*/
public void setDefaultPath(String defaultPath) {
this.defaultPath = defaultPath;
}
}
|
package ca.uhnresearch.pughlab.tracker.restlets;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Status;
import org.restlet.routing.Filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultingFilter extends Filter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private String defaultPath = "/index.html";
public DefaultingFilter(Context context, Restlet next) {
super(context, next);
}
@Override
protected int doHandle (Request request, Response response) {
logger.debug("doHandle FILTER: " + request.getResourceRef().getPath());
int result = super.doHandle(request, response);
if (response.getStatus().equals(Status.CLIENT_ERROR_NOT_FOUND)) {
response.setStatus(Status.SUCCESS_OK);
String path = request.getResourceRef().getPath();
if (! defaultPath.equals(path)) {
request.getResourceRef().setPath(defaultPath);
result = super.doHandle(request, response);
}
}
return result;
}
/**
* @return the defaultPath
*/
public String getDefaultPath() {
return defaultPath;
}
/**
* @param rewrites the defaultPath to set
*/
public void setDefaultPath(String defaultPath) {
this.defaultPath = defaultPath;
}
}
|
Remove server name and port
|
$(function() {
var s = io.connect('/');
s.on("connect", function () {
console.log("connected");
});
s.on("disconnect", function (client) {
console.log("disconnected");
});
s.on("receive_stdout", function (data) {
$("pre#stdout").append(data.value);
// var msg = value.replace( /[!@$%<>'"&|]/g, '' ); //タグ記号とかいくつか削除
});
s.on("receive_stderr", function (data) {
$("pre#stderr").append(data.value);
});
s.on("receive_exit", function (data) {
$("#running-now").hide();
$("div.alert-success").fadeIn("slow");
});
$("#start").click(function() {
var name = $("input#name").val();
if (name == "") {
$("div.input-warning").fadeIn();
return;
}
$("div.input-warning").hide();
$("div.alert-success").hide();
$("pre#stdout").text("");
$("pre#stderr").text("");
$("#running-now").fadeIn("slow");
s.emit("run", { value: name });
});
});
|
$(function() {
var s = io.connect('http://localhost:3000');
s.on("connect", function () {
console.log("connected");
});
s.on("disconnect", function (client) {
console.log("disconnected");
});
s.on("receive_stdout", function (data) {
$("pre#stdout").append(data.value);
// var msg = value.replace( /[!@$%<>'"&|]/g, '' ); //タグ記号とかいくつか削除
});
s.on("receive_stderr", function (data) {
$("pre#stderr").append(data.value);
});
s.on("receive_exit", function (data) {
$("#running-now").hide();
$("div.alert-success").fadeIn("slow");
});
$("#start").click(function() {
var name = $("input#name").val();
if (name == "") {
$("div.input-warning").fadeIn();
return;
}
$("div.input-warning").hide();
$("div.alert-success").hide();
$("pre#stdout").text("");
$("pre#stderr").text("");
$("#running-now").fadeIn("slow");
s.emit("run", { value: name });
});
});
|
Put the calculated value on the right
|
from tests.base_case import ChatBotMongoTestCase
class RepetitiveResponseFilterTestCase(ChatBotMongoTestCase):
"""
Test case for the RepetitiveResponseFilter class.
"""
def test_filter_selection(self):
"""
Test that repetitive responses are filtered out of the results.
"""
from chatterbot.filters import RepetitiveResponseFilter
from chatterbot.trainers import ListTrainer
self.chatbot.filters = (RepetitiveResponseFilter(), )
self.chatbot.set_trainer(ListTrainer, **self.get_kwargs())
self.chatbot.train([
'Hello',
'Hi',
'Hello',
'Hi',
'Hello',
'Hi, how are you?',
'I am good.'
])
first_response = self.chatbot.get_response('Hello')
second_response = self.chatbot.get_response('Hello')
self.assertEqual('Hi', first_response.text)
self.assertEqual('Hi, how are you?', second_response.text)
|
from tests.base_case import ChatBotMongoTestCase
class RepetitiveResponseFilterTestCase(ChatBotMongoTestCase):
"""
Test case for the RepetitiveResponseFilter class.
"""
def test_filter_selection(self):
"""
Test that repetitive responses are filtered out of the results.
"""
from chatterbot.filters import RepetitiveResponseFilter
from chatterbot.trainers import ListTrainer
self.chatbot.filters = (RepetitiveResponseFilter(), )
self.chatbot.set_trainer(ListTrainer, **self.get_kwargs())
self.chatbot.train([
'Hello',
'Hi',
'Hello',
'Hi',
'Hello',
'Hi, how are you?',
'I am good.'
])
first_response = self.chatbot.get_response('Hello')
second_response = self.chatbot.get_response('Hello')
self.assertEqual(first_response.text, 'Hi')
self.assertEqual(second_response.text, 'Hi, how are you?')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.